// page init
jQuery(function () {
    initPopupRemove();
    initDrop();
    initCycleCarousel();
    initFormValidation();
    initSlickslider();
    initSameHeight();
    initCarousel();
    initLightbox();
    initAddClassOnResize();
    initZoom();
    initCustomForms();
    //intTooltip();
    initAccordion();
    initAnchors();
    //initLoadMore();
    initMobileNav();
    initLayoutFix();
    initPrint();
    initAutocomplete();
});


function initAutocomplete() {
    jQuery('[data-autocomplete]').uiAutocomplete();
}

function initPopupRemove() {
    jQuery(document).on('click', 'a.close', function () {
        jQuery(this).parent().addClass('is-hidden');
    });
}

function initPrint() {
    jQuery(document).on('click', 'a.print', function() {
        window.print();
    });
}

function initLayoutFix() {
    jQuery('div.modal').on('shown.bs.modal hidden.bs.modal', function () {
        jQuery(this).removeAttr('style');
        jQuery(window).trigger('resize');
    });
}

// mobile menu init
function initMobileNav() {
    jQuery('body').mobileNav({
        menuActiveClass: 'filter-active',
        menuOpener: '.filter-control'
    });
}

// load more init
//function initLoadMore() {
//    jQuery('.load-more-holder').loadMore({
//        linkSelector: '.load-more',
//        additionBottomOffset: 50
//    });
//}


// initialize custom form elements
function initCustomForms() {
    jcf.setOptions('Select', {
        wrapNative: false
    });
    jcf.replaceAll();
}

// initialize bootstrap tooltip
function intTooltip() {
    $('[data-toggle="tooltip"]').tooltip();
}

// accordion menu init
function initAccordion() {
    jQuery('.accordion').slideAccordion({
        opener: 'a.opener',
        slider: '.slide',
        animSpeed: 300
    });
}

// initialize smooth anchor links
function initAnchors() {
    new SmoothScroll({
        anchorLinks: '.smooth-scroll'
    });
}


function initAddClassOnResize() {
    var win = jQuery(window),
		doc = jQuery('html'),
		resizeClass = 'resize-active',
		flag, timer;
    var removeClassHandler = function () {
        flag = false;
        doc.removeClass(resizeClass);
    };
    var resizeHandler = function () {
        if (!flag) {
            flag = true;
            doc.addClass(resizeClass);
        }
        clearTimeout(timer);
        timer = setTimeout(removeClassHandler, 500);
    };
    win.on('resize orientationchange', resizeHandler);
}

function initZoom() {
    var win = jQuery(window);
    jQuery('.product-detail-wrap .main-img').not("#video").each(function () {
        var block = jQuery(this);
        var init = function () {
            block.zoomer({
                marginMin: 10,
                marginMax: 100
            });
        };
        var destroy = function () {
            block.zoomer('destroy');
        };
        var resizeHanlder = function () {
            if (win.width() > 767 && !block.hasClass('zoomer-element')) {
                init();
            }
            if (win.width() <= 767 && block.hasClass('zoomer-element')) {
                destroy();
            }
        };
        resizeHanlder();
        win.on('resize load orientationchange', resizeHanlder);
    });
}

function initDrop() {
    var page = jQuery('body');
    var activeClass = 'active';
    var hiddenClass = 'hidden-level';
    var activeMenuClass = 'nav-active';
    var header = jQuery('#header');
    var items = header.find('li:has(> div):not(:has(> .subnav-drop))');
    var nav = header.find('#nav');
    var isTouchDevice = /Windows Phone/.test(navigator.userAgent) || ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
    var outsideClickHandler = function (e) {
        var target = jQuery(e.target);
        if (!target.closest('#header').length && page.hasClass(activeMenuClass)) {
            page.removeClass(activeMenuClass);
            header.find('li').removeClass(activeClass).removeClass(hiddenClass);
        }
    };
    var togglePageClass = function () {
        if (items.filter('.' + activeClass).length) {
            page.addClass(activeMenuClass);
        } else {
            page.removeClass(activeMenuClass);
            items.removeClass(activeClass);
        }
    };
    var toggleNav = function (e) {
        e.preventDefault();
        page.toggleClass(activeMenuClass);
    };
    var toggleSubLevel = function (e) {
        e.preventDefault();
        var link = jQuery(this);
        var item = link.parent();
        var holder = item.closest('.sub-drop');
        var drop = link.siblings();
        item.toggleClass(activeClass);
        if (item.hasClass(activeClass)) {
            drop.stop(true, false).slideDown('slow');
        } else {
            drop.stop(true, false).slideUp('slow', function () {
                drop.removeAttr('style');
            });
        }
        holder.find('.subnav > li').not(item).removeClass(activeClass).find('> div').slideUp('slow', function () {
            jQuery(this).removeAttr('style');
        });
    };
    var closeDrop = function (e) {
        if (e) e.preventDefault();
        var item = jQuery(this).closest('.' + activeClass);
        if (!item.closest('.' + activeClass).length) {
            page.removeClass(activeMenuClass);
            items.removeClass(activeClass).removeClass(hiddenClass);
        }

        if (item.closest('.flyout').length) {
            page.removeClass(activeMenuClass);
            items.removeClass(activeClass).removeClass(hiddenClass);
        }
        if (window.innerWidth >= 768 && !isTouchDevice) {
            page.removeClass(activeMenuClass);
        }
        item.removeClass(activeClass);
        item.siblings().removeClass(hiddenClass);
    };
    //to close the whole nav from sub menue
    var hardCloseNav=function(e)
    {
        if (e) e.preventDefault();
        var item = $(this).closest('.' + activeClass);
        page.removeClass(activeMenuClass);
        items.removeClass(activeClass).removeClass(hiddenClass);
        item.removeClass(activeClass);
        item.siblings().removeClass(hiddenClass);
    };
    var showDrop = function (e) {
        if (e) e.preventDefault();
        var item = jQuery(this).parent();
        item.addClass(activeClass).removeClass(hiddenClass);
        item.siblings().addClass(hiddenClass).removeClass(activeClass);
        if (window.innerWidth >= 992) {
            item.children(".sub-drop").css("top", item.position().top);
        }
      
        togglePageClass();
    };
    var hideDrop = function (e) {
        if (e) e.preventDefault();
        jQuery(this).addClass(hiddenClass).removeClass(activeClass);
        togglePageClass();
    };
    // toggle page nav
    header.on('click', '.nav-opener, .menu-close', toggleNav);
    // open current level
    // items.on('click', '> a', showDrop);
    items.on('click', '> a', function (e) {
        e.preventDefault();
        var item = jQuery(this).parent();
        if (item.hasClass(activeClass)) {
            closeDrop.apply(this);
        } else {
            showDrop.apply(this);
        }
    });
    if (!isTouchDevice && window.innerWidth > 1024) {
        items.filter('.category-nav li').on('mouseenter', '> a', showDrop);
        items.filter('.category-nav li').on('mouseleave', hideDrop);
    }
    // close current level
    header.on('click', '.nav-close', closeDrop);
    $('.nav-hard-close').click(hardCloseNav);
    // sub drops
    header.on('click', '.sub-drop .subnav-opener', toggleSubLevel);
    // close by click outside
    jQuery(document).on('click', outsideClickHandler);
}

// align blocks height
function initSameHeight() {
    jQuery('.same-height').sameHeight({
        elements: '.height',
        flexible: true,
        multiLine: true
    });
}

// scroll gallery init
function initCarousel() {
    jQuery('.carousel').scrollGallery({
        mask: '.mask1',
        slider: '.slideset1',
        slides: '.slide1',
        btnPrev: 'a.btn-prev',
        btnNext: 'a.btn-next',
        generatePagination: '.pagination-links',
        disableWhileAnimating: true,
        autoRotation: false,
        switchTime: 3000,
        animSpeed: 500,
        maskAutoSize: true,
        step: 1
    });
}

// cycle scroll gallery init
function initCycleCarousel() {
    jQuery('.hero-banner').scrollAbsoluteGallery({
        mask: '.mask',
        slider: '.slideset',
        slides: '.slide',
        btnPrev: 'a.btn-prev',
        btnNext: 'a.btn-next',
        pagerLinks: '.banner-nav li',
        stretchSlideToMask: true,
        pauseOnHover: true,
        maskAutoSize: true,
        autoRotation: true,
        switchTime: 5000,
        animSpeed: 500
    });

    jQuery('.prduct-detail-slide').scrollAbsoluteGallery({
        mask: '.mask',
        slider: '.slideset',
        slides: '.slide',
        btnPrev: 'a.btn-prev1',
        btnNext: 'a.btn-next1',
        pagerLinks: '.product-slide-nav .slide1',
        stretchSlideToMask: true,
        pauseOnHover: true,
        maskAutoSize: true,
        autoRotation: false,
        switchTime: 3000,
        animSpeed: 500
    });
}

function initFormValidation() {
    jQuery('.form-validation').formValidation({
        errorClass: 'input-error',
        addClassToParent: '.form-group'
    });
}

// slick slider
function initSlickslider() {
    jQuery(".slick-slider").slick({
        infinite: true,
        centerMode: false,
        slidesToShow: 3,
        prevArrow: '<a href="#" class="btn-prev"><i aria-hidden="true" class="fa fa-angle-left"></i><span class="sr-only">Previous</span></a>',
        nextArrow: '<a href="#" class="btn-next"><i aria-hidden="true" class="fa fa-angle-right"></i><span class="sr-only">Next</span></a>',
        arrows: true,
        slidesToScroll: 1,
        variableWidth: true,
        responsive: [
          {
              breakpoint: 992,
              settings: {
                  centerPadding: '10px',
                  slidesToShow: 3
              }
          },
          {
              breakpoint: 640,
              settings: {
                  centerPadding: '10px',
                  slidesToShow: 2
              }
          },
          {
              breakpoint: 480,
              settings: {
                  centerPadding: '10px',
                  slidesToShow: 1
              }
          }
        ]
    });

    jQuery(".gift-cards-slide").slick({
        infinite: true,
        centerMode: false,
        slidesToShow: 3,
        prevArrow: '<a href="#" class="btn-prev"><i aria-hidden="true" class="icon-arrow-left"></i><span class="sr-only">Previous</span></a>',
        nextArrow: '<a href="#" class="btn-next"><i aria-hidden="true" class="icon-arrow-right"></i><span class="sr-only">Next</span></a>',
        arrows: true,
        slidesToScroll: 1,
        variableWidth: true,
        responsive: [
          {
              breakpoint: 992,
              settings: {
                  slidesToShow: 3
              }
          },
          {
              breakpoint: 768,
              settings: {
                  variableWidth: false,
                  slidesToShow: 2
              }
          }
        ]
    });
}

/*
 * jQuery Cycle Carousel plugin
 */
; (function ($) {
    function ScrollAbsoluteGallery(options) {
        this.options = $.extend({
            activeClass: 'active',
            mask: 'div.slides-mask',
            slider: '>ul',
            slides: '>li',
            btnPrev: '.btn-prev',
            btnNext: '.btn-next',
            pagerLinks: 'ul.pager > li',
            generatePagination: false,
            pagerList: '<ul>',
            pagerListItem: '<li><a href="#"></a></li>',
            pagerListItemText: 'a',
            galleryReadyClass: 'gallery-js-ready',
            currentNumber: 'span.current-num',
            totalNumber: 'span.total-num',
            maskAutoSize: false,
            autoRotation: false,
            pauseOnHover: false,
            stretchSlideToMask: false,
            switchTime: 3000,
            animSpeed: 500,
            handleTouch: true,
            swipeThreshold: 15,
            vertical: false
        }, options);
        this.init();
    }
    ScrollAbsoluteGallery.prototype = {
        init: function () {
            if (this.options.holder) {
                this.findElements();
                this.attachEvents();
                this.makeCallback('onInit', this);
            }
        },
        findElements: function () {
            // find structure elements
            this.holder = $(this.options.holder).addClass(this.options.galleryReadyClass);
            this.mask = this.holder.find(this.options.mask);
            this.slider = this.mask.find(this.options.slider);
            this.slides = this.slider.find(this.options.slides);
            this.btnPrev = this.holder.find(this.options.btnPrev);
            this.btnNext = this.holder.find(this.options.btnNext);

            // slide count display
            this.currentNumber = this.holder.find(this.options.currentNumber);
            this.totalNumber = this.holder.find(this.options.totalNumber);

            // create gallery pagination
            if (typeof this.options.generatePagination === 'string') {
                this.pagerLinks = this.buildPagination();
            } else {
                this.pagerLinks = this.holder.find(this.options.pagerLinks);
            }

            // define index variables
            this.sizeProperty = this.options.vertical ? 'height' : 'width';
            this.positionProperty = this.options.vertical ? 'top' : 'left';
            this.animProperty = this.options.vertical ? 'marginTop' : 'marginLeft';

            this.slideSize = this.slides[this.sizeProperty]();
            this.currentIndex = 0;
            this.prevIndex = 0;

            // reposition elements
            this.options.maskAutoSize = this.options.vertical ? false : this.options.maskAutoSize;
            if (this.options.vertical) {
                this.mask.css({
                    height: this.slides.innerHeight()
                });
            }
            if (this.options.maskAutoSize) {
                this.mask.css({
                    height: this.slider.height()
                });
            }
            this.slider.css({
                position: 'relative',
                height: this.options.vertical ? this.slideSize * this.slides.length : '100%'
            });
            this.slides.css({
                position: 'absolute'
            }).css(this.positionProperty, -9999).eq(this.currentIndex).css(this.positionProperty, 0);
            this.refreshState();
        },
        buildPagination: function () {
            var pagerLinks = $();
            if (!this.pagerHolder) {
                this.pagerHolder = this.holder.find(this.options.generatePagination);
            }
            if (this.pagerHolder.length) {
                this.pagerHolder.empty();
                this.pagerList = $(this.options.pagerList).appendTo(this.pagerHolder);
                for (var i = 0; i < this.slides.length; i++) {
                    $(this.options.pagerListItem).appendTo(this.pagerList).find(this.options.pagerListItemText).text(i + 1);
                }
                pagerLinks = this.pagerList.children();
            }
            return pagerLinks;
        },
        attachEvents: function () {
            // attach handlers
            var self = this;
            if (this.btnPrev.length) {
                this.btnPrevHandler = function (e) {
                    e.preventDefault();
                    self.prevSlide();
                };
                this.btnPrev.click(this.btnPrevHandler);
            }
            if (this.btnNext.length) {
                this.btnNextHandler = function (e) {
                    e.preventDefault();
                    self.nextSlide();
                };
                this.btnNext.click(this.btnNextHandler);
            }
            if (this.pagerLinks.length) {
                this.pagerLinksHandler = function (e) {
                    e.preventDefault();
                    self.numSlide(self.pagerLinks.index(e.currentTarget));
                };
                this.pagerLinks.click(this.pagerLinksHandler);
            }

            // handle autorotation pause on hover
            if (this.options.pauseOnHover) {
                this.hoverHandler = function () {
                    clearTimeout(self.timer);
                };
                this.leaveHandler = function () {
                    self.autoRotate();
                };
                this.holder.bind({ mouseenter: this.hoverHandler, mouseleave: this.leaveHandler });
            }

            // handle holder and slides dimensions
            this.resizeHandler = function () {
                if (!self.animating) {
                    if (self.options.stretchSlideToMask) {
                        self.resizeSlides();
                    }
                    self.resizeHolder();
                    self.setSlidesPosition(self.currentIndex);
                }
            };
            $(window).bind('load resize orientationchange', this.resizeHandler);
            if (self.options.stretchSlideToMask) {
                self.resizeSlides();
            }

            // handle swipe on mobile devices
            if (this.options.handleTouch && window.Hammer && this.mask.length && this.slides.length > 1 && isTouchDevice) {
                this.swipeHandler = new Hammer.Manager(this.mask[0]);
                this.swipeHandler.add(new Hammer.Pan({
                    direction: self.options.vertical ? Hammer.DIRECTION_VERTICAL : Hammer.DIRECTION_HORIZONTAL,
                    threshold: self.options.swipeThreshold
                }));

                this.swipeHandler.on('panstart', function () {
                    if (self.animating) {
                        self.swipeHandler.stop();
                    } else {
                        clearTimeout(self.timer);
                    }
                }).on('panmove', function (e) {
                    self.swipeOffset = -self.slideSize + e[self.options.vertical ? 'deltaY' : 'deltaX'];
                    self.slider.css(self.animProperty, self.swipeOffset);
                    clearTimeout(self.timer);
                }).on('panend', function (e) {
                    if (e.distance > self.options.swipeThreshold) {
                        if (e.offsetDirection === Hammer.DIRECTION_RIGHT || e.offsetDirection === Hammer.DIRECTION_DOWN) {
                            self.nextSlide();
                        } else {
                            self.prevSlide();
                        }
                    } else {
                        var tmpObj = {};
                        tmpObj[self.animProperty] = -self.slideSize;
                        self.slider.animate(tmpObj, { duration: self.options.animSpeed });
                        self.autoRotate();
                    }
                    self.swipeOffset = 0;
                });
            }

            // start autorotation
            this.autoRotate();
            this.resizeHolder();
            this.setSlidesPosition(this.currentIndex);
        },
        resizeSlides: function () {
            this.slideSize = this.mask[this.options.vertical ? 'height' : 'width']();
            this.slides.css(this.sizeProperty, this.slideSize);
        },
        resizeHolder: function () {
            if (this.options.maskAutoSize) {
                this.mask.css({
                    height: this.slides.eq(this.currentIndex).outerHeight(true)
                });
            }
        },
        prevSlide: function () {
            if (!this.animating && this.slides.length > 1) {
                this.direction = -1;
                this.prevIndex = this.currentIndex;
                if (this.currentIndex > 0) this.currentIndex--;
                else this.currentIndex = this.slides.length - 1;
                this.switchSlide();
            }
        },
        nextSlide: function (fromAutoRotation) {
            if (!this.animating && this.slides.length > 1) {
                this.direction = 1;
                this.prevIndex = this.currentIndex;
                if (this.currentIndex < this.slides.length - 1) this.currentIndex++;
                else this.currentIndex = 0;
                this.switchSlide();
            }
        },
        numSlide: function (c) {
            if (!this.animating && this.currentIndex !== c && this.slides.length > 1) {
                this.direction = c > this.currentIndex ? 1 : -1;
                this.prevIndex = this.currentIndex;
                this.currentIndex = c;
                this.switchSlide();
            }
        },
        preparePosition: function () {
            // prepare slides position before animation
            this.setSlidesPosition(this.prevIndex, this.direction < 0 ? this.currentIndex : null, this.direction > 0 ? this.currentIndex : null, this.direction);
        },
        setSlidesPosition: function (index, slideLeft, slideRight, direction) {
            // reposition holder and nearest slides
            if (this.slides.length > 1) {
                var prevIndex = (typeof slideLeft === 'number' ? slideLeft : index > 0 ? index - 1 : this.slides.length - 1);
                var nextIndex = (typeof slideRight === 'number' ? slideRight : index < this.slides.length - 1 ? index + 1 : 0);

                this.slider.css(this.animProperty, this.swipeOffset ? this.swipeOffset : -this.slideSize);
                this.slides.css(this.positionProperty, -9999).eq(index).css(this.positionProperty, this.slideSize);
                if (prevIndex === nextIndex && typeof direction === 'number') {
                    var calcOffset = direction > 0 ? this.slideSize * 2 : 0;
                    this.slides.eq(nextIndex).css(this.positionProperty, calcOffset);
                } else {
                    this.slides.eq(prevIndex).css(this.positionProperty, 0);
                    this.slides.eq(nextIndex).css(this.positionProperty, this.slideSize * 2);
                }
            }
        },
        switchSlide: function () {
            // prepare positions and calculate offset
            var self = this;
            var oldSlide = this.slides.eq(this.prevIndex);
            var newSlide = this.slides.eq(this.currentIndex);
            this.animating = true;

            // resize mask to fit slide
            if (this.options.maskAutoSize) {
                this.mask.animate({
                    height: newSlide.outerHeight(true)
                }, {
                    duration: this.options.animSpeed
                });
            }

            // start animation
            var animProps = {};
            animProps[this.animProperty] = this.direction > 0 ? -this.slideSize * 2 : 0;
            this.preparePosition();
            this.slider.animate(animProps, {
                duration: this.options.animSpeed, complete: function () {
                    self.setSlidesPosition(self.currentIndex);

                    // start autorotation
                    self.animating = false;
                    self.autoRotate();

                    // onchange callback
                    self.makeCallback('onChange', self);
                }
            });

            // refresh classes
            this.refreshState();

            // onchange callback
            this.makeCallback('onBeforeChange', this);
        },
        refreshState: function (initial) {
            // slide change function
            this.slides.removeClass(this.options.activeClass).eq(this.currentIndex).addClass(this.options.activeClass);
            this.pagerLinks.removeClass(this.options.activeClass).eq(this.currentIndex).addClass(this.options.activeClass);

            // display current slide number
            this.currentNumber.html(this.currentIndex + 1);
            this.totalNumber.html(this.slides.length);

            // add class if not enough slides
            this.holder.toggleClass('not-enough-slides', this.slides.length === 1);
        },
        autoRotate: function () {
            var self = this;
            clearTimeout(this.timer);
            if (this.options.autoRotation) {
                this.timer = setTimeout(function () {
                    self.nextSlide();
                }, this.options.switchTime);
            }
        },
        makeCallback: function (name) {
            if (typeof this.options[name] === 'function') {
                var args = Array.prototype.slice.call(arguments);
                args.shift();
                this.options[name].apply(this, args);
            }
        },
        destroy: function () {
            // destroy handler
            this.btnPrev.unbind('click', this.btnPrevHandler);
            this.btnNext.unbind('click', this.btnNextHandler);
            this.pagerLinks.unbind('click', this.pagerLinksHandler);
            this.holder.unbind('mouseenter', this.hoverHandler);
            this.holder.unbind('mouseleave', this.leaveHandler);
            $(window).unbind('load resize orientationchange', this.resizeHandler);
            clearTimeout(this.timer);

            // destroy swipe handler
            if (this.swipeHandler) {
                this.swipeHandler.destroy();
            }

            // remove inline styles, classes and pagination
            this.holder.removeClass(this.options.galleryReadyClass);
            this.slider.add(this.slides).removeAttr('style');
            if (typeof this.options.generatePagination === 'string') {
                this.pagerHolder.empty();
            }
        }
    };

    // detect device type
    var isTouchDevice = /Windows Phone/.test(navigator.userAgent) || ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;

    // jquery plugin
    $.fn.scrollAbsoluteGallery = function (opt) {
        return this.each(function () {
            $(this).data('ScrollAbsoluteGallery', new ScrollAbsoluteGallery($.extend(opt, { holder: this })));
        });
    };
}(jQuery));


/*!
 * JavaScript Custom Forms
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
; (function (root, factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory(require('jquery'));
    } else {
        root.jcf = factory(jQuery);
    }
}(this, function ($) {
    'use strict';

    // define version
    var version = '1.1.3';

    // private variables
    var customInstances = [];

    // default global options
    var commonOptions = {
        optionsKey: 'jcf',
        dataKey: 'jcf-instance',
        rtlClass: 'jcf-rtl',
        focusClass: 'jcf-focus',
        pressedClass: 'jcf-pressed',
        disabledClass: 'jcf-disabled',
        hiddenClass: 'jcf-hidden',
        resetAppearanceClass: 'jcf-reset-appearance',
        unselectableClass: 'jcf-unselectable'
    };

    // detect device type
    var isTouchDevice = ('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch,
		isWinPhoneDevice = /Windows Phone/.test(navigator.userAgent);
    commonOptions.isMobileDevice = !!(isTouchDevice || isWinPhoneDevice);

    // create global stylesheet if custom forms are used
    var createStyleSheet = function () {
        var styleTag = $('<style>').appendTo('head'),
			styleSheet = styleTag.prop('sheet') || styleTag.prop('styleSheet');

        // crossbrowser style handling
        var addCSSRule = function (selector, rules, index) {
            if (styleSheet.insertRule) {
                styleSheet.insertRule(selector + '{' + rules + '}', index);
            } else {
                styleSheet.addRule(selector, rules, index);
            }
        };

        // add special rules
        addCSSRule('.' + commonOptions.hiddenClass, 'position:absolute !important;left:-9999px !important;height:1px !important;width:1px !important;margin:0 !important;border-width:0 !important;-webkit-appearance:none;-moz-appearance:none;appearance:none');
        addCSSRule('.' + commonOptions.rtlClass + ' .' + commonOptions.hiddenClass, 'right:-9999px !important; left: auto !important');
        addCSSRule('.' + commonOptions.unselectableClass, '-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: rgba(0,0,0,0);');
        addCSSRule('.' + commonOptions.resetAppearanceClass, 'background: none; border: none; -webkit-appearance: none; appearance: none; opacity: 0; filter: alpha(opacity=0);');

        // detect rtl pages
        var html = $('html'), body = $('body');
        if (html.css('direction') === 'rtl' || body.css('direction') === 'rtl') {
            html.addClass(commonOptions.rtlClass);
        }

        // handle form reset event
        html.on('reset', function () {
            setTimeout(function () {
                api.refreshAll();
            }, 0);
        });

        // mark stylesheet as created
        commonOptions.styleSheetCreated = true;
    };

    // simplified pointer events handler
    (function () {
        var pointerEventsSupported = navigator.pointerEnabled || navigator.msPointerEnabled,
			touchEventsSupported = ('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch,
			eventList, eventMap = {}, eventPrefix = 'jcf-';

        // detect events to attach
        if (pointerEventsSupported) {
            eventList = {
                pointerover: navigator.pointerEnabled ? 'pointerover' : 'MSPointerOver',
                pointerdown: navigator.pointerEnabled ? 'pointerdown' : 'MSPointerDown',
                pointermove: navigator.pointerEnabled ? 'pointermove' : 'MSPointerMove',
                pointerup: navigator.pointerEnabled ? 'pointerup' : 'MSPointerUp'
            };
        } else {
            eventList = {
                pointerover: 'mouseover',
                pointerdown: 'mousedown' + (touchEventsSupported ? ' touchstart' : ''),
                pointermove: 'mousemove' + (touchEventsSupported ? ' touchmove' : ''),
                pointerup: 'mouseup' + (touchEventsSupported ? ' touchend' : '')
            };
        }

        // create event map
        $.each(eventList, function (targetEventName, fakeEventList) {
            $.each(fakeEventList.split(' '), function (index, fakeEventName) {
                eventMap[fakeEventName] = targetEventName;
            });
        });

        // jQuery event hooks
        $.each(eventList, function (eventName, eventHandlers) {
            eventHandlers = eventHandlers.split(' ');
            $.event.special[eventPrefix + eventName] = {
                setup: function () {
                    var self = this;
                    $.each(eventHandlers, function (index, fallbackEvent) {
                        if (self.addEventListener) self.addEventListener(fallbackEvent, fixEvent, false);
                        else self['on' + fallbackEvent] = fixEvent;
                    });
                },
                teardown: function () {
                    var self = this;
                    $.each(eventHandlers, function (index, fallbackEvent) {
                        if (self.addEventListener) self.removeEventListener(fallbackEvent, fixEvent, false);
                        else self['on' + fallbackEvent] = null;
                    });
                }
            };
        });

        // check that mouse event are not simulated by mobile browsers
        var lastTouch = null;
        var mouseEventSimulated = function (e) {
            var dx = Math.abs(e.pageX - lastTouch.x),
				dy = Math.abs(e.pageY - lastTouch.y),
				rangeDistance = 25;

            if (dx <= rangeDistance && dy <= rangeDistance) {
                return true;
            }
        };

        // normalize event
        var fixEvent = function (e) {
            var origEvent = e || window.event,
				touchEventData = null,
				targetEventName = eventMap[origEvent.type];

            e = $.event.fix(origEvent);
            e.type = eventPrefix + targetEventName;

            if (origEvent.pointerType) {
                switch (origEvent.pointerType) {
                    case 2: e.pointerType = 'touch'; break;
                    case 3: e.pointerType = 'pen'; break;
                    case 4: e.pointerType = 'mouse'; break;
                    default: e.pointerType = origEvent.pointerType;
                }
            } else {
                e.pointerType = origEvent.type.substr(0, 5); // "mouse" or "touch" word length
            }

            if (!e.pageX && !e.pageY) {
                touchEventData = origEvent.changedTouches ? origEvent.changedTouches[0] : origEvent;
                e.pageX = touchEventData.pageX;
                e.pageY = touchEventData.pageY;
            }

            if (origEvent.type === 'touchend') {
                lastTouch = { x: e.pageX, y: e.pageY };
            }
            if (e.pointerType === 'mouse' && lastTouch && mouseEventSimulated(e)) {
                return;
            } else {
                return ($.event.dispatch || $.event.handle).call(this, e);
            }
        };
    }());

    // custom mousewheel/trackpad handler
    (function () {
        var wheelEvents = ('onwheel' in document || document.documentMode >= 9 ? 'wheel' : 'mousewheel DOMMouseScroll').split(' '),
			shimEventName = 'jcf-mousewheel';

        $.event.special[shimEventName] = {
            setup: function () {
                var self = this;
                $.each(wheelEvents, function (index, fallbackEvent) {
                    if (self.addEventListener) self.addEventListener(fallbackEvent, fixEvent, false);
                    else self['on' + fallbackEvent] = fixEvent;
                });
            },
            teardown: function () {
                var self = this;
                $.each(wheelEvents, function (index, fallbackEvent) {
                    if (self.addEventListener) self.removeEventListener(fallbackEvent, fixEvent, false);
                    else self['on' + fallbackEvent] = null;
                });
            }
        };

        var fixEvent = function (e) {
            var origEvent = e || window.event;
            e = $.event.fix(origEvent);
            e.type = shimEventName;

            // old wheel events handler
            if ('detail' in origEvent) { e.deltaY = -origEvent.detail; }
            if ('wheelDelta' in origEvent) { e.deltaY = -origEvent.wheelDelta; }
            if ('wheelDeltaY' in origEvent) { e.deltaY = -origEvent.wheelDeltaY; }
            if ('wheelDeltaX' in origEvent) { e.deltaX = -origEvent.wheelDeltaX; }

            // modern wheel event handler
            if ('deltaY' in origEvent) {
                e.deltaY = origEvent.deltaY;
            }
            if ('deltaX' in origEvent) {
                e.deltaX = origEvent.deltaX;
            }

            // handle deltaMode for mouse wheel
            e.delta = e.deltaY || e.deltaX;
            if (origEvent.deltaMode === 1) {
                var lineHeight = 16;
                e.delta *= lineHeight;
                e.deltaY *= lineHeight;
                e.deltaX *= lineHeight;
            }

            return ($.event.dispatch || $.event.handle).call(this, e);
        };
    }());

    // extra module methods
    var moduleMixin = {
        // provide function for firing native events
        fireNativeEvent: function (elements, eventName) {
            $(elements).each(function () {
                var element = this, eventObject;
                if (element.dispatchEvent) {
                    eventObject = document.createEvent('HTMLEvents');
                    eventObject.initEvent(eventName, true, true);
                    element.dispatchEvent(eventObject);
                } else if (document.createEventObject) {
                    eventObject = document.createEventObject();
                    eventObject.target = element;
                    element.fireEvent('on' + eventName, eventObject);
                }
            });
        },
        // bind event handlers for module instance (functions beggining with "on")
        bindHandlers: function () {
            var self = this;
            $.each(self, function (propName, propValue) {
                if (propName.indexOf('on') === 0 && $.isFunction(propValue)) {
                    // dont use $.proxy here because it doesn't create unique handler
                    self[propName] = function () {
                        return propValue.apply(self, arguments);
                    };
                }
            });
        }
    };

    // public API
    var api = {
        version: version,
        modules: {},
        getOptions: function () {
            return $.extend({}, commonOptions);
        },
        setOptions: function (moduleName, moduleOptions) {
            if (arguments.length > 1) {
                // set module options
                if (this.modules[moduleName]) {
                    $.extend(this.modules[moduleName].prototype.options, moduleOptions);
                }
            } else {
                // set common options
                $.extend(commonOptions, moduleName);
            }
        },
        addModule: function (proto) {
            // add module to list
            var Module = function (options) {
                // save instance to collection
                if (!options.element.data(commonOptions.dataKey)) {
                    options.element.data(commonOptions.dataKey, this);
                }
                customInstances.push(this);

                // save options
                this.options = $.extend({}, commonOptions, this.options, getInlineOptions(options.element), options);

                // bind event handlers to instance
                this.bindHandlers();

                // call constructor
                this.init.apply(this, arguments);
            };

            // parse options from HTML attribute
            var getInlineOptions = function (element) {
                var dataOptions = element.data(commonOptions.optionsKey),
					attrOptions = element.attr(commonOptions.optionsKey);

                if (dataOptions) {
                    return dataOptions;
                } else if (attrOptions) {
                    try {
                        return $.parseJSON(attrOptions);
                    } catch (e) {
                        // ignore invalid attributes
                    }
                }
            };

            // set proto as prototype for new module
            Module.prototype = proto;

            // add mixin methods to module proto
            $.extend(proto, moduleMixin);
            if (proto.plugins) {
                $.each(proto.plugins, function (pluginName, plugin) {
                    $.extend(plugin.prototype, moduleMixin);
                });
            }

            // override destroy method
            var originalDestroy = Module.prototype.destroy;
            Module.prototype.destroy = function () {
                this.options.element.removeData(this.options.dataKey);

                for (var i = customInstances.length - 1; i >= 0; i--) {
                    if (customInstances[i] === this) {
                        customInstances.splice(i, 1);
                        break;
                    }
                }

                if (originalDestroy) {
                    originalDestroy.apply(this, arguments);
                }
            };

            // save module to list
            this.modules[proto.name] = Module;
        },
        getInstance: function (element) {
            return $(element).data(commonOptions.dataKey);
        },
        replace: function (elements, moduleName, customOptions) {
            var self = this,
				instance;

            if (!commonOptions.styleSheetCreated) {
                createStyleSheet();
            }

            $(elements).each(function () {
                var moduleOptions,
					element = $(this);

                instance = element.data(commonOptions.dataKey);
                if (instance) {
                    instance.refresh();
                } else {
                    if (!moduleName) {
                        $.each(self.modules, function (currentModuleName, module) {
                            if (module.prototype.matchElement.call(module.prototype, element)) {
                                moduleName = currentModuleName;
                                return false;
                            }
                        });
                    }
                    if (moduleName) {
                        moduleOptions = $.extend({ element: element }, customOptions);
                        instance = new self.modules[moduleName](moduleOptions);
                    }
                }
            });
            return instance;
        },
        refresh: function (elements) {
            $(elements).each(function () {
                var instance = $(this).data(commonOptions.dataKey);
                if (instance) {
                    instance.refresh();
                }
            });
        },
        destroy: function (elements) {
            $(elements).each(function () {
                var instance = $(this).data(commonOptions.dataKey);
                if (instance) {
                    instance.destroy();
                }
            });
        },
        replaceAll: function (context) {
            var self = this;
            $.each(this.modules, function (moduleName, module) {
                $(module.prototype.selector, context).each(function () {
                    if (this.className.indexOf('jcf-ignore') < 0) {
                        self.replace(this, moduleName);
                    }
                });
            });
        },
        refreshAll: function (context) {
            if (context) {
                $.each(this.modules, function (moduleName, module) {
                    $(module.prototype.selector, context).each(function () {
                        var instance = $(this).data(commonOptions.dataKey);
                        if (instance) {
                            instance.refresh();
                        }
                    });
                });
            } else {
                for (var i = customInstances.length - 1; i >= 0; i--) {
                    customInstances[i].refresh();
                }
            }
        },
        destroyAll: function (context) {
            if (context) {
                $.each(this.modules, function (moduleName, module) {
                    $(module.prototype.selector, context).each(function (index, element) {
                        var instance = $(element).data(commonOptions.dataKey);
                        if (instance) {
                            instance.destroy();
                        }
                    });
                });
            } else {
                while (customInstances.length) {
                    customInstances[0].destroy();
                }
            }
        }
    };

    // always export API to the global window object
    window.jcf = api;

    return api;
}));

/*!
 * JavaScript Custom Forms : Select Module
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
; (function ($, window) {
    'use strict';

    jcf.addModule({
        name: 'Select',
        selector: 'select',
        options: {
            element: null,
            multipleCompactStyle: false
        },
        plugins: {
            ListBox: ListBox,
            ComboBox: ComboBox,
            SelectList: SelectList
        },
        matchElement: function (element) {
            return element.is('select');
        },
        init: function () {
            this.element = $(this.options.element);
            this.createInstance();
        },
        isListBox: function () {
            return this.element.is('[size]:not([jcf-size]), [multiple]');
        },
        createInstance: function () {
            if (this.instance) {
                this.instance.destroy();
            }
            if (this.isListBox() && !this.options.multipleCompactStyle) {
                this.instance = new ListBox(this.options);
            } else {
                this.instance = new ComboBox(this.options);
            }
        },
        refresh: function () {
            var typeMismatch = (this.isListBox() && this.instance instanceof ComboBox) ||
								(!this.isListBox() && this.instance instanceof ListBox);

            if (typeMismatch) {
                this.createInstance();
            } else {
                this.instance.refresh();
            }
        },
        destroy: function () {
            this.instance.destroy();
        }
    });

    // combobox module
    function ComboBox(options) {
        this.options = $.extend({
            wrapNative: true,
            wrapNativeOnMobile: true,
            fakeDropInBody: true,
            useCustomScroll: true,
            flipDropToFit: true,
            maxVisibleItems: 10,
            fakeAreaStructure: '<span class="jcf-select"><span class="jcf-select-text"></span><span class="jcf-select-opener"></span></span>',
            fakeDropStructure: '<div class="jcf-select-drop"><div class="jcf-select-drop-content"></div></div>',
            optionClassPrefix: 'jcf-option-',
            selectClassPrefix: 'jcf-select-',
            dropContentSelector: '.jcf-select-drop-content',
            selectTextSelector: '.jcf-select-text',
            dropActiveClass: 'jcf-drop-active',
            flipDropClass: 'jcf-drop-flipped'
        }, options);
        this.init();
    }
    $.extend(ComboBox.prototype, {
        init: function () {
            this.initStructure();
            this.bindHandlers();
            this.attachEvents();
            this.refresh();
        },
        initStructure: function () {
            // prepare structure
            this.win = $(window);
            this.doc = $(document);
            this.realElement = $(this.options.element);
            this.fakeElement = $(this.options.fakeAreaStructure).insertAfter(this.realElement);
            this.selectTextContainer = this.fakeElement.find(this.options.selectTextSelector);
            this.selectText = $('<span></span>').appendTo(this.selectTextContainer);
            makeUnselectable(this.fakeElement);

            // copy classes from original select
            this.fakeElement.addClass(getPrefixedClasses(this.realElement.prop('className'), this.options.selectClassPrefix));

            // handle compact multiple style
            if (this.realElement.prop('multiple')) {
                this.fakeElement.addClass('jcf-compact-multiple');
            }

            // detect device type and dropdown behavior
            if (this.options.isMobileDevice && this.options.wrapNativeOnMobile && !this.options.wrapNative) {
                this.options.wrapNative = true;
            }

            if (this.options.wrapNative) {
                // wrap native select inside fake block
                this.realElement.prependTo(this.fakeElement).css({
                    position: 'absolute',
                    height: '100%',
                    width: '100%'
                }).addClass(this.options.resetAppearanceClass);
            } else {
                // just hide native select
                this.realElement.addClass(this.options.hiddenClass);
                this.fakeElement.attr('title', this.realElement.attr('title'));
                this.fakeDropTarget = this.options.fakeDropInBody ? $('body') : this.fakeElement;
            }
        },
        attachEvents: function () {
            // delayed refresh handler
            var self = this;
            this.delayedRefresh = function () {
                setTimeout(function () {
                    self.refresh();
                    if (self.list) {
                        self.list.refresh();
                        self.list.scrollToActiveOption();
                    }
                }, 1);
            };

            // native dropdown event handlers
            if (this.options.wrapNative) {
                this.realElement.on({
                    focus: this.onFocus,
                    change: this.onChange,
                    click: this.onChange,
                    keydown: this.onChange
                });
            } else {
                // custom dropdown event handlers
                this.realElement.on({
                    focus: this.onFocus,
                    change: this.onChange,
                    keydown: this.onKeyDown
                });
                this.fakeElement.on({
                    'jcf-pointerdown': this.onSelectAreaPress
                });
            }
        },
        onKeyDown: function (e) {
            if (e.which === 13) {
                this.toggleDropdown();
            } else if (this.dropActive) {
                this.delayedRefresh();
            }
        },
        onChange: function () {
            this.refresh();
        },
        onFocus: function () {
            if (!this.pressedFlag || !this.focusedFlag) {
                this.fakeElement.addClass(this.options.focusClass);
                this.realElement.on('blur', this.onBlur);
                this.toggleListMode(true);
                this.focusedFlag = true;
            }
        },
        onBlur: function () {
            if (!this.pressedFlag) {
                this.fakeElement.removeClass(this.options.focusClass);
                this.realElement.off('blur', this.onBlur);
                this.toggleListMode(false);
                this.focusedFlag = false;
            }
        },
        onResize: function () {
            if (this.dropActive) {
                this.hideDropdown();
            }
        },
        onSelectDropPress: function () {
            this.pressedFlag = true;
        },
        onSelectDropRelease: function (e, pointerEvent) {
            this.pressedFlag = false;
            if (pointerEvent.pointerType === 'mouse') {
                this.realElement.focus();
            }
        },
        onSelectAreaPress: function (e) {
            // skip click if drop inside fake element or real select is disabled
            var dropClickedInsideFakeElement = !this.options.fakeDropInBody && $(e.target).closest(this.dropdown).length;
            if (dropClickedInsideFakeElement || e.button > 1 || this.realElement.is(':disabled')) {
                return;
            }

            // toggle dropdown visibility
            this.selectOpenedByEvent = e.pointerType;
            this.toggleDropdown();

            // misc handlers
            if (!this.focusedFlag) {
                if (e.pointerType === 'mouse') {
                    this.realElement.focus();
                } else {
                    this.onFocus(e);
                }
            }
            this.pressedFlag = true;
            this.fakeElement.addClass(this.options.pressedClass);
            this.doc.on('jcf-pointerup', this.onSelectAreaRelease);
        },
        onSelectAreaRelease: function (e) {
            if (this.focusedFlag && e.pointerType === 'mouse') {
                this.realElement.focus();
            }
            this.pressedFlag = false;
            this.fakeElement.removeClass(this.options.pressedClass);
            this.doc.off('jcf-pointerup', this.onSelectAreaRelease);
        },
        onOutsideClick: function (e) {
            var target = $(e.target),
				clickedInsideSelect = target.closest(this.fakeElement).length || target.closest(this.dropdown).length;

            if (!clickedInsideSelect) {
                this.hideDropdown();
            }
        },
        onSelect: function () {
            this.refresh();

            if (this.realElement.prop('multiple')) {
                this.repositionDropdown();
            } else {
                this.hideDropdown();
            }

            this.fireNativeEvent(this.realElement, 'change');
        },
        toggleListMode: function (state) {
            if (!this.options.wrapNative) {
                if (state) {
                    // temporary change select to list to avoid appearing of native dropdown
                    this.realElement.attr({
                        size: 4,
                        'jcf-size': ''
                    });
                } else {
                    // restore select from list mode to dropdown select
                    if (!this.options.wrapNative) {
                        this.realElement.removeAttr('size jcf-size');
                    }
                }
            }
        },
        createDropdown: function () {
            // destroy previous dropdown if needed
            if (this.dropdown) {
                this.list.destroy();
                this.dropdown.remove();
            }

            // create new drop container
            this.dropdown = $(this.options.fakeDropStructure).appendTo(this.fakeDropTarget);
            this.dropdown.addClass(getPrefixedClasses(this.realElement.prop('className'), this.options.selectClassPrefix));
            makeUnselectable(this.dropdown);

            // handle compact multiple style
            if (this.realElement.prop('multiple')) {
                this.dropdown.addClass('jcf-compact-multiple');
            }

            // set initial styles for dropdown in body
            if (this.options.fakeDropInBody) {
                this.dropdown.css({
                    position: 'absolute',
                    top: -9999
                });
            }

            // create new select list instance
            this.list = new SelectList({
                useHoverClass: true,
                handleResize: false,
                alwaysPreventMouseWheel: true,
                maxVisibleItems: this.options.maxVisibleItems,
                useCustomScroll: this.options.useCustomScroll,
                holder: this.dropdown.find(this.options.dropContentSelector),
                multipleSelectWithoutKey: this.realElement.prop('multiple'),
                element: this.realElement
            });
            $(this.list).on({
                select: this.onSelect,
                press: this.onSelectDropPress,
                release: this.onSelectDropRelease
            });
        },
        repositionDropdown: function () {
            var selectOffset = this.fakeElement.offset(),
				selectWidth = this.fakeElement.outerWidth(),
				selectHeight = this.fakeElement.outerHeight(),
				dropHeight = this.dropdown.css('width', selectWidth).outerHeight(),
				winScrollTop = this.win.scrollTop(),
				winHeight = this.win.height(),
				calcTop, calcLeft, bodyOffset, needFlipDrop = false;

            // check flip drop position
            if (selectOffset.top + selectHeight + dropHeight > winScrollTop + winHeight && selectOffset.top - dropHeight > winScrollTop) {
                needFlipDrop = true;
            }

            if (this.options.fakeDropInBody) {
                bodyOffset = this.fakeDropTarget.css('position') !== 'static' ? this.fakeDropTarget.offset().top : 0;
                if (this.options.flipDropToFit && needFlipDrop) {
                    // calculate flipped dropdown position
                    calcLeft = selectOffset.left;
                    calcTop = selectOffset.top - dropHeight - bodyOffset;
                } else {
                    // calculate default drop position
                    calcLeft = selectOffset.left;
                    calcTop = selectOffset.top + selectHeight - bodyOffset;
                }

                // update drop styles
                this.dropdown.css({
                    width: selectWidth,
                    left: calcLeft,
                    top: calcTop
                });
            }

            // refresh flipped class
            this.dropdown.add(this.fakeElement).toggleClass(this.options.flipDropClass, this.options.flipDropToFit && needFlipDrop);
        },
        showDropdown: function () {
            // do not show empty custom dropdown
            if (!this.realElement.prop('options').length) {
                return;
            }

            // create options list if not created
            if (!this.dropdown) {
                this.createDropdown();
            }

            // show dropdown
            this.dropActive = true;
            this.dropdown.appendTo(this.fakeDropTarget);
            this.fakeElement.addClass(this.options.dropActiveClass);
            this.refreshSelectedText();
            this.repositionDropdown();
            this.list.setScrollTop(this.savedScrollTop);
            this.list.refresh();

            // add temporary event handlers
            this.win.on('resize', this.onResize);
            this.doc.on('jcf-pointerdown', this.onOutsideClick);
        },
        hideDropdown: function () {
            if (this.dropdown) {
                this.savedScrollTop = this.list.getScrollTop();
                this.fakeElement.removeClass(this.options.dropActiveClass + ' ' + this.options.flipDropClass);
                this.dropdown.removeClass(this.options.flipDropClass).detach();
                this.doc.off('jcf-pointerdown', this.onOutsideClick);
                this.win.off('resize', this.onResize);
                this.dropActive = false;
                if (this.selectOpenedByEvent === 'touch') {
                    this.onBlur();
                }
            }
        },
        toggleDropdown: function () {
            if (this.dropActive) {
                this.hideDropdown();
            } else {
                this.showDropdown();
            }
        },
        refreshSelectedText: function () {
            // redraw selected area
            var selectedIndex = this.realElement.prop('selectedIndex'),
				selectedOption = this.realElement.prop('options')[selectedIndex],
				selectedOptionImage = selectedOption ? selectedOption.getAttribute('data-image') : null,
				selectedOptionText = '',
				selectedOptionClasses,
				self = this;

            if (this.realElement.prop('multiple')) {
                $.each(this.realElement.prop('options'), function (index, option) {
                    if (option.selected) {
                        selectedOptionText += (selectedOptionText ? ', ' : '') + option.innerHTML;
                    }
                });
                if (!selectedOptionText) {
                    selectedOptionText = self.realElement.attr('placeholder') || '';
                }
                this.selectText.removeAttr('class').html(selectedOptionText);
            } else if (!selectedOption) {
                if (this.selectImage) {
                    this.selectImage.hide();
                }
                this.selectText.removeAttr('class').empty();
            } else if (this.currentSelectedText !== selectedOption.innerHTML || this.currentSelectedImage !== selectedOptionImage) {
                selectedOptionClasses = getPrefixedClasses(selectedOption.className, this.options.optionClassPrefix);
                this.selectText.attr('class', selectedOptionClasses).html(selectedOption.innerHTML);

                if (selectedOptionImage) {
                    if (!this.selectImage) {
                        this.selectImage = $('<img>').prependTo(this.selectTextContainer).hide();
                    }
                    this.selectImage.attr('src', selectedOptionImage).show();
                } else if (this.selectImage) {
                    this.selectImage.hide();
                }

                this.currentSelectedText = selectedOption.innerHTML;
                this.currentSelectedImage = selectedOptionImage;
            }
        },
        refresh: function () {
            // refresh fake select visibility
            if (this.realElement.prop('style').display === 'none') {
                this.fakeElement.hide();
            } else {
                this.fakeElement.show();
            }

            // refresh selected text
            this.refreshSelectedText();

            // handle disabled state
            this.fakeElement.toggleClass(this.options.disabledClass, this.realElement.is(':disabled'));
        },
        destroy: function () {
            // restore structure
            if (this.options.wrapNative) {
                this.realElement.insertBefore(this.fakeElement).css({
                    position: '',
                    height: '',
                    width: ''
                }).removeClass(this.options.resetAppearanceClass);
            } else {
                this.realElement.removeClass(this.options.hiddenClass);
                if (this.realElement.is('[jcf-size]')) {
                    this.realElement.removeAttr('size jcf-size');
                }
            }

            // removing element will also remove its event handlers
            this.fakeElement.remove();

            // remove other event handlers
            this.doc.off('jcf-pointerup', this.onSelectAreaRelease);
            this.realElement.off({
                focus: this.onFocus
            });
        }
    });

    // listbox module
    function ListBox(options) {
        this.options = $.extend({
            wrapNative: true,
            useCustomScroll: true,
            fakeStructure: '<span class="jcf-list-box"><span class="jcf-list-wrapper"></span></span>',
            selectClassPrefix: 'jcf-select-',
            listHolder: '.jcf-list-wrapper'
        }, options);
        this.init();
    }
    $.extend(ListBox.prototype, {
        init: function () {
            this.bindHandlers();
            this.initStructure();
            this.attachEvents();
        },
        initStructure: function () {
            this.realElement = $(this.options.element);
            this.fakeElement = $(this.options.fakeStructure).insertAfter(this.realElement);
            this.listHolder = this.fakeElement.find(this.options.listHolder);
            makeUnselectable(this.fakeElement);

            // copy classes from original select
            this.fakeElement.addClass(getPrefixedClasses(this.realElement.prop('className'), this.options.selectClassPrefix));
            this.realElement.addClass(this.options.hiddenClass);

            this.list = new SelectList({
                useCustomScroll: this.options.useCustomScroll,
                holder: this.listHolder,
                selectOnClick: false,
                element: this.realElement
            });
        },
        attachEvents: function () {
            // delayed refresh handler
            var self = this;
            this.delayedRefresh = function (e) {
                if (e && e.which === 16) {
                    // ignore SHIFT key
                    return;
                } else {
                    clearTimeout(self.refreshTimer);
                    self.refreshTimer = setTimeout(function () {
                        self.refresh();
                        self.list.scrollToActiveOption();
                    }, 1);
                }
            };

            // other event handlers
            this.realElement.on({
                focus: this.onFocus,
                click: this.delayedRefresh,
                keydown: this.delayedRefresh
            });

            // select list event handlers
            $(this.list).on({
                select: this.onSelect,
                press: this.onFakeOptionsPress,
                release: this.onFakeOptionsRelease
            });
        },
        onFakeOptionsPress: function (e, pointerEvent) {
            this.pressedFlag = true;
            if (pointerEvent.pointerType === 'mouse') {
                this.realElement.focus();
            }
        },
        onFakeOptionsRelease: function (e, pointerEvent) {
            this.pressedFlag = false;
            if (pointerEvent.pointerType === 'mouse') {
                this.realElement.focus();
            }
        },
        onSelect: function () {
            this.fireNativeEvent(this.realElement, 'change');
            this.fireNativeEvent(this.realElement, 'click');
        },
        onFocus: function () {
            if (!this.pressedFlag || !this.focusedFlag) {
                this.fakeElement.addClass(this.options.focusClass);
                this.realElement.on('blur', this.onBlur);
                this.focusedFlag = true;
            }
        },
        onBlur: function () {
            if (!this.pressedFlag) {
                this.fakeElement.removeClass(this.options.focusClass);
                this.realElement.off('blur', this.onBlur);
                this.focusedFlag = false;
            }
        },
        refresh: function () {
            this.fakeElement.toggleClass(this.options.disabledClass, this.realElement.is(':disabled'));
            this.list.refresh();
        },
        destroy: function () {
            this.list.destroy();
            this.realElement.insertBefore(this.fakeElement).removeClass(this.options.hiddenClass);
            this.fakeElement.remove();
        }
    });

    // options list module
    function SelectList(options) {
        this.options = $.extend({
            holder: null,
            maxVisibleItems: 10,
            selectOnClick: true,
            useHoverClass: false,
            useCustomScroll: false,
            handleResize: true,
            multipleSelectWithoutKey: false,
            alwaysPreventMouseWheel: false,
            indexAttribute: 'data-index',
            cloneClassPrefix: 'jcf-option-',
            containerStructure: '<span class="jcf-list"><span class="jcf-list-content"></span></span>',
            containerSelector: '.jcf-list-content',
            captionClass: 'jcf-optgroup-caption',
            disabledClass: 'jcf-disabled',
            optionClass: 'jcf-option',
            groupClass: 'jcf-optgroup',
            hoverClass: 'jcf-hover',
            selectedClass: 'jcf-selected',
            scrollClass: 'jcf-scroll-active'
        }, options);
        this.init();
    }
    $.extend(SelectList.prototype, {
        init: function () {
            this.initStructure();
            this.refreshSelectedClass();
            this.attachEvents();
        },
        initStructure: function () {
            this.element = $(this.options.element);
            this.indexSelector = '[' + this.options.indexAttribute + ']';
            this.container = $(this.options.containerStructure).appendTo(this.options.holder);
            this.listHolder = this.container.find(this.options.containerSelector);
            this.lastClickedIndex = this.element.prop('selectedIndex');
            this.rebuildList();
        },
        attachEvents: function () {
            this.bindHandlers();
            this.listHolder.on('jcf-pointerdown', this.indexSelector, this.onItemPress);
            this.listHolder.on('jcf-pointerdown', this.onPress);

            if (this.options.useHoverClass) {
                this.listHolder.on('jcf-pointerover', this.indexSelector, this.onHoverItem);
            }
        },
        onPress: function (e) {
            $(this).trigger('press', e);
            this.listHolder.on('jcf-pointerup', this.onRelease);
        },
        onRelease: function (e) {
            $(this).trigger('release', e);
            this.listHolder.off('jcf-pointerup', this.onRelease);
        },
        onHoverItem: function (e) {
            var hoverIndex = parseFloat(e.currentTarget.getAttribute(this.options.indexAttribute));
            this.fakeOptions.removeClass(this.options.hoverClass).eq(hoverIndex).addClass(this.options.hoverClass);
        },
        onItemPress: function (e) {
            if (e.pointerType === 'touch' || this.options.selectOnClick) {
                // select option after "click"
                this.tmpListOffsetTop = this.list.offset().top;
                this.listHolder.on('jcf-pointerup', this.indexSelector, this.onItemRelease);
            } else {
                // select option immediately
                this.onSelectItem(e);
            }
        },
        onItemRelease: function (e) {
            // remove event handlers and temporary data
            this.listHolder.off('jcf-pointerup', this.indexSelector, this.onItemRelease);

            // simulate item selection
            if (this.tmpListOffsetTop === this.list.offset().top) {
                this.listHolder.on('click', this.indexSelector, { savedPointerType: e.pointerType }, this.onSelectItem);
            }
            delete this.tmpListOffsetTop;
        },
        onSelectItem: function (e) {
            var clickedIndex = parseFloat(e.currentTarget.getAttribute(this.options.indexAttribute)),
				pointerType = e.data && e.data.savedPointerType || e.pointerType || 'mouse',
				range;

            // remove click event handler
            this.listHolder.off('click', this.indexSelector, this.onSelectItem);

            // ignore clicks on disabled options
            if (e.button > 1 || this.realOptions[clickedIndex].disabled) {
                return;
            }

            if (this.element.prop('multiple')) {
                if (e.metaKey || e.ctrlKey || pointerType === 'touch' || this.options.multipleSelectWithoutKey) {
                    // if CTRL/CMD pressed or touch devices - toggle selected option
                    this.realOptions[clickedIndex].selected = !this.realOptions[clickedIndex].selected;
                } else if (e.shiftKey) {
                    // if SHIFT pressed - update selection
                    range = [this.lastClickedIndex, clickedIndex].sort(function (a, b) {
                        return a - b;
                    });
                    this.realOptions.each(function (index, option) {
                        option.selected = (index >= range[0] && index <= range[1]);
                    });
                } else {
                    // set single selected index
                    this.element.prop('selectedIndex', clickedIndex);
                }
            } else {
                this.element.prop('selectedIndex', clickedIndex);
            }

            // save last clicked option
            if (!e.shiftKey) {
                this.lastClickedIndex = clickedIndex;
            }

            // refresh classes
            this.refreshSelectedClass();

            // scroll to active item in desktop browsers
            if (pointerType === 'mouse') {
                this.scrollToActiveOption();
            }

            // make callback when item selected
            $(this).trigger('select');
        },
        rebuildList: function () {
            // rebuild options
            var self = this,
				rootElement = this.element[0];

            // recursively create fake options
            this.storedSelectHTML = rootElement.innerHTML;
            this.optionIndex = 0;
            this.list = $(this.createOptionsList(rootElement));
            this.listHolder.empty().append(this.list);
            this.realOptions = this.element.find('option');
            this.fakeOptions = this.list.find(this.indexSelector);
            this.fakeListItems = this.list.find('.' + this.options.captionClass + ',' + this.indexSelector);
            delete this.optionIndex;

            // detect max visible items
            var maxCount = this.options.maxVisibleItems,
				sizeValue = this.element.prop('size');
            if (sizeValue > 1 && !this.element.is('[jcf-size]')) {
                maxCount = sizeValue;
            }

            // handle scrollbar
            var needScrollBar = this.fakeOptions.length > maxCount;
            this.container.toggleClass(this.options.scrollClass, needScrollBar);
            if (needScrollBar) {
                // change max-height
                this.listHolder.css({
                    maxHeight: this.getOverflowHeight(maxCount),
                    overflow: 'auto'
                });

                if (this.options.useCustomScroll && jcf.modules.Scrollable) {
                    // add custom scrollbar if specified in options
                    jcf.replace(this.listHolder, 'Scrollable', {
                        handleResize: this.options.handleResize,
                        alwaysPreventMouseWheel: this.options.alwaysPreventMouseWheel
                    });
                    return;
                }
            }

            // disable edge wheel scrolling
            if (this.options.alwaysPreventMouseWheel) {
                this.preventWheelHandler = function (e) {
                    var currentScrollTop = self.listHolder.scrollTop(),
						maxScrollTop = self.listHolder.prop('scrollHeight') - self.listHolder.innerHeight();

                    // check edge cases
                    if ((currentScrollTop <= 0 && e.deltaY < 0) || (currentScrollTop >= maxScrollTop && e.deltaY > 0)) {
                        e.preventDefault();
                    }
                };
                this.listHolder.on('jcf-mousewheel', this.preventWheelHandler);
            }
        },
        refreshSelectedClass: function () {
            var self = this,
				selectedItem,
				isMultiple = this.element.prop('multiple'),
				selectedIndex = this.element.prop('selectedIndex');

            if (isMultiple) {
                this.realOptions.each(function (index, option) {
                    self.fakeOptions.eq(index).toggleClass(self.options.selectedClass, !!option.selected);
                });
            } else {
                this.fakeOptions.removeClass(this.options.selectedClass + ' ' + this.options.hoverClass);
                selectedItem = this.fakeOptions.eq(selectedIndex).addClass(this.options.selectedClass);
                if (this.options.useHoverClass) {
                    selectedItem.addClass(this.options.hoverClass);
                }
            }
        },
        scrollToActiveOption: function () {
            // scroll to target option
            var targetOffset = this.getActiveOptionOffset();
            if (typeof targetOffset === 'number') {
                this.listHolder.prop('scrollTop', targetOffset);
            }
        },
        getSelectedIndexRange: function () {
            var firstSelected = -1, lastSelected = -1;
            this.realOptions.each(function (index, option) {
                if (option.selected) {
                    if (firstSelected < 0) {
                        firstSelected = index;
                    }
                    lastSelected = index;
                }
            });
            return [firstSelected, lastSelected];
        },
        getChangedSelectedIndex: function () {
            var selectedIndex = this.element.prop('selectedIndex'),
				targetIndex;

            if (this.element.prop('multiple')) {
                // multiple selects handling
                if (!this.previousRange) {
                    this.previousRange = [selectedIndex, selectedIndex];
                }
                this.currentRange = this.getSelectedIndexRange();
                targetIndex = this.currentRange[this.currentRange[0] !== this.previousRange[0] ? 0 : 1];
                this.previousRange = this.currentRange;
                return targetIndex;
            } else {
                // single choice selects handling
                return selectedIndex;
            }
        },
        getActiveOptionOffset: function () {
            // calc values
            var dropHeight = this.listHolder.height(),
				dropScrollTop = this.listHolder.prop('scrollTop'),
				currentIndex = this.getChangedSelectedIndex(),
				fakeOption = this.fakeOptions.eq(currentIndex),
				fakeOptionOffset = fakeOption.offset().top - this.list.offset().top,
				fakeOptionHeight = fakeOption.innerHeight();

            // scroll list
            if (fakeOptionOffset + fakeOptionHeight >= dropScrollTop + dropHeight) {
                // scroll down (always scroll to option)
                return fakeOptionOffset - dropHeight + fakeOptionHeight;
            } else if (fakeOptionOffset < dropScrollTop) {
                // scroll up to option
                return fakeOptionOffset;
            }
        },
        getOverflowHeight: function (sizeValue) {
            var item = this.fakeListItems.eq(sizeValue - 1),
				listOffset = this.list.offset().top,
				itemOffset = item.offset().top,
				itemHeight = item.innerHeight();

            return itemOffset + itemHeight - listOffset;
        },
        getScrollTop: function () {
            return this.listHolder.scrollTop();
        },
        setScrollTop: function (value) {
            this.listHolder.scrollTop(value);
        },
        createOption: function (option) {
            var newOption = document.createElement('span');
            newOption.className = this.options.optionClass;
            newOption.innerHTML = option.innerHTML;
            newOption.setAttribute(this.options.indexAttribute, this.optionIndex++);

            var optionImage, optionImageSrc = option.getAttribute('data-image');
            if (optionImageSrc) {
                optionImage = document.createElement('img');
                optionImage.src = optionImageSrc;
                newOption.insertBefore(optionImage, newOption.childNodes[0]);
            }
            if (option.disabled) {
                newOption.className += ' ' + this.options.disabledClass;
            }
            if (option.className) {
                newOption.className += ' ' + getPrefixedClasses(option.className, this.options.cloneClassPrefix);
            }
            return newOption;
        },
        createOptGroup: function (optgroup) {
            var optGroupContainer = document.createElement('span'),
				optGroupName = optgroup.getAttribute('label'),
				optGroupCaption, optGroupList;

            // create caption
            optGroupCaption = document.createElement('span');
            optGroupCaption.className = this.options.captionClass;
            optGroupCaption.innerHTML = optGroupName;
            optGroupContainer.appendChild(optGroupCaption);

            // create list of options
            if (optgroup.children.length) {
                optGroupList = this.createOptionsList(optgroup);
                optGroupContainer.appendChild(optGroupList);
            }

            optGroupContainer.className = this.options.groupClass;
            return optGroupContainer;
        },
        createOptionContainer: function () {
            var optionContainer = document.createElement('li');
            return optionContainer;
        },
        createOptionsList: function (container) {
            var self = this,
				list = document.createElement('ul');

            $.each(container.children, function (index, currentNode) {
                var item = self.createOptionContainer(currentNode),
					newNode;

                switch (currentNode.tagName.toLowerCase()) {
                    case 'option': newNode = self.createOption(currentNode); break;
                    case 'optgroup': newNode = self.createOptGroup(currentNode); break;
                }
                list.appendChild(item).appendChild(newNode);
            });
            return list;
        },
        refresh: function () {
            // check for select innerHTML changes
            if (this.storedSelectHTML !== this.element.prop('innerHTML')) {
                this.rebuildList();
            }

            // refresh custom scrollbar
            var scrollInstance = jcf.getInstance(this.listHolder);
            if (scrollInstance) {
                scrollInstance.refresh();
            }

            // refresh selectes classes
            this.refreshSelectedClass();
        },
        destroy: function () {
            this.listHolder.off('jcf-mousewheel', this.preventWheelHandler);
            this.listHolder.off('jcf-pointerdown', this.indexSelector, this.onSelectItem);
            this.listHolder.off('jcf-pointerover', this.indexSelector, this.onHoverItem);
            this.listHolder.off('jcf-pointerdown', this.onPress);
        }
    });

    // helper functions
    var getPrefixedClasses = function (className, prefixToAdd) {
        return className ? className.replace(/[\s]*([\S]+)+[\s]*/gi, prefixToAdd + '$1 ') : '';
    };
    var makeUnselectable = (function () {
        var unselectableClass = jcf.getOptions().unselectableClass;
        function preventHandler(e) {
            e.preventDefault();
        }
        return function (node) {
            node.addClass(unselectableClass).on('selectstart', preventHandler);
        };
    }());

}(jQuery, this));



/*!
 * JavaScript Custom Forms : Number Module
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
; (function ($) {
    'use strict';

    jcf.addModule({
        name: 'Number',
        selector: 'input[type="number"]',
        options: {
            realElementClass: 'jcf-real-element',
            fakeStructure: '<span class="jcf-number"><span class="jcf-btn-inc"></span><span class="jcf-btn-dec"></span></span>',
            btnIncSelector: '.jcf-btn-inc',
            btnDecSelector: '.jcf-btn-dec',
            pressInterval: 150
        },
        matchElement: function (element) {
            return element.is(this.selector);
        },
        init: function () {
            this.initStructure();
            this.attachEvents();
            this.refresh();
        },
        initStructure: function () {
            this.page = $('html');
            this.realElement = $(this.options.element).addClass(this.options.realElementClass);
            this.fakeElement = $(this.options.fakeStructure).insertBefore(this.realElement).prepend(this.realElement);
            this.btnDec = this.fakeElement.find(this.options.btnDecSelector);
            this.btnInc = this.fakeElement.find(this.options.btnIncSelector);

            // set initial values
            this.initialValue = parseFloat(this.realElement.val()) || 0;
            this.minValue = parseFloat(this.realElement.attr('min'));
            this.maxValue = parseFloat(this.realElement.attr('max'));
            this.stepValue = parseFloat(this.realElement.attr('step')) || 1;

            // check attribute values
            this.minValue = isNaN(this.minValue) ? -Infinity : this.minValue;
            this.maxValue = isNaN(this.maxValue) ? Infinity : this.maxValue;

            // handle range
            if (isFinite(this.maxValue)) {
                this.maxValue -= (this.maxValue - this.minValue) % this.stepValue;
            }
        },
        attachEvents: function () {
            this.realElement.on({
                focus: this.onFocus
            });
            this.btnDec.add(this.btnInc).on('jcf-pointerdown', this.onBtnPress);
        },
        onBtnPress: function (e) {
            var self = this,
				increment;

            if (!this.realElement.is(':disabled')) {
                increment = this.btnInc.is(e.currentTarget);

                self.step(increment);
                clearInterval(this.stepTimer);
                this.stepTimer = setInterval(function () {
                    self.step(increment);
                }, this.options.pressInterval);

                this.page.on('jcf-pointerup', this.onBtnRelease);
            }
        },
        onBtnRelease: function () {
            clearInterval(this.stepTimer);
            this.page.off('jcf-pointerup', this.onBtnRelease);
        },
        onFocus: function () {
            this.fakeElement.addClass(this.options.focusClass);
            this.realElement.on({
                blur: this.onBlur,
                keydown: this.onKeyPress
            });
        },
        onBlur: function () {
            this.fakeElement.removeClass(this.options.focusClass);
            this.realElement.off({
                blur: this.onBlur,
                keydown: this.onKeyPress
            });
        },
        onKeyPress: function (e) {
            if (e.which === 38 || e.which === 40) {
                e.preventDefault();
                this.step(e.which === 38);
            }
        },
        step: function (increment) {
            var originalValue = parseFloat(this.realElement.val()),
				newValue = originalValue || 0,
				addValue = this.stepValue * (increment ? 1 : -1),
				edgeNumber = isFinite(this.minValue) ? this.minValue : this.initialValue - Math.abs(newValue * this.stepValue),
				diff = Math.abs(edgeNumber - newValue) % this.stepValue;

            // handle step diff
            if (diff) {
                if (increment) {
                    newValue += addValue - diff;
                } else {
                    newValue -= diff;
                }
            } else {
                newValue += addValue;
            }

            // handle min/max limits
            if (newValue < this.minValue) {
                newValue = this.minValue;
            } else if (newValue > this.maxValue) {
                newValue = this.maxValue;
            }

            // update value in real input if its changed
            if (newValue !== originalValue) {
                this.realElement.val(newValue).trigger('change');
                this.refresh();
            }
        },
        refresh: function () {
            var isDisabled = this.realElement.is(':disabled'),
				currentValue = parseFloat(this.realElement.val());

            // handle disabled state
            this.fakeElement.toggleClass(this.options.disabledClass, isDisabled);

            // refresh button classes
            this.btnDec.toggleClass(this.options.disabledClass, currentValue === this.minValue);
            this.btnInc.toggleClass(this.options.disabledClass, currentValue === this.maxValue);
        },
        destroy: function () {
            // restore original structure
            this.realElement.removeClass(this.options.realElementClass).insertBefore(this.fakeElement);
            this.fakeElement.remove();
            clearInterval(this.stepTimer);

            // remove event handlers
            this.page.off('jcf-pointerup', this.onBtnRelease);
            this.realElement.off({
                keydown: this.onKeyPress,
                focus: this.onFocus,
                blur: this.onBlur
            });
        }
    });

}(jQuery));




/*
 * jQuery Carousel plugin
 */
; (function ($) {
    function ScrollGallery(options) {
        this.options = $.extend({
            mask: 'div.mask',
            slider: '>*',
            slides: '>*',
            activeClass: 'active',
            disabledClass: 'disabled',
            btnPrev: 'a.btn-prev',
            btnNext: 'a.btn-next',
            generatePagination: false,
            pagerList: '<ul>',
            pagerListItem: '<li><a href="#"></a></li>',
            pagerListItemText: 'a',
            pagerLinks: '.pagination li',
            currentNumber: 'span.current-num',
            totalNumber: 'span.total-num',
            btnPlay: '.btn-play',
            btnPause: '.btn-pause',
            btnPlayPause: '.btn-play-pause',
            galleryReadyClass: 'gallery-js-ready',
            autorotationActiveClass: 'autorotation-active',
            autorotationDisabledClass: 'autorotation-disabled',
            stretchSlideToMask: false,
            circularRotation: true,
            disableWhileAnimating: false,
            autoRotation: false,
            pauseOnHover: isTouchDevice ? false : true,
            maskAutoSize: false,
            switchTime: 4000,
            animSpeed: 600,
            event: 'click',
            swipeThreshold: 15,
            handleTouch: true,
            vertical: false,
            useTranslate3D: false,
            step: false
        }, options);
        this.init();
    }
    ScrollGallery.prototype = {
        init: function () {
            if (this.options.holder) {
                this.findElements();
                this.attachEvents();
                this.refreshPosition();
                this.refreshState(true);
                this.resumeRotation();
                this.makeCallback('onInit', this);
            }
        },
        findElements: function () {
            // define dimensions proporties
            this.fullSizeFunction = this.options.vertical ? 'outerHeight' : 'outerWidth';
            this.innerSizeFunction = this.options.vertical ? 'height' : 'width';
            this.slideSizeFunction = 'outerHeight';
            this.maskSizeProperty = 'height';
            this.animProperty = this.options.vertical ? 'marginTop' : 'marginLeft';

            // control elements
            this.gallery = $(this.options.holder).addClass(this.options.galleryReadyClass);
            this.mask = this.gallery.find(this.options.mask);
            this.slider = this.mask.find(this.options.slider);
            this.slides = this.slider.find(this.options.slides);
            this.btnPrev = this.gallery.find(this.options.btnPrev);
            this.btnNext = this.gallery.find(this.options.btnNext);
            this.currentStep = 0; this.stepsCount = 0;

            // get start index
            if (this.options.step === false) {
                var activeSlide = this.slides.filter('.' + this.options.activeClass);
                if (activeSlide.length) {
                    this.currentStep = this.slides.index(activeSlide);
                }
            }

            // calculate offsets
            this.calculateOffsets();

            // create gallery pagination
            if (typeof this.options.generatePagination === 'string') {
                this.pagerLinks = $();
                this.buildPagination();
            } else {
                this.pagerLinks = this.gallery.find(this.options.pagerLinks);
                this.attachPaginationEvents();
            }

            // autorotation control buttons
            this.btnPlay = this.gallery.find(this.options.btnPlay);
            this.btnPause = this.gallery.find(this.options.btnPause);
            this.btnPlayPause = this.gallery.find(this.options.btnPlayPause);

            // misc elements
            this.curNum = this.gallery.find(this.options.currentNumber);
            this.allNum = this.gallery.find(this.options.totalNumber);
        },
        attachEvents: function () {
            // bind handlers scope
            var self = this;
            this.bindHandlers(['onWindowResize']);
            $(window).bind('load resize orientationchange', this.onWindowResize);

            // previous and next button handlers
            if (this.btnPrev.length) {
                this.prevSlideHandler = function (e) {
                    e.preventDefault();
                    self.prevSlide();
                };
                this.btnPrev.bind(this.options.event, this.prevSlideHandler);
            }
            if (this.btnNext.length) {
                this.nextSlideHandler = function (e) {
                    e.preventDefault();
                    self.nextSlide();
                };
                this.btnNext.bind(this.options.event, this.nextSlideHandler);
            }

            // pause on hover handling
            if (this.options.pauseOnHover && !isTouchDevice) {
                this.hoverHandler = function () {
                    if (self.options.autoRotation) {
                        self.galleryHover = true;
                        self.pauseRotation();
                    }
                };
                this.leaveHandler = function () {
                    if (self.options.autoRotation) {
                        self.galleryHover = false;
                        self.resumeRotation();
                    }
                };
                this.gallery.bind({ mouseenter: this.hoverHandler, mouseleave: this.leaveHandler });
            }

            // autorotation buttons handler
            if (this.btnPlay.length) {
                this.btnPlayHandler = function (e) {
                    e.preventDefault();
                    self.startRotation();
                };
                this.btnPlay.bind(this.options.event, this.btnPlayHandler);
            }
            if (this.btnPause.length) {
                this.btnPauseHandler = function (e) {
                    e.preventDefault();
                    self.stopRotation();
                };
                this.btnPause.bind(this.options.event, this.btnPauseHandler);
            }
            if (this.btnPlayPause.length) {
                this.btnPlayPauseHandler = function (e) {
                    e.preventDefault();
                    if (!self.gallery.hasClass(self.options.autorotationActiveClass)) {
                        self.startRotation();
                    } else {
                        self.stopRotation();
                    }
                };
                this.btnPlayPause.bind(this.options.event, this.btnPlayPauseHandler);
            }

            // enable hardware acceleration
            if (isTouchDevice && this.options.useTranslate3D) {
                this.slider.css({ '-webkit-transform': 'translate3d(0px, 0px, 0px)' });
            }

            // swipe event handling
            if (isTouchDevice && this.options.handleTouch && window.Hammer && this.mask.length) {
                this.swipeHandler = new Hammer.Manager(this.mask[0]);
                this.swipeHandler.add(new Hammer.Pan({
                    direction: self.options.vertical ? Hammer.DIRECTION_VERTICAL : Hammer.DIRECTION_HORIZONTAL,
                    threshold: self.options.swipeThreshold
                }));

                this.swipeHandler.on('panstart', function () {
                    if (self.galleryAnimating) {
                        self.swipeHandler.stop();
                    } else {
                        self.pauseRotation();
                        self.originalOffset = parseFloat(self.slider.css(self.animProperty));
                    }
                }).on('panmove', function (e) {
                    var tmpOffset = self.originalOffset + e[self.options.vertical ? 'deltaY' : 'deltaX'];
                    tmpOffset = Math.max(Math.min(0, tmpOffset), self.maxOffset);
                    self.slider.css(self.animProperty, tmpOffset);
                }).on('panend', function (e) {
                    self.resumeRotation();
                    if (e.distance > self.options.swipeThreshold) {
                        if (e.offsetDirection === Hammer.DIRECTION_RIGHT || e.offsetDirection === Hammer.DIRECTION_DOWN) {
                            self.nextSlide();
                        } else {
                            self.prevSlide();
                        }
                    } else {
                        self.switchSlide();
                    }
                });
            }
        },
        onWindowResize: function () {
            if (!this.galleryAnimating) {
                this.calculateOffsets();
                this.refreshPosition();
                this.buildPagination();
                this.refreshState();
                this.resizeQueue = false;
            } else {
                this.resizeQueue = true;
            }
        },
        refreshPosition: function () {
            this.currentStep = Math.min(this.currentStep, this.stepsCount - 1);
            this.tmpProps = {};
            this.tmpProps[this.animProperty] = this.getStepOffset();
            this.slider.stop().css(this.tmpProps);
        },
        calculateOffsets: function () {
            var self = this, tmpOffset, tmpStep;
            if (this.options.stretchSlideToMask) {
                var tmpObj = {};
                tmpObj[this.innerSizeFunction] = this.mask[this.innerSizeFunction]();
                this.slides.css(tmpObj);
            }

            this.maskSize = this.mask[this.innerSizeFunction]();
            this.sumSize = this.getSumSize();
            this.maxOffset = this.maskSize - this.sumSize;

            // vertical gallery with single size step custom behavior
            if (this.options.vertical && this.options.maskAutoSize) {
                this.options.step = 1;
                this.stepsCount = this.slides.length;
                this.stepOffsets = [0];
                tmpOffset = 0;
                for (var i = 0; i < this.slides.length; i++) {
                    tmpOffset -= $(this.slides[i])[this.fullSizeFunction](true);
                    this.stepOffsets.push(tmpOffset);
                }
                this.maxOffset = tmpOffset;
                return;
            }

            // scroll by slide size
            if (typeof this.options.step === 'number' && this.options.step > 0) {
                this.slideDimensions = [];
                this.slides.each($.proxy(function (ind, obj) {
                    self.slideDimensions.push($(obj)[self.fullSizeFunction](true));
                }, this));

                // calculate steps count
                this.stepOffsets = [0];
                this.stepsCount = 1;
                tmpOffset = tmpStep = 0;
                while (tmpOffset > this.maxOffset) {
                    tmpOffset -= this.getSlideSize(tmpStep, tmpStep + this.options.step);
                    tmpStep += this.options.step;
                    this.stepOffsets.push(Math.max(tmpOffset, this.maxOffset));
                    this.stepsCount++;
                }
            }
                // scroll by mask size
            else {
                // define step size
                this.stepSize = this.maskSize;

                // calculate steps count
                this.stepsCount = 1;
                tmpOffset = 0;
                while (tmpOffset > this.maxOffset) {
                    tmpOffset -= this.stepSize;
                    this.stepsCount++;
                }
            }
        },
        getSumSize: function () {
            var sum = 0;
            this.slides.each($.proxy(function (ind, obj) {
                sum += $(obj)[this.fullSizeFunction](true);
            }, this));
            this.slider.css(this.innerSizeFunction, sum);
            return sum;
        },
        getStepOffset: function (step) {
            step = step || this.currentStep;
            if (typeof this.options.step === 'number') {
                return this.stepOffsets[this.currentStep];
            } else {
                return Math.min(0, Math.max(-this.currentStep * this.stepSize, this.maxOffset));
            }
        },
        getSlideSize: function (i1, i2) {
            var sum = 0;
            for (var i = i1; i < Math.min(i2, this.slideDimensions.length) ; i++) {
                sum += this.slideDimensions[i];
            }
            return sum;
        },
        buildPagination: function () {
            if (typeof this.options.generatePagination === 'string') {
                if (!this.pagerHolder) {
                    this.pagerHolder = this.gallery.find(this.options.generatePagination);
                }
                if (this.pagerHolder.length && this.oldStepsCount != this.stepsCount) {
                    this.oldStepsCount = this.stepsCount;
                    this.pagerHolder.empty();
                    this.pagerList = $(this.options.pagerList).appendTo(this.pagerHolder);
                    for (var i = 0; i < this.stepsCount; i++) {
                        $(this.options.pagerListItem).appendTo(this.pagerList).find(this.options.pagerListItemText).text(i + 1);
                    }
                    this.pagerLinks = this.pagerList.children();
                    this.attachPaginationEvents();
                }
            }
        },
        attachPaginationEvents: function () {
            var self = this;
            this.pagerLinksHandler = function (e) {
                e.preventDefault();
                self.numSlide(self.pagerLinks.index(e.currentTarget));
            };
            this.pagerLinks.bind(this.options.event, this.pagerLinksHandler);
        },
        prevSlide: function () {
            if (!(this.options.disableWhileAnimating && this.galleryAnimating)) {
                if (this.currentStep > 0) {
                    this.currentStep--;
                    this.switchSlide();
                } else if (this.options.circularRotation) {
                    this.currentStep = this.stepsCount - 1;
                    this.switchSlide();
                }
            }
        },
        nextSlide: function (fromAutoRotation) {
            if (!(this.options.disableWhileAnimating && this.galleryAnimating)) {
                if (this.currentStep < this.stepsCount - 1) {
                    this.currentStep++;
                    this.switchSlide();
                } else if (this.options.circularRotation || fromAutoRotation === true) {
                    this.currentStep = 0;
                    this.switchSlide();
                }
            }
        },
        numSlide: function (c) {
            if (this.currentStep != c) {
                this.currentStep = c;
                this.switchSlide();
            }
        },
        switchSlide: function () {
            var self = this;
            this.galleryAnimating = true;
            this.tmpProps = {};
            this.tmpProps[this.animProperty] = this.getStepOffset();
            this.slider.stop().animate(this.tmpProps, {
                duration: this.options.animSpeed, complete: function () {
                    // animation complete
                    self.galleryAnimating = false;
                    if (self.resizeQueue) {
                        self.onWindowResize();
                    }

                    // onchange callback
                    self.makeCallback('onChange', self);
                    self.autoRotate();
                }
            });
            this.refreshState();

            // onchange callback
            this.makeCallback('onBeforeChange', this);
        },
        refreshState: function (initial) {
            if (this.options.step === 1 || this.stepsCount === this.slides.length) {
                this.slides.removeClass(this.options.activeClass).eq(this.currentStep).addClass(this.options.activeClass);
            }
            this.pagerLinks.removeClass(this.options.activeClass).eq(this.currentStep).addClass(this.options.activeClass);
            this.curNum.html(this.currentStep + 1);
            this.allNum.html(this.stepsCount);

            // initial refresh
            if (this.options.maskAutoSize && typeof this.options.step === 'number') {
                this.tmpProps = {};
                this.tmpProps[this.maskSizeProperty] = this.slides.eq(Math.min(this.currentStep, this.slides.length - 1))[this.slideSizeFunction](true);
                this.mask.stop()[initial ? 'css' : 'animate'](this.tmpProps);
            }

            // disabled state
            if (!this.options.circularRotation) {
                this.btnPrev.add(this.btnNext).removeClass(this.options.disabledClass);
                if (this.currentStep === 0) this.btnPrev.addClass(this.options.disabledClass);
                if (this.currentStep === this.stepsCount - 1) this.btnNext.addClass(this.options.disabledClass);
            }

            // add class if not enough slides
            this.gallery.toggleClass('not-enough-slides', this.sumSize <= this.maskSize);
        },
        startRotation: function () {
            this.options.autoRotation = true;
            this.galleryHover = false;
            this.autoRotationStopped = false;
            this.resumeRotation();
        },
        stopRotation: function () {
            this.galleryHover = true;
            this.autoRotationStopped = true;
            this.pauseRotation();
        },
        pauseRotation: function () {
            this.gallery.addClass(this.options.autorotationDisabledClass);
            this.gallery.removeClass(this.options.autorotationActiveClass);
            clearTimeout(this.timer);
        },
        resumeRotation: function () {
            if (!this.autoRotationStopped) {
                this.gallery.addClass(this.options.autorotationActiveClass);
                this.gallery.removeClass(this.options.autorotationDisabledClass);
                this.autoRotate();
            }
        },
        autoRotate: function () {
            var self = this;
            clearTimeout(this.timer);
            if (this.options.autoRotation && !this.galleryHover && !this.autoRotationStopped) {
                this.timer = setTimeout(function () {
                    self.nextSlide(true);
                }, this.options.switchTime);
            } else {
                this.pauseRotation();
            }
        },
        bindHandlers: function (handlersList) {
            var self = this;
            $.each(handlersList, function (index, handler) {
                var origHandler = self[handler];
                self[handler] = function () {
                    return origHandler.apply(self, arguments);
                };
            });
        },
        makeCallback: function (name) {
            if (typeof this.options[name] === 'function') {
                var args = Array.prototype.slice.call(arguments);
                args.shift();
                this.options[name].apply(this, args);
            }
        },
        destroy: function () {
            // destroy handler
            $(window).unbind('load resize orientationchange', this.onWindowResize);
            this.btnPrev.unbind(this.options.event, this.prevSlideHandler);
            this.btnNext.unbind(this.options.event, this.nextSlideHandler);
            this.pagerLinks.unbind(this.options.event, this.pagerLinksHandler);
            this.gallery.unbind('mouseenter', this.hoverHandler);
            this.gallery.unbind('mouseleave', this.leaveHandler);

            // autorotation buttons handlers
            this.stopRotation();
            this.btnPlay.unbind(this.options.event, this.btnPlayHandler);
            this.btnPause.unbind(this.options.event, this.btnPauseHandler);
            this.btnPlayPause.unbind(this.options.event, this.btnPlayPauseHandler);

            // destroy swipe handler
            if (this.swipeHandler) {
                this.swipeHandler.destroy();
            }

            // remove inline styles, classes and pagination
            var unneededClasses = [this.options.galleryReadyClass, this.options.autorotationActiveClass, this.options.autorotationDisabledClass];
            this.gallery.removeClass(unneededClasses.join(' '));
            this.slider.add(this.slides).removeAttr('style');
            if (typeof this.options.generatePagination === 'string') {
                this.pagerHolder.empty();
            }
        }
    };

    // detect device type
    var isTouchDevice = /Windows Phone/.test(navigator.userAgent) || ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;

    // jquery plugin
    $.fn.scrollGallery = function (opt) {
        return this.each(function () {
            $(this).data('ScrollGallery', new ScrollGallery($.extend(opt, { holder: this })));
        });
    };
}(jQuery));

/*! Hammer.JS - v2.0.4 - 2014-09-28
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2014 Jorik Tangelder;
 * Licensed under the MIT license */
if (Object.create) { !function (a, b, c, d) { "use strict"; function e(a, b, c) { return setTimeout(k(a, c), b) } function f(a, b, c) { return Array.isArray(a) ? (g(a, c[b], c), !0) : !1 } function g(a, b, c) { var e; if (a) if (a.forEach) a.forEach(b, c); else if (a.length !== d) for (e = 0; e < a.length;) b.call(c, a[e], e, a), e++; else for (e in a) a.hasOwnProperty(e) && b.call(c, a[e], e, a) } function h(a, b, c) { for (var e = Object.keys(b), f = 0; f < e.length;) (!c || c && a[e[f]] === d) && (a[e[f]] = b[e[f]]), f++; return a } function i(a, b) { return h(a, b, !0) } function j(a, b, c) { var d, e = b.prototype; d = a.prototype = Object.create(e), d.constructor = a, d._super = e, c && h(d, c) } function k(a, b) { return function () { return a.apply(b, arguments) } } function l(a, b) { return typeof a == kb ? a.apply(b ? b[0] || d : d, b) : a } function m(a, b) { return a === d ? b : a } function n(a, b, c) { g(r(b), function (b) { a.addEventListener(b, c, !1) }) } function o(a, b, c) { g(r(b), function (b) { a.removeEventListener(b, c, !1) }) } function p(a, b) { for (; a;) { if (a == b) return !0; a = a.parentNode } return !1 } function q(a, b) { return a.indexOf(b) > -1 } function r(a) { return a.trim().split(/\s+/g) } function s(a, b, c) { if (a.indexOf && !c) return a.indexOf(b); for (var d = 0; d < a.length;) { if (c && a[d][c] == b || !c && a[d] === b) return d; d++ } return -1 } function t(a) { return Array.prototype.slice.call(a, 0) } function u(a, b, c) { for (var d = [], e = [], f = 0; f < a.length;) { var g = b ? a[f][b] : a[f]; s(e, g) < 0 && d.push(a[f]), e[f] = g, f++ } return c && (d = b ? d.sort(function (a, c) { return a[b] > c[b] }) : d.sort()), d } function v(a, b) { for (var c, e, f = b[0].toUpperCase() + b.slice(1), g = 0; g < ib.length;) { if (c = ib[g], e = c ? c + f : b, e in a) return e; g++ } return d } function w() { return ob++ } function x(a) { var b = a.ownerDocument; return b.defaultView || b.parentWindow } function y(a, b) { var c = this; this.manager = a, this.callback = b, this.element = a.element, this.target = a.options.inputTarget, this.domHandler = function (b) { l(a.options.enable, [a]) && c.handler(b) }, this.init() } function z(a) { var b, c = a.options.inputClass; return new (b = c ? c : rb ? N : sb ? Q : qb ? S : M)(a, A) } function A(a, b, c) { var d = c.pointers.length, e = c.changedPointers.length, f = b & yb && d - e === 0, g = b & (Ab | Bb) && d - e === 0; c.isFirst = !!f, c.isFinal = !!g, f && (a.session = {}), c.eventType = b, B(a, c), a.emit("hammer.input", c), a.recognize(c), a.session.prevInput = c } function B(a, b) { var c = a.session, d = b.pointers, e = d.length; c.firstInput || (c.firstInput = E(b)), e > 1 && !c.firstMultiple ? c.firstMultiple = E(b) : 1 === e && (c.firstMultiple = !1); var f = c.firstInput, g = c.firstMultiple, h = g ? g.center : f.center, i = b.center = F(d); b.timeStamp = nb(), b.deltaTime = b.timeStamp - f.timeStamp, b.angle = J(h, i), b.distance = I(h, i), C(c, b), b.offsetDirection = H(b.deltaX, b.deltaY), b.scale = g ? L(g.pointers, d) : 1, b.rotation = g ? K(g.pointers, d) : 0, D(c, b); var j = a.element; p(b.srcEvent.target, j) && (j = b.srcEvent.target), b.target = j } function C(a, b) { var c = b.center, d = a.offsetDelta || {}, e = a.prevDelta || {}, f = a.prevInput || {}; (b.eventType === yb || f.eventType === Ab) && (e = a.prevDelta = { x: f.deltaX || 0, y: f.deltaY || 0 }, d = a.offsetDelta = { x: c.x, y: c.y }), b.deltaX = e.x + (c.x - d.x), b.deltaY = e.y + (c.y - d.y) } function D(a, b) { var c, e, f, g, h = a.lastInterval || b, i = b.timeStamp - h.timeStamp; if (b.eventType != Bb && (i > xb || h.velocity === d)) { var j = h.deltaX - b.deltaX, k = h.deltaY - b.deltaY, l = G(i, j, k); e = l.x, f = l.y, c = mb(l.x) > mb(l.y) ? l.x : l.y, g = H(j, k), a.lastInterval = b } else c = h.velocity, e = h.velocityX, f = h.velocityY, g = h.direction; b.velocity = c, b.velocityX = e, b.velocityY = f, b.direction = g } function E(a) { for (var b = [], c = 0; c < a.pointers.length;) b[c] = { clientX: lb(a.pointers[c].clientX), clientY: lb(a.pointers[c].clientY) }, c++; return { timeStamp: nb(), pointers: b, center: F(b), deltaX: a.deltaX, deltaY: a.deltaY } } function F(a) { var b = a.length; if (1 === b) return { x: lb(a[0].clientX), y: lb(a[0].clientY) }; for (var c = 0, d = 0, e = 0; b > e;) c += a[e].clientX, d += a[e].clientY, e++; return { x: lb(c / b), y: lb(d / b) } } function G(a, b, c) { return { x: b / a || 0, y: c / a || 0 } } function H(a, b) { return a === b ? Cb : mb(a) >= mb(b) ? a > 0 ? Db : Eb : b > 0 ? Fb : Gb } function I(a, b, c) { c || (c = Kb); var d = b[c[0]] - a[c[0]], e = b[c[1]] - a[c[1]]; return Math.sqrt(d * d + e * e) } function J(a, b, c) { c || (c = Kb); var d = b[c[0]] - a[c[0]], e = b[c[1]] - a[c[1]]; return 180 * Math.atan2(e, d) / Math.PI } function K(a, b) { return J(b[1], b[0], Lb) - J(a[1], a[0], Lb) } function L(a, b) { return I(b[0], b[1], Lb) / I(a[0], a[1], Lb) } function M() { this.evEl = Nb, this.evWin = Ob, this.allow = !0, this.pressed = !1, y.apply(this, arguments) } function N() { this.evEl = Rb, this.evWin = Sb, y.apply(this, arguments), this.store = this.manager.session.pointerEvents = [] } function O() { this.evTarget = Ub, this.evWin = Vb, this.started = !1, y.apply(this, arguments) } function P(a, b) { var c = t(a.touches), d = t(a.changedTouches); return b & (Ab | Bb) && (c = u(c.concat(d), "identifier", !0)), [c, d] } function Q() { this.evTarget = Xb, this.targetIds = {}, y.apply(this, arguments) } function R(a, b) { var c = t(a.touches), d = this.targetIds; if (b & (yb | zb) && 1 === c.length) return d[c[0].identifier] = !0, [c, c]; var e, f, g = t(a.changedTouches), h = [], i = this.target; if (f = c.filter(function (a) { return p(a.target, i) }), b === yb) for (e = 0; e < f.length;) d[f[e].identifier] = !0, e++; for (e = 0; e < g.length;) d[g[e].identifier] && h.push(g[e]), b & (Ab | Bb) && delete d[g[e].identifier], e++; return h.length ? [u(f.concat(h), "identifier", !0), h] : void 0 } function S() { y.apply(this, arguments); var a = k(this.handler, this); this.touch = new Q(this.manager, a), this.mouse = new M(this.manager, a) } function T(a, b) { this.manager = a, this.set(b) } function U(a) { if (q(a, bc)) return bc; var b = q(a, cc), c = q(a, dc); return b && c ? cc + " " + dc : b || c ? b ? cc : dc : q(a, ac) ? ac : _b } function V(a) { this.id = w(), this.manager = null, this.options = i(a || {}, this.defaults), this.options.enable = m(this.options.enable, !0), this.state = ec, this.simultaneous = {}, this.requireFail = [] } function W(a) { return a & jc ? "cancel" : a & hc ? "end" : a & gc ? "move" : a & fc ? "start" : "" } function X(a) { return a == Gb ? "down" : a == Fb ? "up" : a == Db ? "left" : a == Eb ? "right" : "" } function Y(a, b) { var c = b.manager; return c ? c.get(a) : a } function Z() { V.apply(this, arguments) } function $() { Z.apply(this, arguments), this.pX = null, this.pY = null } function _() { Z.apply(this, arguments) } function ab() { V.apply(this, arguments), this._timer = null, this._input = null } function bb() { Z.apply(this, arguments) } function cb() { Z.apply(this, arguments) } function db() { V.apply(this, arguments), this.pTime = !1, this.pCenter = !1, this._timer = null, this._input = null, this.count = 0 } function eb(a, b) { return b = b || {}, b.recognizers = m(b.recognizers, eb.defaults.preset), new fb(a, b) } function fb(a, b) { b = b || {}, this.options = i(b, eb.defaults), this.options.inputTarget = this.options.inputTarget || a, this.handlers = {}, this.session = {}, this.recognizers = [], this.element = a, this.input = z(this), this.touchAction = new T(this, this.options.touchAction), gb(this, !0), g(b.recognizers, function (a) { var b = this.add(new a[0](a[1])); a[2] && b.recognizeWith(a[2]), a[3] && b.requireFailure(a[3]) }, this) } function gb(a, b) { var c = a.element; g(a.options.cssProps, function (a, d) { c.style[v(c.style, d)] = b ? a : "" }) } function hb(a, c) { var d = b.createEvent("Event"); d.initEvent(a, !0, !0), d.gesture = c, c.target.dispatchEvent(d) } var ib = ["", "webkit", "moz", "MS", "ms", "o"], jb = b.createElement("div"), kb = "function", lb = Math.round, mb = Math.abs, nb = Date.now, ob = 1, pb = /mobile|tablet|ip(ad|hone|od)|android/i, qb = "ontouchstart" in a, rb = v(a, "PointerEvent") !== d, sb = qb && pb.test(navigator.userAgent), tb = "touch", ub = "pen", vb = "mouse", wb = "kinect", xb = 25, yb = 1, zb = 2, Ab = 4, Bb = 8, Cb = 1, Db = 2, Eb = 4, Fb = 8, Gb = 16, Hb = Db | Eb, Ib = Fb | Gb, Jb = Hb | Ib, Kb = ["x", "y"], Lb = ["clientX", "clientY"]; y.prototype = { handler: function () { }, init: function () { this.evEl && n(this.element, this.evEl, this.domHandler), this.evTarget && n(this.target, this.evTarget, this.domHandler), this.evWin && n(x(this.element), this.evWin, this.domHandler) }, destroy: function () { this.evEl && o(this.element, this.evEl, this.domHandler), this.evTarget && o(this.target, this.evTarget, this.domHandler), this.evWin && o(x(this.element), this.evWin, this.domHandler) } }; var Mb = { mousedown: yb, mousemove: zb, mouseup: Ab }, Nb = "mousedown", Ob = "mousemove mouseup"; j(M, y, { handler: function (a) { var b = Mb[a.type]; b & yb && 0 === a.button && (this.pressed = !0), b & zb && 1 !== a.which && (b = Ab), this.pressed && this.allow && (b & Ab && (this.pressed = !1), this.callback(this.manager, b, { pointers: [a], changedPointers: [a], pointerType: vb, srcEvent: a })) } }); var Pb = { pointerdown: yb, pointermove: zb, pointerup: Ab, pointercancel: Bb, pointerout: Bb }, Qb = { 2: tb, 3: ub, 4: vb, 5: wb }, Rb = "pointerdown", Sb = "pointermove pointerup pointercancel"; a.MSPointerEvent && (Rb = "MSPointerDown", Sb = "MSPointerMove MSPointerUp MSPointerCancel"), j(N, y, { handler: function (a) { var b = this.store, c = !1, d = a.type.toLowerCase().replace("ms", ""), e = Pb[d], f = Qb[a.pointerType] || a.pointerType, g = f == tb, h = s(b, a.pointerId, "pointerId"); e & yb && (0 === a.button || g) ? 0 > h && (b.push(a), h = b.length - 1) : e & (Ab | Bb) && (c = !0), 0 > h || (b[h] = a, this.callback(this.manager, e, { pointers: b, changedPointers: [a], pointerType: f, srcEvent: a }), c && b.splice(h, 1)) } }); var Tb = { touchstart: yb, touchmove: zb, touchend: Ab, touchcancel: Bb }, Ub = "touchstart", Vb = "touchstart touchmove touchend touchcancel"; j(O, y, { handler: function (a) { var b = Tb[a.type]; if (b === yb && (this.started = !0), this.started) { var c = P.call(this, a, b); b & (Ab | Bb) && c[0].length - c[1].length === 0 && (this.started = !1), this.callback(this.manager, b, { pointers: c[0], changedPointers: c[1], pointerType: tb, srcEvent: a }) } } }); var Wb = { touchstart: yb, touchmove: zb, touchend: Ab, touchcancel: Bb }, Xb = "touchstart touchmove touchend touchcancel"; j(Q, y, { handler: function (a) { var b = Wb[a.type], c = R.call(this, a, b); c && this.callback(this.manager, b, { pointers: c[0], changedPointers: c[1], pointerType: tb, srcEvent: a }) } }), j(S, y, { handler: function (a, b, c) { var d = c.pointerType == tb, e = c.pointerType == vb; if (d) this.mouse.allow = !1; else if (e && !this.mouse.allow) return; b & (Ab | Bb) && (this.mouse.allow = !0), this.callback(a, b, c) }, destroy: function () { this.touch.destroy(), this.mouse.destroy() } }); var Yb = v(jb.style, "touchAction"), Zb = Yb !== d, $b = "compute", _b = "auto", ac = "manipulation", bc = "none", cc = "pan-x", dc = "pan-y"; T.prototype = { set: function (a) { a == $b && (a = this.compute()), Zb && (this.manager.element.style[Yb] = a), this.actions = a.toLowerCase().trim() }, update: function () { this.set(this.manager.options.touchAction) }, compute: function () { var a = []; return g(this.manager.recognizers, function (b) { l(b.options.enable, [b]) && (a = a.concat(b.getTouchAction())) }), U(a.join(" ")) }, preventDefaults: function (a) { if (!Zb) { var b = a.srcEvent, c = a.offsetDirection; if (this.manager.session.prevented) return void b.preventDefault(); var d = this.actions, e = q(d, bc), f = q(d, dc), g = q(d, cc); return e || f && c & Hb || g && c & Ib ? this.preventSrc(b) : void 0 } }, preventSrc: function (a) { this.manager.session.prevented = !0, a.preventDefault() } }; var ec = 1, fc = 2, gc = 4, hc = 8, ic = hc, jc = 16, kc = 32; V.prototype = { defaults: {}, set: function (a) { return h(this.options, a), this.manager && this.manager.touchAction.update(), this }, recognizeWith: function (a) { if (f(a, "recognizeWith", this)) return this; var b = this.simultaneous; return a = Y(a, this), b[a.id] || (b[a.id] = a, a.recognizeWith(this)), this }, dropRecognizeWith: function (a) { return f(a, "dropRecognizeWith", this) ? this : (a = Y(a, this), delete this.simultaneous[a.id], this) }, requireFailure: function (a) { if (f(a, "requireFailure", this)) return this; var b = this.requireFail; return a = Y(a, this), -1 === s(b, a) && (b.push(a), a.requireFailure(this)), this }, dropRequireFailure: function (a) { if (f(a, "dropRequireFailure", this)) return this; a = Y(a, this); var b = s(this.requireFail, a); return b > -1 && this.requireFail.splice(b, 1), this }, hasRequireFailures: function () { return this.requireFail.length > 0 }, canRecognizeWith: function (a) { return !!this.simultaneous[a.id] }, emit: function (a) { function b(b) { c.manager.emit(c.options.event + (b ? W(d) : ""), a) } var c = this, d = this.state; hc > d && b(!0), b(), d >= hc && b(!0) }, tryEmit: function (a) { return this.canEmit() ? this.emit(a) : void (this.state = kc) }, canEmit: function () { for (var a = 0; a < this.requireFail.length;) { if (!(this.requireFail[a].state & (kc | ec))) return !1; a++ } return !0 }, recognize: function (a) { var b = h({}, a); return l(this.options.enable, [this, b]) ? (this.state & (ic | jc | kc) && (this.state = ec), this.state = this.process(b), void (this.state & (fc | gc | hc | jc) && this.tryEmit(b))) : (this.reset(), void (this.state = kc)) }, process: function () { }, getTouchAction: function () { }, reset: function () { } }, j(Z, V, { defaults: { pointers: 1 }, attrTest: function (a) { var b = this.options.pointers; return 0 === b || a.pointers.length === b }, process: function (a) { var b = this.state, c = a.eventType, d = b & (fc | gc), e = this.attrTest(a); return d && (c & Bb || !e) ? b | jc : d || e ? c & Ab ? b | hc : b & fc ? b | gc : fc : kc } }), j($, Z, { defaults: { event: "pan", threshold: 10, pointers: 1, direction: Jb }, getTouchAction: function () { var a = this.options.direction, b = []; return a & Hb && b.push(dc), a & Ib && b.push(cc), b }, directionTest: function (a) { var b = this.options, c = !0, d = a.distance, e = a.direction, f = a.deltaX, g = a.deltaY; return e & b.direction || (b.direction & Hb ? (e = 0 === f ? Cb : 0 > f ? Db : Eb, c = f != this.pX, d = Math.abs(a.deltaX)) : (e = 0 === g ? Cb : 0 > g ? Fb : Gb, c = g != this.pY, d = Math.abs(a.deltaY))), a.direction = e, c && d > b.threshold && e & b.direction }, attrTest: function (a) { return Z.prototype.attrTest.call(this, a) && (this.state & fc || !(this.state & fc) && this.directionTest(a)) }, emit: function (a) { this.pX = a.deltaX, this.pY = a.deltaY; var b = X(a.direction); b && this.manager.emit(this.options.event + b, a), this._super.emit.call(this, a) } }), j(_, Z, { defaults: { event: "pinch", threshold: 0, pointers: 2 }, getTouchAction: function () { return [bc] }, attrTest: function (a) { return this._super.attrTest.call(this, a) && (Math.abs(a.scale - 1) > this.options.threshold || this.state & fc) }, emit: function (a) { if (this._super.emit.call(this, a), 1 !== a.scale) { var b = a.scale < 1 ? "in" : "out"; this.manager.emit(this.options.event + b, a) } } }), j(ab, V, { defaults: { event: "press", pointers: 1, time: 500, threshold: 5 }, getTouchAction: function () { return [_b] }, process: function (a) { var b = this.options, c = a.pointers.length === b.pointers, d = a.distance < b.threshold, f = a.deltaTime > b.time; if (this._input = a, !d || !c || a.eventType & (Ab | Bb) && !f) this.reset(); else if (a.eventType & yb) this.reset(), this._timer = e(function () { this.state = ic, this.tryEmit() }, b.time, this); else if (a.eventType & Ab) return ic; return kc }, reset: function () { clearTimeout(this._timer) }, emit: function (a) { this.state === ic && (a && a.eventType & Ab ? this.manager.emit(this.options.event + "up", a) : (this._input.timeStamp = nb(), this.manager.emit(this.options.event, this._input))) } }), j(bb, Z, { defaults: { event: "rotate", threshold: 0, pointers: 2 }, getTouchAction: function () { return [bc] }, attrTest: function (a) { return this._super.attrTest.call(this, a) && (Math.abs(a.rotation) > this.options.threshold || this.state & fc) } }), j(cb, Z, { defaults: { event: "swipe", threshold: 10, velocity: .65, direction: Hb | Ib, pointers: 1 }, getTouchAction: function () { return $.prototype.getTouchAction.call(this) }, attrTest: function (a) { var b, c = this.options.direction; return c & (Hb | Ib) ? b = a.velocity : c & Hb ? b = a.velocityX : c & Ib && (b = a.velocityY), this._super.attrTest.call(this, a) && c & a.direction && a.distance > this.options.threshold && mb(b) > this.options.velocity && a.eventType & Ab }, emit: function (a) { var b = X(a.direction); b && this.manager.emit(this.options.event + b, a), this.manager.emit(this.options.event, a) } }), j(db, V, { defaults: { event: "tap", pointers: 1, taps: 1, interval: 300, time: 250, threshold: 2, posThreshold: 10 }, getTouchAction: function () { return [ac] }, process: function (a) { var b = this.options, c = a.pointers.length === b.pointers, d = a.distance < b.threshold, f = a.deltaTime < b.time; if (this.reset(), a.eventType & yb && 0 === this.count) return this.failTimeout(); if (d && f && c) { if (a.eventType != Ab) return this.failTimeout(); var g = this.pTime ? a.timeStamp - this.pTime < b.interval : !0, h = !this.pCenter || I(this.pCenter, a.center) < b.posThreshold; this.pTime = a.timeStamp, this.pCenter = a.center, h && g ? this.count += 1 : this.count = 1, this._input = a; var i = this.count % b.taps; if (0 === i) return this.hasRequireFailures() ? (this._timer = e(function () { this.state = ic, this.tryEmit() }, b.interval, this), fc) : ic } return kc }, failTimeout: function () { return this._timer = e(function () { this.state = kc }, this.options.interval, this), kc }, reset: function () { clearTimeout(this._timer) }, emit: function () { this.state == ic && (this._input.tapCount = this.count, this.manager.emit(this.options.event, this._input)) } }), eb.VERSION = "2.0.4", eb.defaults = { domEvents: !1, touchAction: $b, enable: !0, inputTarget: null, inputClass: null, preset: [[bb, { enable: !1 }], [_, { enable: !1 }, ["rotate"]], [cb, { direction: Hb }], [$, { direction: Hb }, ["swipe"]], [db], [db, { event: "doubletap", taps: 2 }, ["tap"]], [ab]], cssProps: { userSelect: "none", touchSelect: "none", touchCallout: "none", contentZooming: "none", userDrag: "none", tapHighlightColor: "rgba(0,0,0,0)" } }; var lc = 1, mc = 2; fb.prototype = { set: function (a) { return h(this.options, a), a.touchAction && this.touchAction.update(), a.inputTarget && (this.input.destroy(), this.input.target = a.inputTarget, this.input.init()), this }, stop: function (a) { this.session.stopped = a ? mc : lc }, recognize: function (a) { var b = this.session; if (!b.stopped) { this.touchAction.preventDefaults(a); var c, d = this.recognizers, e = b.curRecognizer; (!e || e && e.state & ic) && (e = b.curRecognizer = null); for (var f = 0; f < d.length;) c = d[f], b.stopped === mc || e && c != e && !c.canRecognizeWith(e) ? c.reset() : c.recognize(a), !e && c.state & (fc | gc | hc) && (e = b.curRecognizer = c), f++ } }, get: function (a) { if (a instanceof V) return a; for (var b = this.recognizers, c = 0; c < b.length; c++) if (b[c].options.event == a) return b[c]; return null }, add: function (a) { if (f(a, "add", this)) return this; var b = this.get(a.options.event); return b && this.remove(b), this.recognizers.push(a), a.manager = this, this.touchAction.update(), a }, remove: function (a) { if (f(a, "remove", this)) return this; var b = this.recognizers; return a = this.get(a), b.splice(s(b, a), 1), this.touchAction.update(), this }, on: function (a, b) { var c = this.handlers; return g(r(a), function (a) { c[a] = c[a] || [], c[a].push(b) }), this }, off: function (a, b) { var c = this.handlers; return g(r(a), function (a) { b ? c[a].splice(s(c[a], b), 1) : delete c[a] }), this }, emit: function (a, b) { this.options.domEvents && hb(a, b); var c = this.handlers[a] && this.handlers[a].slice(); if (c && c.length) { b.type = a, b.preventDefault = function () { b.srcEvent.preventDefault() }; for (var d = 0; d < c.length;) c[d](b), d++ } }, destroy: function () { this.element && gb(this, !1), this.handlers = {}, this.session = {}, this.input.destroy(), this.element = null } }, h(eb, { INPUT_START: yb, INPUT_MOVE: zb, INPUT_END: Ab, INPUT_CANCEL: Bb, STATE_POSSIBLE: ec, STATE_BEGAN: fc, STATE_CHANGED: gc, STATE_ENDED: hc, STATE_RECOGNIZED: ic, STATE_CANCELLED: jc, STATE_FAILED: kc, DIRECTION_NONE: Cb, DIRECTION_LEFT: Db, DIRECTION_RIGHT: Eb, DIRECTION_UP: Fb, DIRECTION_DOWN: Gb, DIRECTION_HORIZONTAL: Hb, DIRECTION_VERTICAL: Ib, DIRECTION_ALL: Jb, Manager: fb, Input: y, TouchAction: T, TouchInput: Q, MouseInput: M, PointerEventInput: N, TouchMouseInput: S, SingleTouchInput: O, Recognizer: V, AttrRecognizer: Z, Tap: db, Pan: $, Swipe: cb, Pinch: _, Rotate: bb, Press: ab, on: n, off: o, each: g, merge: i, extend: h, inherit: j, bindFn: k, prefixed: v }), typeof define == kb && define.amd ? define(function () { return eb }) : "undefined" != typeof module && module.exports ? module.exports = eb : a[c] = eb }(window, document, "Hammer"); }



/*
 * Simple Mobile Navigation
 */
; (function ($) {
    function MobileNav(options) {
        this.options = $.extend({
            container: null,
            hideOnClickOutside: false,
            menuActiveClass: 'nav-active',
            menuOpener: '.nav-opener',
            menuDrop: '.nav-drop',
            toggleEvent: 'click',
            outsideClickEvent: 'click touchstart pointerdown MSPointerDown'
        }, options);
        this.initStructure();
        this.attachEvents();
    }
    MobileNav.prototype = {
        initStructure: function () {
            this.page = $('html');
            this.container = $(this.options.container);
            this.opener = this.container.find(this.options.menuOpener);
            this.drop = this.container.find(this.options.menuDrop);
        },
        attachEvents: function () {
            var self = this;

            if (activateResizeHandler) {
                activateResizeHandler();
                activateResizeHandler = null;
            }

            this.outsideClickHandler = function (e) {
                if (self.isOpened()) {
                    var target = $(e.target);
                    if (!target.closest(self.opener).length && !target.closest(self.drop).length) {
                        self.hide();
                    }
                }
            };

            this.openerClickHandler = function (e) {
                e.preventDefault();
                self.toggle();
            };

            this.opener.on(this.options.toggleEvent, this.openerClickHandler);
        },
        isOpened: function () {
            return this.container.hasClass(this.options.menuActiveClass);
        },
        show: function () {
            this.container.addClass(this.options.menuActiveClass);
            if (this.options.hideOnClickOutside) {
                this.page.on(this.options.outsideClickEvent, this.outsideClickHandler);
            }
        },
        hide: function () {
            this.container.removeClass(this.options.menuActiveClass);
            if (this.options.hideOnClickOutside) {
                this.page.off(this.options.outsideClickEvent, this.outsideClickHandler);
            }
        },
        toggle: function () {
            if (this.isOpened()) {
                this.hide();
            } else {
                this.show();
            }
        },
        destroy: function () {
            this.container.removeClass(this.options.menuActiveClass);
            this.opener.off(this.options.toggleEvent, this.clickHandler);
            this.page.off(this.options.outsideClickEvent, this.outsideClickHandler);
        }
    };

    var activateResizeHandler = function () {
        var win = $(window),
			doc = $('html'),
			resizeClass = 'resize-active',
			flag, timer;
        var removeClassHandler = function () {
            flag = false;
            doc.removeClass(resizeClass);
        };
        var resizeHandler = function () {
            if (!flag) {
                flag = true;
                doc.addClass(resizeClass);
            }
            clearTimeout(timer);
            timer = setTimeout(removeClassHandler, 500);
        };
        win.on('resize orientationchange', resizeHandler);
    };

    $.fn.mobileNav = function (options) {
        return this.each(function () {
            var params = $.extend({}, options, { container: this }),
				instance = new MobileNav(params);
            $.data(this, 'MobileNav', instance);
        });
    };
}(jQuery));


/*
 * jQuery Load More plugin
 */
; (function ($, $win) {
    'use strict';

    var ScrollLoader = {
        attachEvents: function () {
            var self = this;

            $win.on('load.ScrollLoader resize.ScrollLoader orientationchange.ScrollLoader', function () { self.onResizeHandler(); });
            $win.on('scroll.ScrollLoader', function () { self.onScrollHandler(); });
            this.$holder.on('ContentLoader/loaded.ScrollLoader', function () { self.onResizeHandler(); });

            this.winProps = {};
            this.holderProps = {};
            this.onResizeHandler();
        },

        onResizeHandler: function () {
            this.winProps.height = $win.height();
            this.holderProps.height = this.$holder.outerHeight();
            this.holderProps.offset = this.$holder.offset().top;

            this.onScrollHandler();
        },

        onScrollHandler: function () {
            this.winProps.scroll = $win.scrollTop();

            if (this.winProps.scroll + this.winProps.height + Math.min(1, this.options.additionBottomOffset) > this.holderProps.height + this.holderProps.offset) {
                this.loadInclude();
            }
        },

        destroySubEvents: function () {
            $win.off('.ScrollLoader');
            this.$holder.off('.ScrollLoader');
        }
    };

    var ClickLoader = {
        attachEvents: function () {
            var self = this;

            this.$holder.on('click.ClickLoader', this.options.linkSelector, function (e) { self.onClickHandler(e); });
        },

        onClickHandler: function (e) {
            e.preventDefault();

            this.loadInclude();
        },

        destroySubEvents: function () {
            this.$holder.off('.ClickLoader');
        }
    };

    var ContentLoader = function ($holder, options) {
        this.$holder = $holder;
        this.options = options;

        this.init();
    };

    var ContentLoaderProto = {
        init: function () {
            this.$link = this.$holder.find(this.options.linkSelector);
            this.$newContentTarget = this.options.newContentTarget ? this.$holder.find(this.options.newContentTarget) : this.$holder;

            if (!this.$link.length) {
                this.removeInstance();
                return;
            }

            this.attachEvents();
        },

        loadInclude: function () {
            if (this.isBusy) {
                return;
            }

            var self = this;

            this.toggleBusyMode(true);

            $.get(self.$link.attr('href'), function (source) { self.successHandler(source); });
        },

        successHandler: function (include) {
            var $tmpDiv = jQuery('<div>').html(include);
            var $nextIncludeLink = $tmpDiv.find(this.options.linkSelector);

            if ($nextIncludeLink.length) {
                this.refreshLink($nextIncludeLink);
            } else {
                this.destroy();
            }

            this.appendItems($tmpDiv.children());
        },

        appendItems: function ($newItems) {
            var self = this;

            this.$newContentTarget.append($newItems.addClass(this.options.preAppendClass));

            setTimeout(function () { // need this timeout coz need some time for css preAppendClass applied to the new items
                $newItems.removeClass(self.options.preAppendClass);

                self.$holder.trigger('ContentLoader/loaded');
                self.toggleBusyMode(false);
            }, 100);

            if (window.picturefill) {
                window.picturefill();
            }
        },

        refreshLink: function ($nextIncludeLink) {
            this.$link.attr('href', $nextIncludeLink.attr('href'));
            $nextIncludeLink.remove();
        },

        toggleBusyMode: function (state) {
            this.$holder.toggleClass(this.options.busyClass, state);
            this.isBusy = state;
        },

        removeInstance: function () {
            this.$holder.removeData('ContentLoader');
        },

        destroy: function () {
            this.removeInstance();
            this.destroySubEvents();

            this.$link.remove();
        }
    };

    $.fn.loadMore = function (options) {
        options = $.extend({
            scroll: false,
            linkSelector: '.load-more',
            newContentTarget: null,
            busyClass: 'is-busy',
            additionBottomOffset: 50,
            preAppendClass: 'new-item'
        }, options);

        return this.each(function () {
            var $holder = $(this);

            ContentLoader.prototype = $.extend(options.scroll ? ScrollLoader : ClickLoader, ContentLoaderProto);

            $holder.data('ContentLoader', new ContentLoader($holder, options));
        });
    };
}(jQuery, jQuery(window)));

/*!
 * SmoothScroll module
 */
; (function ($, exports) {
    // private variables
    var page,
		win = $(window),
		activeBlock, activeWheelHandler,
		wheelEvents = ('onwheel' in document || document.documentMode >= 9 ? 'wheel' : 'mousewheel DOMMouseScroll');

    // animation handlers
    function scrollTo(offset, options, callback) {
        // initialize variables
        var scrollBlock;
        if (document.body) {
            if (typeof options === 'number') {
                options = { duration: options };
            } else {
                options = options || {};
            }
            page = page || $('html, body');
            scrollBlock = options.container || page;
        } else {
            return;
        }

        // treat single number as scrollTop
        if (typeof offset === 'number') {
            offset = { top: offset };
        }

        // handle mousewheel/trackpad while animation is active
        if (activeBlock && activeWheelHandler) {
            activeBlock.off(wheelEvents, activeWheelHandler);
        }
        if (options.wheelBehavior && options.wheelBehavior !== 'none') {
            activeWheelHandler = function (e) {
                if (options.wheelBehavior === 'stop') {
                    scrollBlock.off(wheelEvents, activeWheelHandler);
                    scrollBlock.stop();
                } else if (options.wheelBehavior === 'ignore') {
                    e.preventDefault();
                }
            };
            activeBlock = scrollBlock.on(wheelEvents, activeWheelHandler);
        }

        // start scrolling animation
        scrollBlock.stop().animate({
            scrollLeft: offset.left,
            scrollTop: offset.top
        }, options.duration, function () {
            if (activeWheelHandler) {
                scrollBlock.off(wheelEvents, activeWheelHandler);
            }
            if ($.isFunction(callback)) {
                callback();
            }
        });
    }

    // smooth scroll contstructor
    function SmoothScroll(options) {
        this.options = $.extend({
            anchorLinks: 'a[href^="#"]',	// selector or jQuery object
            container: null,		// specify container for scrolling (default - whole page)
            extraOffset: null,		// function or fixed number
            activeClasses: null,	// null, "link", "parent"
            easing: 'swing',		// easing of scrolling
            animMode: 'duration',	// or "speed" mode
            animDuration: 800,		// total duration for scroll (any distance)
            animSpeed: 1500,		// pixels per second
            anchorActiveClass: 'anchor-active',
            sectionActiveClass: 'section-active',
            wheelBehavior: 'stop', // "stop", "ignore" or "none"
            useNativeAnchorScrolling: false // do not handle click in devices with native smooth scrolling
        }, options);
        this.init();
    }
    SmoothScroll.prototype = {
        init: function () {
            this.initStructure();
            this.attachEvents();
        },
        initStructure: function () {
            var self = this;

            this.container = this.options.container ? $(this.options.container) : $('html,body');
            this.scrollContainer = this.options.container ? this.container : win;
            this.anchorLinks = jQuery(this.options.anchorLinks).filter(function () {
                return document.getElementById(this.getAttribute('href').slice(1));
            });
        },
        getAnchorTarget: function (link) {
            // get target block from link href
            var targetId = $(link).attr('href');
            return $(targetId.length > 1 ? targetId : 'html');
        },
        getTargetOffset: function (block) {
            // get target offset
            var blockOffset = block.offset().top;
            if (this.options.container) {
                blockOffset -= this.container.offset().top - this.container.prop('scrollTop');
            }

            // handle extra offset
            if (typeof this.options.extraOffset === 'number') {
                blockOffset -= this.options.extraOffset;
            } else if (typeof this.options.extraOffset === 'function') {
                blockOffset -= this.options.extraOffset(block);
            }
            return { top: blockOffset };
        },
        attachEvents: function () {
            var self = this;

            // handle active classes
            if (this.options.activeClasses && this.anchorLinks.length) {
                // cache structure
                this.anchorData = [];

                for (var i = 0; i < this.anchorLinks.length; i++) {
                    var link = jQuery(this.anchorLinks[i]),
						targetBlock = self.getAnchorTarget(link),
						anchorDataItem;

                    $.each(self.anchorData, function (index, item) {
                        if (item.block[0] === targetBlock[0]) {
                            anchorDataItem = item;
                        }
                    });

                    if (anchorDataItem) {
                        anchorDataItem.link = anchorDataItem.link.add(link);
                    } else {
                        self.anchorData.push({
                            link: link,
                            block: targetBlock
                        });
                    }
                };

                // add additional event handlers
                this.resizeHandler = function () {
                    self.recalculateOffsets();
                };
                this.scrollHandler = function () {
                    self.refreshActiveClass();
                };

                this.recalculateOffsets();
                this.scrollContainer.on('scroll', this.scrollHandler);
                win.on('resize', this.resizeHandler);
            }

            // handle click event
            this.clickHandler = function (e) {
                self.onClick(e);
            };
            if (!this.options.useNativeAnchorScrolling) {
                this.anchorLinks.on('click', this.clickHandler);
            }
        },
        recalculateOffsets: function () {
            var self = this;
            $.each(this.anchorData, function (index, data) {
                data.offset = self.getTargetOffset(data.block);
                data.height = data.block.outerHeight();
            });
            this.refreshActiveClass();
        },
        refreshActiveClass: function () {
            var self = this,
				foundFlag = false,
				containerHeight = this.container.prop('scrollHeight'),
				viewPortHeight = this.scrollContainer.height(),
				scrollTop = this.options.container ? this.container.prop('scrollTop') : win.scrollTop();

            // user function instead of default handler
            if (this.options.customScrollHandler) {
                this.options.customScrollHandler.call(this, scrollTop, this.anchorData);
                return;
            }

            // sort anchor data by offsets
            this.anchorData.sort(function (a, b) {
                return a.offset.top - b.offset.top;
            });
            function toggleActiveClass(anchor, block, state) {
                anchor.toggleClass(self.options.anchorActiveClass, state);
                block.toggleClass(self.options.sectionActiveClass, state);
            }

            // default active class handler
            $.each(this.anchorData, function (index) {
                var reverseIndex = self.anchorData.length - index - 1,
					data = self.anchorData[reverseIndex],
					anchorElement = (self.options.activeClasses === 'parent' ? data.link.parent() : data.link);

                if (scrollTop >= containerHeight - viewPortHeight) {
                    // handle last section
                    if (reverseIndex === self.anchorData.length - 1) {
                        toggleActiveClass(anchorElement, data.block, true);
                    } else {
                        toggleActiveClass(anchorElement, data.block, false);
                    }
                } else {
                    // handle other sections
                    if (!foundFlag && (scrollTop >= data.offset.top - 1 || reverseIndex === 0)) {
                        foundFlag = true;
                        toggleActiveClass(anchorElement, data.block, true);
                    } else {
                        toggleActiveClass(anchorElement, data.block, false);
                    }
                }
            });
        },
        calculateScrollDuration: function (offset) {
            var distance;
            if (this.options.animMode === 'speed') {
                distance = Math.abs(this.scrollContainer.scrollTop() - offset.top);
                return (distance / this.options.animSpeed) * 1000;
            } else {
                return this.options.animDuration;
            }
        },
        onClick: function (e) {
            var targetBlock = this.getAnchorTarget(e.currentTarget),
				targetOffset = this.getTargetOffset(targetBlock);

            e.preventDefault();
            scrollTo(targetOffset, {
                container: this.container,
                wheelBehavior: this.options.wheelBehavior,
                duration: this.calculateScrollDuration(targetOffset)
            });
        },
        destroy: function () {
            if (this.options.activeClasses) {
                win.off('resize', this.resizeHandler);
                this.scrollContainer.off('scroll', this.scrollHandler);
            }
            this.anchorLinks.off('click', this.clickHandler);
        }
    };

    // public API
    $.extend(SmoothScroll, {
        scrollTo: function (blockOrOffset, durationOrOptions, callback) {
            scrollTo(blockOrOffset, durationOrOptions, callback);
        }
    });

    // export module
    exports.SmoothScroll = SmoothScroll;
}(jQuery, this));


/*
 * jQuery SameHeight plugin
 */
; (function ($) {
    $.fn.sameHeight = function (opt) {
        var options = $.extend({
            skipClass: 'same-height-ignore',
            leftEdgeClass: 'same-height-left',
            rightEdgeClass: 'same-height-right',
            elements: '>*',
            flexible: false,
            multiLine: false,
            useMinHeight: false,
            biggestHeight: false
        }, opt);
        return this.each(function () {
            var holder = $(this), postResizeTimer, ignoreResize;
            var elements = holder.find(options.elements).not('.' + options.skipClass);
            if (!elements.length) return;

            // resize handler
            function doResize() {
                elements.css(options.useMinHeight && supportMinHeight ? 'minHeight' : 'height', '');
                if (options.multiLine) {
                    // resize elements row by row
                    resizeElementsByRows(elements, options);
                } else {
                    // resize elements by holder
                    resizeElements(elements, holder, options);
                }
            }
            doResize();

            // handle flexible layout / font resize
            var delayedResizeHandler = function () {
                if (!ignoreResize) {
                    ignoreResize = true;
                    doResize();
                    clearTimeout(postResizeTimer);
                    postResizeTimer = setTimeout(function () {
                        doResize();
                        setTimeout(function () {
                            ignoreResize = false;
                        }, 10);
                    }, 100);
                }
            };

            // handle flexible/responsive layout
            if (options.flexible) {
                $(window).bind('resize orientationchange fontresize', delayedResizeHandler);
            }

            // handle complete page load including images and fonts
            $(window).bind('load', delayedResizeHandler);
        });
    };

    // detect css min-height support
    var supportMinHeight = typeof document.documentElement.style.maxHeight !== 'undefined';

    // get elements by rows
    function resizeElementsByRows(boxes, options) {
        var currentRow = $(), maxHeight, maxCalcHeight = 0, firstOffset = boxes.eq(0).offset().top;
        boxes.each(function (ind) {
            var curItem = $(this);
            if (curItem.offset().top === firstOffset) {
                currentRow = currentRow.add(this);
            } else {
                maxHeight = getMaxHeight(currentRow);
                maxCalcHeight = Math.max(maxCalcHeight, resizeElements(currentRow, maxHeight, options));
                currentRow = curItem;
                firstOffset = curItem.offset().top;
            }
        });
        if (currentRow.length) {
            maxHeight = getMaxHeight(currentRow);
            maxCalcHeight = Math.max(maxCalcHeight, resizeElements(currentRow, maxHeight, options));
        }
        if (options.biggestHeight) {
            boxes.css(options.useMinHeight && supportMinHeight ? 'minHeight' : 'height', maxCalcHeight);
        }
    }

    // calculate max element height
    function getMaxHeight(boxes) {
        var maxHeight = 0;
        boxes.each(function () {
            maxHeight = Math.max(maxHeight, $(this).outerHeight());
        });
        return maxHeight;
    }

    // resize helper function
    function resizeElements(boxes, parent, options) {
        var calcHeight;
        var parentHeight = typeof parent === 'number' ? parent : parent.height();
        boxes.removeClass(options.leftEdgeClass).removeClass(options.rightEdgeClass).each(function (i) {
            var element = $(this);
            var depthDiffHeight = 0;
            var isBorderBox = element.css('boxSizing') === 'border-box' || element.css('-moz-box-sizing') === 'border-box' || element.css('-webkit-box-sizing') === 'border-box';

            if (typeof parent !== 'number') {
                element.parents().each(function () {
                    var tmpParent = $(this);
                    if (parent.is(this)) {
                        return false;
                    } else {
                        depthDiffHeight += tmpParent.outerHeight() - tmpParent.height();
                    }
                });
            }
            calcHeight = parentHeight - depthDiffHeight;
            calcHeight -= isBorderBox ? 0 : element.outerHeight() - element.height();

            if (calcHeight > 0) {
                element.css(options.useMinHeight && supportMinHeight ? 'minHeight' : 'height', calcHeight);
            }
        });
        boxes.filter(':first').addClass(options.leftEdgeClass);
        boxes.filter(':last').addClass(options.rightEdgeClass);
        return calcHeight;
    }
}(jQuery));

/*
 * jQuery FontResize Event
 */
jQuery.onFontResize = (function ($) {
    $(function () {
        var randomID = 'font-resize-frame-' + Math.floor(Math.random() * 1000);
        var resizeFrame = $('<iframe>').attr('id', randomID).addClass('font-resize-helper');

        // required styles
        resizeFrame.css({
            width: '100em',
            height: '10px',
            position: 'absolute',
            borderWidth: 0,
            top: '-9999px',
            left: '-9999px'
        }).appendTo('body');

        // use native IE resize event if possible
        if (window.attachEvent && !window.addEventListener) {
            resizeFrame.bind('resize', function () {
                $.onFontResize.trigger(resizeFrame[0].offsetWidth / 100);
            });
        }
            // use script inside the iframe to detect resize for other browsers
        else {
            var doc = resizeFrame[0].contentWindow.document;
            doc.open();
            doc.write('<scri' + 'pt>window.onload = function(){var em = parent.jQuery("#' + randomID + '")[0];window.onresize = function(){if(parent.jQuery.onFontResize){parent.jQuery.onFontResize.trigger(em.offsetWidth / 100);}}};</scri' + 'pt>');
            doc.close();
        }
        jQuery.onFontResize.initialSize = resizeFrame[0].offsetWidth / 100;
    });
    return {
        // public method, so it can be called from within the iframe
        trigger: function (em) {
            $(window).trigger("fontresize", [em]);
        }
    };
}(jQuery));

/*
 * jQuery form validation plugin
 */
; (function ($) {
    'use strict';

    var FormValidation = (function () {
        var Validator = function ($field, $fields) {
            this.$field = $field;
            this.$fields = $fields;
        };

        Validator.prototype = {
            reg: {
                email: '^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$',
                number: '^[0-9]+$'
            },

            checkField: function () {
                return {
                    state: this.run(),
                    $fields: this.$field.add(this.additionalFields)
                }
            },

            run: function () {
                var fieldType;

                switch (this.$field.get(0).tagName.toUpperCase()) {
                    case 'SELECT':
                        fieldType = 'select';
                        break;

                    case 'TEXTAREA':
                        fieldType = 'text';
                        break;

                    default:
                        fieldType = this.$field.data('type') || this.$field.attr('type');
                }

                var functionName = 'check_' + fieldType;
                var state = true;

                if ($.isFunction(this[functionName])) {
                    state = this[functionName]();

                    if (state && this.$field.data('confirm')) {
                        state = this.check_confirm();
                    }
                }

                return state;
            },

            check_email: function () {
                var value = this.getValue();
                var required = this.$field.data('required');
                var requiredOrValue = required || value.length;

                if ((requiredOrValue && !this.check_regexp(value, this.reg.email))) {
                    return false;
                }

                return requiredOrValue ? true : null;
            },

            check_number: function () {
                var value = this.getValue();
                var required = this.$field.data('required');
                var isNumber = this.check_regexp(value, this.reg.number);
                var requiredOrValue = required || value.length;

                if (requiredOrValue && !isNumber) {
                    return false;
                }

                var min = this.$field.data('min');
                var max = this.$field.data('max');
                value = +value;

                if ((min && (value < min || !isNumber)) || (max && (value > max || !isNumber))) {
                    return false;
                }

                return (requiredOrValue || min || max) ? true : null;
            },

            check_password: function () {
                return this.check_text();
            },

            check_text: function () {
                var value = this.getValue();
                var required = this.$field.data('required');

                if (this.$field.data('required') && !value.length) {
                    return false;
                }

                var min = +this.$field.data('min');
                var max = +this.$field.data('max');

                if ((min && value.length < min) || (max && value.length > max)) {
                    return false;
                }

                var regExp = this.$field.data('regexp');

                if (regExp && !this.check_regexp(value, regExp)) {
                    return false;
                }

                return (required || min || max || regExp) ? true : null;
            },

            check_confirm: function () {
                var value = this.getValue();
                var $confirmFields = this.$fields.filter('[data-confirm="' + this.$field.data('confirm') + '"]');
                var confirmState = true;

                for (var i = $confirmFields.length - 1; i >= 0; i--) {
                    if ($confirmFields.eq(i).val() !== value || !value.length) {
                        confirmState = false;
                        break;
                    }
                }

                this.additionalFields = $confirmFields;

                return confirmState;
            },

            check_select: function () {
                var required = this.$field.data('required');

                if (required && this.$field.get(0).selectedIndex === 0) {
                    return false;
                }

                return required ? true : null;
            },

            check_radio: function () {
                var $fields = this.$fields.filter('[name="' + this.$field.attr('name') + '"]');
                var required = this.$field.data('required');

                if (required && !$fields.filter(':checked').length) {
                    return false;
                }

                this.additionalFields = $fields;

                return required ? true : null;
            },

            check_checkbox: function () {
                var required = this.$field.data('required');

                if (required && !this.$field.prop('checked')) {
                    return false;
                }

                return required ? true : null;
            },

            check_at_least_one: function () {
                var $fields = this.$fields.filter('[data-name="' + this.$field.data('name') + '"]');

                if (!$fields.filter(':checked').length) {
                    return false;
                }

                this.additionalFields = $fields;

                return true;
            },

            check_regexp: function (val, exp) {
                return new RegExp(exp).test(val);
            },

            getValue: function () {
                if (this.$field.data('trim')) {
                    this.$field.val($.trim(this.$field.val()));
                }

                return this.$field.val();
            }
        };

        var publicClass = function (form, options) {
            this.$form = $(form).attr('novalidate', 'novalidate');
            this.options = options;
        };

        publicClass.prototype = {
            buildSelector: function (input) {
                return ':input:not(' + this.options.skipDefaultFields + (this.options.skipFields ? ',' + this.options.skipFields : '') + ')';
            },

            init: function () {
                this.fieldsSelector = this.buildSelector(':input');

                this.$form
					.on('submit', this.submitHandler.bind(this))
					.on('keyup blur', this.fieldsSelector, this.changeHandler.bind(this))
					.on('change', this.buildSelector('select'), this.changeHandler.bind(this))
					.on('focus', this.fieldsSelector, this.focusHandler.bind(this));
            },

            submitHandler: function (e) {
                var self = this;
                var $fields = this.getFormFields();

                this.getClassTarget($fields)
				    .removeClass(this.options.errorClass + ' ' + this.options.successClass);

                this.setFormState(true);

                $fields.each(function (i, input) {
                    var $field = $(input);
                    var $classTarget = self.getClassTarget($field);

                    // continue iteration if $field has error class already
                    if ($classTarget.hasClass(self.options.errorClass)) {
                        return;
                    }

                    self.setState(new Validator($field, $fields).checkField());
                });

                return this.checkSuccess($fields, e);
            },

            checkSuccess: function ($fields, e) {
                var self = this;
                var success = this.getClassTarget($fields || this.getFormFields())
								  .filter('.' + this.options.errorClass).length === 0;

                if (e && success && this.options.successSendClass) {
                    e.preventDefault();

                    $.ajax({
                        url: this.$form.removeClass(this.options.successSendClass).attr('action') || '/',
                        type: this.$form.attr('method') || 'POST',
                        data: this.$form.serialize(),
                        success: function () {
                            self.$form.addClass(self.options.successSendClass);
                        }
                    });
                }

                this.setFormState(success);

                return success;
            },

            changeHandler: function (e) {
                var $field = $(e.target);

                if ($field.data('interactive')) {
                    this.setState(new Validator($field, this.getFormFields()).checkField());
                }

                this.checkSuccess();
            },

            focusHandler: function (e) {
                var $field = $(e.target);

                this.getClassTarget($field)
					.removeClass(this.options.errorClass + ' ' + this.options.successClass);

                this.checkSuccess();
            },

            setState: function (result) {
                this.getClassTarget(result.$fields)
					.toggleClass(this.options.errorClass, result.state !== null && !result.state)
					.toggleClass(this.options.successClass, result.state !== null && this.options.successClass && !!result.state);
            },

            setFormState: function (state) {
                if (this.options.errorFormClass) {
                    this.$form.toggleClass(this.options.errorFormClass, !state);
                }
            },

            getClassTarget: function ($input) {
                return (this.options.addClassToParent ? $input.closest(this.options.addClassToParent) : $input);
            },

            getFormFields: function () {
                return this.$form.find(this.fieldsSelector);
            }
        };

        return publicClass;
    }());

    $.fn.formValidation = function (options) {
        options = $.extend({}, {
            errorClass: 'input-error',
            successClass: '',
            errorFormClass: '',
            addClassToParent: '',
            skipDefaultFields: ':button, :submit, :image, :hidden, :reset',
            skipFields: '',
            successSendClass: ''
        }, options);

        return this.each(function () {
            new FormValidation(this, options).init();
        });
    };
}(jQuery));

/*
 * jQuery Accordion plugin
 */
; (function ($) {
    $.fn.slideAccordion = function (opt) {
        // default options
        var options = $.extend({
            addClassBeforeAnimation: false,
            allowClickWhenExpanded: false,
            activeClass: 'active',
            opener: '.opener',
            slider: '.slide',
            animSpeed: 300,
            collapsible: true,
            event: 'click'
        }, opt);

        return this.each(function () {
            // options
            var accordion = $(this);
            var items = accordion.find(':has(' + options.slider + ')');

            items.each(function () {
                var item = $(this);
                var opener = item.find(options.opener);
                var slider = item.find(options.slider);
                opener.bind(options.event, function (e) {
                    if (!slider.is(':animated')) {
                        if (item.hasClass(options.activeClass)) {
                            if (options.allowClickWhenExpanded) {
                                return;
                            } else if (options.collapsible) {
                                slider.slideUp(options.animSpeed, function () {
                                    hideSlide(slider);
                                    item.removeClass(options.activeClass);
                                });
                            }
                        } else {
                            // show active
                            var levelItems = item.siblings('.' + options.activeClass);
                            var sliderElements = levelItems.find(options.slider);
                            item.addClass(options.activeClass);
                            showSlide(slider).hide().slideDown(options.animSpeed);

                            // collapse others
                            sliderElements.slideUp(options.animSpeed, function () {
                                levelItems.removeClass(options.activeClass);
                                hideSlide(sliderElements);
                            });
                        }
                    }
                    e.preventDefault();
                });
                if (item.hasClass(options.activeClass)) showSlide(slider); else hideSlide(slider);
            });
        });
    };

    // accordion slide visibility
    var showSlide = function (slide) {
        return slide.css({ position: '', top: '', left: '', width: '' });
    };
    var hideSlide = function (slide) {
        return slide.show().css({ position: 'absolute', top: -9999, left: -9999, width: slide.width() });
    };
}(jQuery));

// fancybox modal popup init
function initLightbox() {
    jQuery('a.lightbox, a[rel*="lightbox"]').fancybox({
        helpers: {
            overlay: {
                css: {
                    background: 'rgba(0, 0, 0, 0.65)'
                }
            }
        },
        afterLoad: function (current, previous) {
            // handle custom close button in inline modal
            if (current.href.indexOf('#') === 0) {
                jQuery(current.href).find('a.close').off('click.fb').on('click.fb', function (e) {
                    e.preventDefault();
                    jQuery.fancybox.close();
                });
            }
        }
    });
}

/*! fancyBox v2.1.5 fancyapps.com | fancyapps.com/fancybox/#license */
; (function (r, G, f, v) { var J = f("html"), n = f(r), p = f(G), b = f.fancybox = function () { b.open.apply(this, arguments) }, I = navigator.userAgent.match(/msie/i), B = null, s = G.createTouch !== v, t = function (a) { return a && a.hasOwnProperty && a instanceof f }, q = function (a) { return a && "string" === f.type(a) }, E = function (a) { return q(a) && 0 < a.indexOf("%") }, l = function (a, d) { var e = parseInt(a, 10) || 0; d && E(a) && (e *= b.getViewport()[d] / 100); return Math.ceil(e) }, w = function (a, b) { return l(a, b) + "px" }; f.extend(b, { version: "2.1.5", defaults: { padding: 15, margin: 20, width: 800, height: 600, minWidth: 100, minHeight: 100, maxWidth: 9999, maxHeight: 9999, pixelRatio: 1, autoSize: !0, autoHeight: !1, autoWidth: !1, autoResize: !0, autoCenter: !s, fitToView: !0, aspectRatio: !1, topRatio: 0.5, leftRatio: 0.5, scrolling: "auto", wrapCSS: "", arrows: !0, closeBtn: !0, closeClick: !1, nextClick: !1, mouseWheel: !0, autoPlay: !1, playSpeed: 3E3, preload: 3, modal: !1, loop: !0, ajax: { dataType: "html", headers: { "X-fancyBox": !0 } }, iframe: { scrolling: "auto", preload: !0 }, swf: { wmode: "transparent", allowfullscreen: "true", allowscriptaccess: "always" }, keys: { next: { 13: "left", 34: "up", 39: "left", 40: "up" }, prev: { 8: "right", 33: "down", 37: "right", 38: "down" }, close: [27], play: [32], toggle: [70] }, direction: { next: "left", prev: "right" }, scrollOutside: !0, index: 0, type: null, href: null, content: null, title: null, tpl: { wrap: '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>', image: '<img class="fancybox-image" src="{href}" alt="" />', iframe: '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + (I ? ' allowtransparency="true"' : "") + "></iframe>", error: '<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>', closeBtn: '<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>', next: '<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>', prev: '<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>' }, openEffect: "fade", openSpeed: 250, openEasing: "swing", openOpacity: !0, openMethod: "zoomIn", closeEffect: "fade", closeSpeed: 250, closeEasing: "swing", closeOpacity: !0, closeMethod: "zoomOut", nextEffect: "elastic", nextSpeed: 250, nextEasing: "swing", nextMethod: "changeIn", prevEffect: "elastic", prevSpeed: 250, prevEasing: "swing", prevMethod: "changeOut", helpers: { overlay: !0, title: !0 }, onCancel: f.noop, beforeLoad: f.noop, afterLoad: f.noop, beforeShow: f.noop, afterShow: f.noop, beforeChange: f.noop, beforeClose: f.noop, afterClose: f.noop }, group: {}, opts: {}, previous: null, coming: null, current: null, isActive: !1, isOpen: !1, isOpened: !1, wrap: null, skin: null, outer: null, inner: null, player: { timer: null, isActive: !1 }, ajaxLoad: null, imgPreload: null, transitions: {}, helpers: {}, open: function (a, d) { if (a && (f.isPlainObject(d) || (d = {}), !1 !== b.close(!0))) return f.isArray(a) || (a = t(a) ? f(a).get() : [a]), f.each(a, function (e, c) { var k = {}, g, h, j, m, l; "object" === f.type(c) && (c.nodeType && (c = f(c)), t(c) ? (k = { href: c.data("fancybox-href") || c.attr("href"), title: c.data("fancybox-title") || c.attr("title"), isDom: !0, element: c }, f.metadata && f.extend(!0, k, c.metadata())) : k = c); g = d.href || k.href || (q(c) ? c : null); h = d.title !== v ? d.title : k.title || ""; m = (j = d.content || k.content) ? "html" : d.type || k.type; !m && k.isDom && (m = c.data("fancybox-type"), m || (m = (m = c.prop("class").match(/fancybox\.(\w+)/)) ? m[1] : null)); q(g) && (m || (b.isImage(g) ? m = "image" : b.isSWF(g) ? m = "swf" : "#" === g.charAt(0) ? m = "inline" : q(c) && (m = "html", j = c)), "ajax" === m && (l = g.split(/\s+/, 2), g = l.shift(), l = l.shift())); j || ("inline" === m ? g ? j = f(q(g) ? g.replace(/.*(?=#[^\s]+$)/, "") : g) : k.isDom && (j = c) : "html" === m ? j = g : !m && (!g && k.isDom) && (m = "inline", j = c)); f.extend(k, { href: g, type: m, content: j, title: h, selector: l }); a[e] = k }), b.opts = f.extend(!0, {}, b.defaults, d), d.keys !== v && (b.opts.keys = d.keys ? f.extend({}, b.defaults.keys, d.keys) : !1), b.group = a, b._start(b.opts.index) }, cancel: function () { var a = b.coming; a && !1 !== b.trigger("onCancel") && (b.hideLoading(), b.ajaxLoad && b.ajaxLoad.abort(), b.ajaxLoad = null, b.imgPreload && (b.imgPreload.onload = b.imgPreload.onerror = null), a.wrap && a.wrap.stop(!0, !0).trigger("onReset").remove(), b.coming = null, b.current || b._afterZoomOut(a)) }, close: function (a) { b.cancel(); !1 !== b.trigger("beforeClose") && (b.unbindEvents(), b.isActive && (!b.isOpen || !0 === a ? (f(".fancybox-wrap").stop(!0).trigger("onReset").remove(), b._afterZoomOut()) : (b.isOpen = b.isOpened = !1, b.isClosing = !0, f(".fancybox-item, .fancybox-nav").remove(), b.wrap.stop(!0, !0).removeClass("fancybox-opened"), b.transitions[b.current.closeMethod]()))) }, play: function (a) { var d = function () { clearTimeout(b.player.timer) }, e = function () { d(); b.current && b.player.isActive && (b.player.timer = setTimeout(b.next, b.current.playSpeed)) }, c = function () { d(); p.unbind(".player"); b.player.isActive = !1; b.trigger("onPlayEnd") }; if (!0 === a || !b.player.isActive && !1 !== a) { if (b.current && (b.current.loop || b.current.index < b.group.length - 1)) b.player.isActive = !0, p.bind({ "onCancel.player beforeClose.player": c, "onUpdate.player": e, "beforeLoad.player": d }), e(), b.trigger("onPlayStart") } else c() }, next: function (a) { var d = b.current; d && (q(a) || (a = d.direction.next), b.jumpto(d.index + 1, a, "next")) }, prev: function (a) { var d = b.current; d && (q(a) || (a = d.direction.prev), b.jumpto(d.index - 1, a, "prev")) }, jumpto: function (a, d, e) { var c = b.current; c && (a = l(a), b.direction = d || c.direction[a >= c.index ? "next" : "prev"], b.router = e || "jumpto", c.loop && (0 > a && (a = c.group.length + a % c.group.length), a %= c.group.length), c.group[a] !== v && (b.cancel(), b._start(a))) }, reposition: function (a, d) { var e = b.current, c = e ? e.wrap : null, k; c && (k = b._getPosition(d), a && "scroll" === a.type ? (delete k.position, c.stop(!0, !0).animate(k, 200)) : (c.css(k), e.pos = f.extend({}, e.dim, k))) }, update: function (a) { var d = a && a.type, e = !d || "orientationchange" === d; e && (clearTimeout(B), B = null); b.isOpen && !B && (B = setTimeout(function () { var c = b.current; c && !b.isClosing && (b.wrap.removeClass("fancybox-tmp"), (e || "load" === d || "resize" === d && c.autoResize) && b._setDimension(), "scroll" === d && c.canShrink || b.reposition(a), b.trigger("onUpdate"), B = null) }, e && !s ? 0 : 300)) }, toggle: function (a) { b.isOpen && (b.current.fitToView = "boolean" === f.type(a) ? a : !b.current.fitToView, s && (b.wrap.removeAttr("style").addClass("fancybox-tmp"), b.trigger("onUpdate")), b.update()) }, hideLoading: function () { p.unbind(".loading"); f("#fancybox-loading").remove() }, showLoading: function () { var a, d; b.hideLoading(); a = f('<div id="fancybox-loading"><div></div></div>').click(b.cancel).appendTo("body"); p.bind("keydown.loading", function (a) { if (27 === (a.which || a.keyCode)) a.preventDefault(), b.cancel() }); b.defaults.fixed || (d = b.getViewport(), a.css({ position: "absolute", top: 0.5 * d.h + d.y, left: 0.5 * d.w + d.x })) }, getViewport: function () { var a = b.current && b.current.locked || !1, d = { x: n.scrollLeft(), y: n.scrollTop() }; a ? (d.w = a[0].clientWidth, d.h = a[0].clientHeight) : (d.w = s && r.innerWidth ? r.innerWidth : n.width(), d.h = s && r.innerHeight ? r.innerHeight : n.height()); return d }, unbindEvents: function () { b.wrap && t(b.wrap) && b.wrap.unbind(".fb"); p.unbind(".fb"); n.unbind(".fb") }, bindEvents: function () { var a = b.current, d; a && (n.bind("orientationchange.fb" + (s ? "" : " resize.fb") + (a.autoCenter && !a.locked ? " scroll.fb" : ""), b.update), (d = a.keys) && p.bind("keydown.fb", function (e) { var c = e.which || e.keyCode, k = e.target || e.srcElement; if (27 === c && b.coming) return !1; !e.ctrlKey && (!e.altKey && !e.shiftKey && !e.metaKey && (!k || !k.type && !f(k).is("[contenteditable]"))) && f.each(d, function (d, k) { if (1 < a.group.length && k[c] !== v) return b[d](k[c]), e.preventDefault(), !1; if (-1 < f.inArray(c, k)) return b[d](), e.preventDefault(), !1 }) }), f.fn.mousewheel && a.mouseWheel && b.wrap.bind("mousewheel.fb", function (d, c, k, g) { for (var h = f(d.target || null), j = !1; h.length && !j && !h.is(".fancybox-skin") && !h.is(".fancybox-wrap") ;) j = h[0] && !(h[0].style.overflow && "hidden" === h[0].style.overflow) && (h[0].clientWidth && h[0].scrollWidth > h[0].clientWidth || h[0].clientHeight && h[0].scrollHeight > h[0].clientHeight), h = f(h).parent(); if (0 !== c && !j && 1 < b.group.length && !a.canShrink) { if (0 < g || 0 < k) b.prev(0 < g ? "down" : "left"); else if (0 > g || 0 > k) b.next(0 > g ? "up" : "right"); d.preventDefault() } })) }, trigger: function (a, d) { var e, c = d || b.coming || b.current; if (c) { f.isFunction(c[a]) && (e = c[a].apply(c, Array.prototype.slice.call(arguments, 1))); if (!1 === e) return !1; c.helpers && f.each(c.helpers, function (d, e) { if (e && b.helpers[d] && f.isFunction(b.helpers[d][a])) b.helpers[d][a](f.extend(!0, {}, b.helpers[d].defaults, e), c) }); p.trigger(a) } }, isImage: function (a) { return q(a) && a.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i) }, isSWF: function (a) { return q(a) && a.match(/\.(swf)((\?|#).*)?$/i) }, _start: function (a) { var d = {}, e, c; a = l(a); e = b.group[a] || null; if (!e) return !1; d = f.extend(!0, {}, b.opts, e); e = d.margin; c = d.padding; "number" === f.type(e) && (d.margin = [e, e, e, e]); "number" === f.type(c) && (d.padding = [c, c, c, c]); d.modal && f.extend(!0, d, { closeBtn: !1, closeClick: !1, nextClick: !1, arrows: !1, mouseWheel: !1, keys: null, helpers: { overlay: { closeClick: !1 } } }); d.autoSize && (d.autoWidth = d.autoHeight = !0); "auto" === d.width && (d.autoWidth = !0); "auto" === d.height && (d.autoHeight = !0); d.group = b.group; d.index = a; b.coming = d; if (!1 === b.trigger("beforeLoad")) b.coming = null; else { c = d.type; e = d.href; if (!c) return b.coming = null, b.current && b.router && "jumpto" !== b.router ? (b.current.index = a, b[b.router](b.direction)) : !1; b.isActive = !0; if ("image" === c || "swf" === c) d.autoHeight = d.autoWidth = !1, d.scrolling = "visible"; "image" === c && (d.aspectRatio = !0); "iframe" === c && s && (d.scrolling = "scroll"); d.wrap = f(d.tpl.wrap).addClass("fancybox-" + (s ? "mobile" : "desktop") + " fancybox-type-" + c + " fancybox-tmp " + d.wrapCSS).appendTo(d.parent || "body"); f.extend(d, { skin: f(".fancybox-skin", d.wrap), outer: f(".fancybox-outer", d.wrap), inner: f(".fancybox-inner", d.wrap) }); f.each(["Top", "Right", "Bottom", "Left"], function (a, b) { d.skin.css("padding" + b, w(d.padding[a])) }); b.trigger("onReady"); if ("inline" === c || "html" === c) { if (!d.content || !d.content.length) return b._error("content") } else if (!e) return b._error("href"); "image" === c ? b._loadImage() : "ajax" === c ? b._loadAjax() : "iframe" === c ? b._loadIframe() : b._afterLoad() } }, _error: function (a) { f.extend(b.coming, { type: "html", autoWidth: !0, autoHeight: !0, minWidth: 0, minHeight: 0, scrolling: "no", hasError: a, content: b.coming.tpl.error }); b._afterLoad() }, _loadImage: function () { var a = b.imgPreload = new Image; a.onload = function () { this.onload = this.onerror = null; b.coming.width = this.width / b.opts.pixelRatio; b.coming.height = this.height / b.opts.pixelRatio; b._afterLoad() }; a.onerror = function () { this.onload = this.onerror = null; b._error("image") }; a.src = b.coming.href; !0 !== a.complete && b.showLoading() }, _loadAjax: function () { var a = b.coming; b.showLoading(); b.ajaxLoad = f.ajax(f.extend({}, a.ajax, { url: a.href, error: function (a, e) { b.coming && "abort" !== e ? b._error("ajax", a) : b.hideLoading() }, success: function (d, e) { "success" === e && (a.content = d, b._afterLoad()) } })) }, _loadIframe: function () { var a = b.coming, d = f(a.tpl.iframe.replace(/\{rnd\}/g, (new Date).getTime())).attr("scrolling", s ? "auto" : a.iframe.scrolling).attr("src", a.href); f(a.wrap).bind("onReset", function () { try { f(this).find("iframe").hide().attr("src", "//about:blank").end().empty() } catch (a) { } }); a.iframe.preload && (b.showLoading(), d.one("load", function () { f(this).data("ready", 1); s || f(this).bind("load.fb", b.update); f(this).parents(".fancybox-wrap").width("100%").removeClass("fancybox-tmp").show(); b._afterLoad() })); a.content = d.appendTo(a.inner); a.iframe.preload || b._afterLoad() }, _preloadImages: function () { var a = b.group, d = b.current, e = a.length, c = d.preload ? Math.min(d.preload, e - 1) : 0, f, g; for (g = 1; g <= c; g += 1) f = a[(d.index + g) % e], "image" === f.type && f.href && ((new Image).src = f.href) }, _afterLoad: function () { var a = b.coming, d = b.current, e, c, k, g, h; b.hideLoading(); if (a && !1 !== b.isActive) if (!1 === b.trigger("afterLoad", a, d)) a.wrap.stop(!0).trigger("onReset").remove(), b.coming = null; else { d && (b.trigger("beforeChange", d), d.wrap.stop(!0).removeClass("fancybox-opened").find(".fancybox-item, .fancybox-nav").remove()); b.unbindEvents(); e = a.content; c = a.type; k = a.scrolling; f.extend(b, { wrap: a.wrap, skin: a.skin, outer: a.outer, inner: a.inner, current: a, previous: d }); g = a.href; switch (c) { case "inline": case "ajax": case "html": a.selector ? e = f("<div>").html(e).find(a.selector) : t(e) && (e.data("fancybox-placeholder") || e.data("fancybox-placeholder", f('<div class="fancybox-placeholder"></div>').insertAfter(e).hide()), e = e.show().detach(), a.wrap.bind("onReset", function () { f(this).find(e).length && e.hide().replaceAll(e.data("fancybox-placeholder")).data("fancybox-placeholder", !1) })); break; case "image": e = a.tpl.image.replace("{href}", g); break; case "swf": e = '<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + g + '"></param>', h = "", f.each(a.swf, function (a, b) { e += '<param name="' + a + '" value="' + b + '"></param>'; h += " " + a + '="' + b + '"' }), e += '<embed src="' + g + '" type="application/x-shockwave-flash" width="100%" height="100%"' + h + "></embed></object>" } (!t(e) || !e.parent().is(a.inner)) && a.inner.append(e); b.trigger("beforeShow"); a.inner.css("overflow", "yes" === k ? "scroll" : "no" === k ? "hidden" : k); b._setDimension(); b.reposition(); b.isOpen = !1; b.coming = null; b.bindEvents(); if (b.isOpened) { if (d.prevMethod) b.transitions[d.prevMethod]() } else f(".fancybox-wrap").not(a.wrap).stop(!0).trigger("onReset").remove(); b.transitions[b.isOpened ? a.nextMethod : a.openMethod](); b._preloadImages() } }, _setDimension: function () { var a = b.getViewport(), d = 0, e = !1, c = !1, e = b.wrap, k = b.skin, g = b.inner, h = b.current, c = h.width, j = h.height, m = h.minWidth, u = h.minHeight, n = h.maxWidth, p = h.maxHeight, s = h.scrolling, q = h.scrollOutside ? h.scrollbarWidth : 0, x = h.margin, y = l(x[1] + x[3]), r = l(x[0] + x[2]), v, z, t, C, A, F, B, D, H; e.add(k).add(g).width("auto").height("auto").removeClass("fancybox-tmp"); x = l(k.outerWidth(!0) - k.width()); v = l(k.outerHeight(!0) - k.height()); z = y + x; t = r + v; C = E(c) ? (a.w - z) * l(c) / 100 : c; A = E(j) ? (a.h - t) * l(j) / 100 : j; if ("iframe" === h.type) { if (H = h.content, h.autoHeight && 1 === H.data("ready")) try { H[0].contentWindow.document.location && (g.width(C).height(9999), F = H.contents().find("body"), q && F.css("overflow-x", "hidden"), A = F.outerHeight(!0)) } catch (G) { } } else if (h.autoWidth || h.autoHeight) g.addClass("fancybox-tmp"), h.autoWidth || g.width(C), h.autoHeight || g.height(A), h.autoWidth && (C = g.width()), h.autoHeight && (A = g.height()), g.removeClass("fancybox-tmp"); c = l(C); j = l(A); D = C / A; m = l(E(m) ? l(m, "w") - z : m); n = l(E(n) ? l(n, "w") - z : n); u = l(E(u) ? l(u, "h") - t : u); p = l(E(p) ? l(p, "h") - t : p); F = n; B = p; h.fitToView && (n = Math.min(a.w - z, n), p = Math.min(a.h - t, p)); z = a.w - y; r = a.h - r; h.aspectRatio ? (c > n && (c = n, j = l(c / D)), j > p && (j = p, c = l(j * D)), c < m && (c = m, j = l(c / D)), j < u && (j = u, c = l(j * D))) : (c = Math.max(m, Math.min(c, n)), h.autoHeight && "iframe" !== h.type && (g.width(c), j = g.height()), j = Math.max(u, Math.min(j, p))); if (h.fitToView) if (g.width(c).height(j), e.width(c + x), a = e.width(), y = e.height(), h.aspectRatio) for (; (a > z || y > r) && (c > m && j > u) && !(19 < d++) ;) j = Math.max(u, Math.min(p, j - 10)), c = l(j * D), c < m && (c = m, j = l(c / D)), c > n && (c = n, j = l(c / D)), g.width(c).height(j), e.width(c + x), a = e.width(), y = e.height(); else c = Math.max(m, Math.min(c, c - (a - z))), j = Math.max(u, Math.min(j, j - (y - r))); q && ("auto" === s && j < A && c + x + q < z) && (c += q); g.width(c).height(j); e.width(c + x); a = e.width(); y = e.height(); e = (a > z || y > r) && c > m && j > u; c = h.aspectRatio ? c < F && j < B && c < C && j < A : (c < F || j < B) && (c < C || j < A); f.extend(h, { dim: { width: w(a), height: w(y) }, origWidth: C, origHeight: A, canShrink: e, canExpand: c, wPadding: x, hPadding: v, wrapSpace: y - k.outerHeight(!0), skinSpace: k.height() - j }); !H && (h.autoHeight && j > u && j < p && !c) && g.height("auto") }, _getPosition: function (a) { var d = b.current, e = b.getViewport(), c = d.margin, f = b.wrap.width() + c[1] + c[3], g = b.wrap.height() + c[0] + c[2], c = { position: "absolute", top: c[0], left: c[3] }; d.autoCenter && d.fixed && !a && g <= e.h && f <= e.w ? c.position = "fixed" : d.locked || (c.top += e.y, c.left += e.x); c.top = w(Math.max(c.top, c.top + (e.h - g) * d.topRatio)); c.left = w(Math.max(c.left, c.left + (e.w - f) * d.leftRatio)); return c }, _afterZoomIn: function () { var a = b.current; a && (b.isOpen = b.isOpened = !0, b.wrap.css("overflow", "visible").addClass("fancybox-opened"), b.update(), (a.closeClick || a.nextClick && 1 < b.group.length) && b.inner.css("cursor", "pointer").bind("click.fb", function (d) { !f(d.target).is("a") && !f(d.target).parent().is("a") && (d.preventDefault(), b[a.closeClick ? "close" : "next"]()) }), a.closeBtn && f(a.tpl.closeBtn).appendTo(b.skin).bind("click.fb", function (a) { a.preventDefault(); b.close() }), a.arrows && 1 < b.group.length && ((a.loop || 0 < a.index) && f(a.tpl.prev).appendTo(b.outer).bind("click.fb", b.prev), (a.loop || a.index < b.group.length - 1) && f(a.tpl.next).appendTo(b.outer).bind("click.fb", b.next)), b.trigger("afterShow"), !a.loop && a.index === a.group.length - 1 ? b.play(!1) : b.opts.autoPlay && !b.player.isActive && (b.opts.autoPlay = !1, b.play())) }, _afterZoomOut: function (a) { a = a || b.current; f(".fancybox-wrap").trigger("onReset").remove(); f.extend(b, { group: {}, opts: {}, router: !1, current: null, isActive: !1, isOpened: !1, isOpen: !1, isClosing: !1, wrap: null, skin: null, outer: null, inner: null }); b.trigger("afterClose", a) } }); b.transitions = { getOrigPosition: function () { var a = b.current, d = a.element, e = a.orig, c = {}, f = 50, g = 50, h = a.hPadding, j = a.wPadding, m = b.getViewport(); !e && (a.isDom && d.is(":visible")) && (e = d.find("img:first"), e.length || (e = d)); t(e) ? (c = e.offset(), e.is("img") && (f = e.outerWidth(), g = e.outerHeight())) : (c.top = m.y + (m.h - g) * a.topRatio, c.left = m.x + (m.w - f) * a.leftRatio); if ("fixed" === b.wrap.css("position") || a.locked) c.top -= m.y, c.left -= m.x; return c = { top: w(c.top - h * a.topRatio), left: w(c.left - j * a.leftRatio), width: w(f + j), height: w(g + h) } }, step: function (a, d) { var e, c, f = d.prop; c = b.current; var g = c.wrapSpace, h = c.skinSpace; if ("width" === f || "height" === f) e = d.end === d.start ? 1 : (a - d.start) / (d.end - d.start), b.isClosing && (e = 1 - e), c = "width" === f ? c.wPadding : c.hPadding, c = a - c, b.skin[f](l("width" === f ? c : c - g * e)), b.inner[f](l("width" === f ? c : c - g * e - h * e)) }, zoomIn: function () { var a = b.current, d = a.pos, e = a.openEffect, c = "elastic" === e, k = f.extend({ opacity: 1 }, d); delete k.position; c ? (d = this.getOrigPosition(), a.openOpacity && (d.opacity = 0.1)) : "fade" === e && (d.opacity = 0.1); b.wrap.css(d).animate(k, { duration: "none" === e ? 0 : a.openSpeed, easing: a.openEasing, step: c ? this.step : null, complete: b._afterZoomIn }) }, zoomOut: function () { var a = b.current, d = a.closeEffect, e = "elastic" === d, c = { opacity: 0.1 }; e && (c = this.getOrigPosition(), a.closeOpacity && (c.opacity = 0.1)); b.wrap.animate(c, { duration: "none" === d ? 0 : a.closeSpeed, easing: a.closeEasing, step: e ? this.step : null, complete: b._afterZoomOut }) }, changeIn: function () { var a = b.current, d = a.nextEffect, e = a.pos, c = { opacity: 1 }, f = b.direction, g; e.opacity = 0.1; "elastic" === d && (g = "down" === f || "up" === f ? "top" : "left", "down" === f || "right" === f ? (e[g] = w(l(e[g]) - 200), c[g] = "+=200px") : (e[g] = w(l(e[g]) + 200), c[g] = "-=200px")); "none" === d ? b._afterZoomIn() : b.wrap.css(e).animate(c, { duration: a.nextSpeed, easing: a.nextEasing, complete: b._afterZoomIn }) }, changeOut: function () { var a = b.previous, d = a.prevEffect, e = { opacity: 0.1 }, c = b.direction; "elastic" === d && (e["down" === c || "up" === c ? "top" : "left"] = ("up" === c || "left" === c ? "-" : "+") + "=200px"); a.wrap.animate(e, { duration: "none" === d ? 0 : a.prevSpeed, easing: a.prevEasing, complete: function () { f(this).trigger("onReset").remove() } }) } }; b.helpers.overlay = { defaults: { closeClick: !0, speedOut: 200, showEarly: !0, css: {}, locked: !s, fixed: !0 }, overlay: null, fixed: !1, el: f("html"), create: function (a) { a = f.extend({}, this.defaults, a); this.overlay && this.close(); this.overlay = f('<div class="fancybox-overlay"></div>').appendTo(b.coming ? b.coming.parent : a.parent); this.fixed = !1; a.fixed && b.defaults.fixed && (this.overlay.addClass("fancybox-overlay-fixed"), this.fixed = !0) }, open: function (a) { var d = this; a = f.extend({}, this.defaults, a); this.overlay ? this.overlay.unbind(".overlay").width("auto").height("auto") : this.create(a); this.fixed || (n.bind("resize.overlay", f.proxy(this.update, this)), this.update()); a.closeClick && this.overlay.bind("click.overlay", function (a) { if (f(a.target).hasClass("fancybox-overlay")) return b.isActive ? b.close() : d.close(), !1 }); this.overlay.css(a.css).show() }, close: function () { var a, b; n.unbind("resize.overlay"); this.el.hasClass("fancybox-lock") && (f(".fancybox-margin").removeClass("fancybox-margin"), a = n.scrollTop(), b = n.scrollLeft(), this.el.removeClass("fancybox-lock"), n.scrollTop(a).scrollLeft(b)); f(".fancybox-overlay").remove().hide(); f.extend(this, { overlay: null, fixed: !1 }) }, update: function () { var a = "100%", b; this.overlay.width(a).height("100%"); I ? (b = Math.max(G.documentElement.offsetWidth, G.body.offsetWidth), p.width() > b && (a = p.width())) : p.width() > n.width() && (a = p.width()); this.overlay.width(a).height(p.height()) }, onReady: function (a, b) { var e = this.overlay; f(".fancybox-overlay").stop(!0, !0); e || this.create(a); a.locked && (this.fixed && b.fixed) && (e || (this.margin = p.height() > n.height() ? f("html").css("margin-right").replace("px", "") : !1), b.locked = this.overlay.append(b.wrap), b.fixed = !1); !0 === a.showEarly && this.beforeShow.apply(this, arguments) }, beforeShow: function (a, b) { var e, c; b.locked && (!1 !== this.margin && (f("*").filter(function () { return "fixed" === f(this).css("position") && !f(this).hasClass("fancybox-overlay") && !f(this).hasClass("fancybox-wrap") }).addClass("fancybox-margin"), this.el.addClass("fancybox-margin")), e = n.scrollTop(), c = n.scrollLeft(), this.el.addClass("fancybox-lock"), n.scrollTop(e).scrollLeft(c)); this.open(a) }, onUpdate: function () { this.fixed || this.update() }, afterClose: function (a) { this.overlay && !b.coming && this.overlay.fadeOut(a.speedOut, f.proxy(this.close, this)) } }; b.helpers.title = { defaults: { type: "float", position: "bottom" }, beforeShow: function (a) { var d = b.current, e = d.title, c = a.type; f.isFunction(e) && (e = e.call(d.element, d)); if (q(e) && "" !== f.trim(e)) { d = f('<div class="fancybox-title fancybox-title-' + c + '-wrap">' + e + "</div>"); switch (c) { case "inside": c = b.skin; break; case "outside": c = b.wrap; break; case "over": c = b.inner; break; default: c = b.skin, d.appendTo("body"), I && d.width(d.width()), d.wrapInner('<span class="child"></span>'), b.current.margin[2] += Math.abs(l(d.css("margin-bottom"))) } d["top" === a.position ? "prependTo" : "appendTo"](c) } } }; f.fn.fancybox = function (a) { var d, e = f(this), c = this.selector || "", k = function (g) { var h = f(this).blur(), j = d, k, l; !g.ctrlKey && (!g.altKey && !g.shiftKey && !g.metaKey) && !h.is(".fancybox-wrap") && (k = a.groupAttr || "data-fancybox-group", l = h.attr(k), l || (k = "rel", l = h.get(0)[k]), l && ("" !== l && "nofollow" !== l) && (h = c.length ? f(c) : e, h = h.filter("[" + k + '="' + l + '"]'), j = h.index(this)), a.index = j, !1 !== b.open(h, a) && g.preventDefault()) }; a = a || {}; d = a.index || 0; !c || !1 === a.live ? e.unbind("click.fb-start").bind("click.fb-start", k) : p.undelegate(c, "click.fb-start").delegate(c + ":not('.fancybox-item, .fancybox-nav')", "click.fb-start", k); this.filter("[data-fancybox-start=1]").trigger("click"); return this }; p.ready(function () { var a, d; f.scrollbarWidth === v && (f.scrollbarWidth = function () { var a = f('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body"), b = a.children(), b = b.innerWidth() - b.height(99).innerWidth(); a.remove(); return b }); if (f.support.fixedPosition === v) { a = f.support; d = f('<div style="position:fixed;top:20px;"></div>').appendTo("body"); var e = 20 === d[0].offsetTop || 15 === d[0].offsetTop; d.remove(); a.fixedPosition = e } f.extend(b.defaults, { scrollbarWidth: f.scrollbarWidth(), fixed: f.support.fixedPosition, parent: f("body") }); a = f(r).width(); J.addClass("fancybox-lock-test"); d = f(r).width(); J.removeClass("fancybox-lock-test"); f("<style type='text/css'>.fancybox-margin{margin-right:" + (d - a) + "px;}</style>").appendTo("head") }) })(window, document, jQuery);

/*! Hammer.JS - v2.0.4 - 2014-09-28
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2014 Jorik Tangelder;
 * Licensed under the MIT license */
if (Object.create) { !function (a, b, c, d) { "use strict"; function e(a, b, c) { return setTimeout(k(a, c), b) } function f(a, b, c) { return Array.isArray(a) ? (g(a, c[b], c), !0) : !1 } function g(a, b, c) { var e; if (a) if (a.forEach) a.forEach(b, c); else if (a.length !== d) for (e = 0; e < a.length;) b.call(c, a[e], e, a), e++; else for (e in a) a.hasOwnProperty(e) && b.call(c, a[e], e, a) } function h(a, b, c) { for (var e = Object.keys(b), f = 0; f < e.length;) (!c || c && a[e[f]] === d) && (a[e[f]] = b[e[f]]), f++; return a } function i(a, b) { return h(a, b, !0) } function j(a, b, c) { var d, e = b.prototype; d = a.prototype = Object.create(e), d.constructor = a, d._super = e, c && h(d, c) } function k(a, b) { return function () { return a.apply(b, arguments) } } function l(a, b) { return typeof a == kb ? a.apply(b ? b[0] || d : d, b) : a } function m(a, b) { return a === d ? b : a } function n(a, b, c) { g(r(b), function (b) { a.addEventListener(b, c, !1) }) } function o(a, b, c) { g(r(b), function (b) { a.removeEventListener(b, c, !1) }) } function p(a, b) { for (; a;) { if (a == b) return !0; a = a.parentNode } return !1 } function q(a, b) { return a.indexOf(b) > -1 } function r(a) { return a.trim().split(/\s+/g) } function s(a, b, c) { if (a.indexOf && !c) return a.indexOf(b); for (var d = 0; d < a.length;) { if (c && a[d][c] == b || !c && a[d] === b) return d; d++ } return -1 } function t(a) { return Array.prototype.slice.call(a, 0) } function u(a, b, c) { for (var d = [], e = [], f = 0; f < a.length;) { var g = b ? a[f][b] : a[f]; s(e, g) < 0 && d.push(a[f]), e[f] = g, f++ } return c && (d = b ? d.sort(function (a, c) { return a[b] > c[b] }) : d.sort()), d } function v(a, b) { for (var c, e, f = b[0].toUpperCase() + b.slice(1), g = 0; g < ib.length;) { if (c = ib[g], e = c ? c + f : b, e in a) return e; g++ } return d } function w() { return ob++ } function x(a) { var b = a.ownerDocument; return b.defaultView || b.parentWindow } function y(a, b) { var c = this; this.manager = a, this.callback = b, this.element = a.element, this.target = a.options.inputTarget, this.domHandler = function (b) { l(a.options.enable, [a]) && c.handler(b) }, this.init() } function z(a) { var b, c = a.options.inputClass; return new (b = c ? c : rb ? N : sb ? Q : qb ? S : M)(a, A) } function A(a, b, c) { var d = c.pointers.length, e = c.changedPointers.length, f = b & yb && d - e === 0, g = b & (Ab | Bb) && d - e === 0; c.isFirst = !!f, c.isFinal = !!g, f && (a.session = {}), c.eventType = b, B(a, c), a.emit("hammer.input", c), a.recognize(c), a.session.prevInput = c } function B(a, b) { var c = a.session, d = b.pointers, e = d.length; c.firstInput || (c.firstInput = E(b)), e > 1 && !c.firstMultiple ? c.firstMultiple = E(b) : 1 === e && (c.firstMultiple = !1); var f = c.firstInput, g = c.firstMultiple, h = g ? g.center : f.center, i = b.center = F(d); b.timeStamp = nb(), b.deltaTime = b.timeStamp - f.timeStamp, b.angle = J(h, i), b.distance = I(h, i), C(c, b), b.offsetDirection = H(b.deltaX, b.deltaY), b.scale = g ? L(g.pointers, d) : 1, b.rotation = g ? K(g.pointers, d) : 0, D(c, b); var j = a.element; p(b.srcEvent.target, j) && (j = b.srcEvent.target), b.target = j } function C(a, b) { var c = b.center, d = a.offsetDelta || {}, e = a.prevDelta || {}, f = a.prevInput || {}; (b.eventType === yb || f.eventType === Ab) && (e = a.prevDelta = { x: f.deltaX || 0, y: f.deltaY || 0 }, d = a.offsetDelta = { x: c.x, y: c.y }), b.deltaX = e.x + (c.x - d.x), b.deltaY = e.y + (c.y - d.y) } function D(a, b) { var c, e, f, g, h = a.lastInterval || b, i = b.timeStamp - h.timeStamp; if (b.eventType != Bb && (i > xb || h.velocity === d)) { var j = h.deltaX - b.deltaX, k = h.deltaY - b.deltaY, l = G(i, j, k); e = l.x, f = l.y, c = mb(l.x) > mb(l.y) ? l.x : l.y, g = H(j, k), a.lastInterval = b } else c = h.velocity, e = h.velocityX, f = h.velocityY, g = h.direction; b.velocity = c, b.velocityX = e, b.velocityY = f, b.direction = g } function E(a) { for (var b = [], c = 0; c < a.pointers.length;) b[c] = { clientX: lb(a.pointers[c].clientX), clientY: lb(a.pointers[c].clientY) }, c++; return { timeStamp: nb(), pointers: b, center: F(b), deltaX: a.deltaX, deltaY: a.deltaY } } function F(a) { var b = a.length; if (1 === b) return { x: lb(a[0].clientX), y: lb(a[0].clientY) }; for (var c = 0, d = 0, e = 0; b > e;) c += a[e].clientX, d += a[e].clientY, e++; return { x: lb(c / b), y: lb(d / b) } } function G(a, b, c) { return { x: b / a || 0, y: c / a || 0 } } function H(a, b) { return a === b ? Cb : mb(a) >= mb(b) ? a > 0 ? Db : Eb : b > 0 ? Fb : Gb } function I(a, b, c) { c || (c = Kb); var d = b[c[0]] - a[c[0]], e = b[c[1]] - a[c[1]]; return Math.sqrt(d * d + e * e) } function J(a, b, c) { c || (c = Kb); var d = b[c[0]] - a[c[0]], e = b[c[1]] - a[c[1]]; return 180 * Math.atan2(e, d) / Math.PI } function K(a, b) { return J(b[1], b[0], Lb) - J(a[1], a[0], Lb) } function L(a, b) { return I(b[0], b[1], Lb) / I(a[0], a[1], Lb) } function M() { this.evEl = Nb, this.evWin = Ob, this.allow = !0, this.pressed = !1, y.apply(this, arguments) } function N() { this.evEl = Rb, this.evWin = Sb, y.apply(this, arguments), this.store = this.manager.session.pointerEvents = [] } function O() { this.evTarget = Ub, this.evWin = Vb, this.started = !1, y.apply(this, arguments) } function P(a, b) { var c = t(a.touches), d = t(a.changedTouches); return b & (Ab | Bb) && (c = u(c.concat(d), "identifier", !0)), [c, d] } function Q() { this.evTarget = Xb, this.targetIds = {}, y.apply(this, arguments) } function R(a, b) { var c = t(a.touches), d = this.targetIds; if (b & (yb | zb) && 1 === c.length) return d[c[0].identifier] = !0, [c, c]; var e, f, g = t(a.changedTouches), h = [], i = this.target; if (f = c.filter(function (a) { return p(a.target, i) }), b === yb) for (e = 0; e < f.length;) d[f[e].identifier] = !0, e++; for (e = 0; e < g.length;) d[g[e].identifier] && h.push(g[e]), b & (Ab | Bb) && delete d[g[e].identifier], e++; return h.length ? [u(f.concat(h), "identifier", !0), h] : void 0 } function S() { y.apply(this, arguments); var a = k(this.handler, this); this.touch = new Q(this.manager, a), this.mouse = new M(this.manager, a) } function T(a, b) { this.manager = a, this.set(b) } function U(a) { if (q(a, bc)) return bc; var b = q(a, cc), c = q(a, dc); return b && c ? cc + " " + dc : b || c ? b ? cc : dc : q(a, ac) ? ac : _b } function V(a) { this.id = w(), this.manager = null, this.options = i(a || {}, this.defaults), this.options.enable = m(this.options.enable, !0), this.state = ec, this.simultaneous = {}, this.requireFail = [] } function W(a) { return a & jc ? "cancel" : a & hc ? "end" : a & gc ? "move" : a & fc ? "start" : "" } function X(a) { return a == Gb ? "down" : a == Fb ? "up" : a == Db ? "left" : a == Eb ? "right" : "" } function Y(a, b) { var c = b.manager; return c ? c.get(a) : a } function Z() { V.apply(this, arguments) } function $() { Z.apply(this, arguments), this.pX = null, this.pY = null } function _() { Z.apply(this, arguments) } function ab() { V.apply(this, arguments), this._timer = null, this._input = null } function bb() { Z.apply(this, arguments) } function cb() { Z.apply(this, arguments) } function db() { V.apply(this, arguments), this.pTime = !1, this.pCenter = !1, this._timer = null, this._input = null, this.count = 0 } function eb(a, b) { return b = b || {}, b.recognizers = m(b.recognizers, eb.defaults.preset), new fb(a, b) } function fb(a, b) { b = b || {}, this.options = i(b, eb.defaults), this.options.inputTarget = this.options.inputTarget || a, this.handlers = {}, this.session = {}, this.recognizers = [], this.element = a, this.input = z(this), this.touchAction = new T(this, this.options.touchAction), gb(this, !0), g(b.recognizers, function (a) { var b = this.add(new a[0](a[1])); a[2] && b.recognizeWith(a[2]), a[3] && b.requireFailure(a[3]) }, this) } function gb(a, b) { var c = a.element; g(a.options.cssProps, function (a, d) { c.style[v(c.style, d)] = b ? a : "" }) } function hb(a, c) { var d = b.createEvent("Event"); d.initEvent(a, !0, !0), d.gesture = c, c.target.dispatchEvent(d) } var ib = ["", "webkit", "moz", "MS", "ms", "o"], jb = b.createElement("div"), kb = "function", lb = Math.round, mb = Math.abs, nb = Date.now, ob = 1, pb = /mobile|tablet|ip(ad|hone|od)|android/i, qb = "ontouchstart" in a, rb = v(a, "PointerEvent") !== d, sb = qb && pb.test(navigator.userAgent), tb = "touch", ub = "pen", vb = "mouse", wb = "kinect", xb = 25, yb = 1, zb = 2, Ab = 4, Bb = 8, Cb = 1, Db = 2, Eb = 4, Fb = 8, Gb = 16, Hb = Db | Eb, Ib = Fb | Gb, Jb = Hb | Ib, Kb = ["x", "y"], Lb = ["clientX", "clientY"]; y.prototype = { handler: function () { }, init: function () { this.evEl && n(this.element, this.evEl, this.domHandler), this.evTarget && n(this.target, this.evTarget, this.domHandler), this.evWin && n(x(this.element), this.evWin, this.domHandler) }, destroy: function () { this.evEl && o(this.element, this.evEl, this.domHandler), this.evTarget && o(this.target, this.evTarget, this.domHandler), this.evWin && o(x(this.element), this.evWin, this.domHandler) } }; var Mb = { mousedown: yb, mousemove: zb, mouseup: Ab }, Nb = "mousedown", Ob = "mousemove mouseup"; j(M, y, { handler: function (a) { var b = Mb[a.type]; b & yb && 0 === a.button && (this.pressed = !0), b & zb && 1 !== a.which && (b = Ab), this.pressed && this.allow && (b & Ab && (this.pressed = !1), this.callback(this.manager, b, { pointers: [a], changedPointers: [a], pointerType: vb, srcEvent: a })) } }); var Pb = { pointerdown: yb, pointermove: zb, pointerup: Ab, pointercancel: Bb, pointerout: Bb }, Qb = { 2: tb, 3: ub, 4: vb, 5: wb }, Rb = "pointerdown", Sb = "pointermove pointerup pointercancel"; a.MSPointerEvent && (Rb = "MSPointerDown", Sb = "MSPointerMove MSPointerUp MSPointerCancel"), j(N, y, { handler: function (a) { var b = this.store, c = !1, d = a.type.toLowerCase().replace("ms", ""), e = Pb[d], f = Qb[a.pointerType] || a.pointerType, g = f == tb, h = s(b, a.pointerId, "pointerId"); e & yb && (0 === a.button || g) ? 0 > h && (b.push(a), h = b.length - 1) : e & (Ab | Bb) && (c = !0), 0 > h || (b[h] = a, this.callback(this.manager, e, { pointers: b, changedPointers: [a], pointerType: f, srcEvent: a }), c && b.splice(h, 1)) } }); var Tb = { touchstart: yb, touchmove: zb, touchend: Ab, touchcancel: Bb }, Ub = "touchstart", Vb = "touchstart touchmove touchend touchcancel"; j(O, y, { handler: function (a) { var b = Tb[a.type]; if (b === yb && (this.started = !0), this.started) { var c = P.call(this, a, b); b & (Ab | Bb) && c[0].length - c[1].length === 0 && (this.started = !1), this.callback(this.manager, b, { pointers: c[0], changedPointers: c[1], pointerType: tb, srcEvent: a }) } } }); var Wb = { touchstart: yb, touchmove: zb, touchend: Ab, touchcancel: Bb }, Xb = "touchstart touchmove touchend touchcancel"; j(Q, y, { handler: function (a) { var b = Wb[a.type], c = R.call(this, a, b); c && this.callback(this.manager, b, { pointers: c[0], changedPointers: c[1], pointerType: tb, srcEvent: a }) } }), j(S, y, { handler: function (a, b, c) { var d = c.pointerType == tb, e = c.pointerType == vb; if (d) this.mouse.allow = !1; else if (e && !this.mouse.allow) return; b & (Ab | Bb) && (this.mouse.allow = !0), this.callback(a, b, c) }, destroy: function () { this.touch.destroy(), this.mouse.destroy() } }); var Yb = v(jb.style, "touchAction"), Zb = Yb !== d, $b = "compute", _b = "auto", ac = "manipulation", bc = "none", cc = "pan-x", dc = "pan-y"; T.prototype = { set: function (a) { a == $b && (a = this.compute()), Zb && (this.manager.element.style[Yb] = a), this.actions = a.toLowerCase().trim() }, update: function () { this.set(this.manager.options.touchAction) }, compute: function () { var a = []; return g(this.manager.recognizers, function (b) { l(b.options.enable, [b]) && (a = a.concat(b.getTouchAction())) }), U(a.join(" ")) }, preventDefaults: function (a) { if (!Zb) { var b = a.srcEvent, c = a.offsetDirection; if (this.manager.session.prevented) return void b.preventDefault(); var d = this.actions, e = q(d, bc), f = q(d, dc), g = q(d, cc); return e || f && c & Hb || g && c & Ib ? this.preventSrc(b) : void 0 } }, preventSrc: function (a) { this.manager.session.prevented = !0, a.preventDefault() } }; var ec = 1, fc = 2, gc = 4, hc = 8, ic = hc, jc = 16, kc = 32; V.prototype = { defaults: {}, set: function (a) { return h(this.options, a), this.manager && this.manager.touchAction.update(), this }, recognizeWith: function (a) { if (f(a, "recognizeWith", this)) return this; var b = this.simultaneous; return a = Y(a, this), b[a.id] || (b[a.id] = a, a.recognizeWith(this)), this }, dropRecognizeWith: function (a) { return f(a, "dropRecognizeWith", this) ? this : (a = Y(a, this), delete this.simultaneous[a.id], this) }, requireFailure: function (a) { if (f(a, "requireFailure", this)) return this; var b = this.requireFail; return a = Y(a, this), -1 === s(b, a) && (b.push(a), a.requireFailure(this)), this }, dropRequireFailure: function (a) { if (f(a, "dropRequireFailure", this)) return this; a = Y(a, this); var b = s(this.requireFail, a); return b > -1 && this.requireFail.splice(b, 1), this }, hasRequireFailures: function () { return this.requireFail.length > 0 }, canRecognizeWith: function (a) { return !!this.simultaneous[a.id] }, emit: function (a) { function b(b) { c.manager.emit(c.options.event + (b ? W(d) : ""), a) } var c = this, d = this.state; hc > d && b(!0), b(), d >= hc && b(!0) }, tryEmit: function (a) { return this.canEmit() ? this.emit(a) : void (this.state = kc) }, canEmit: function () { for (var a = 0; a < this.requireFail.length;) { if (!(this.requireFail[a].state & (kc | ec))) return !1; a++ } return !0 }, recognize: function (a) { var b = h({}, a); return l(this.options.enable, [this, b]) ? (this.state & (ic | jc | kc) && (this.state = ec), this.state = this.process(b), void (this.state & (fc | gc | hc | jc) && this.tryEmit(b))) : (this.reset(), void (this.state = kc)) }, process: function () { }, getTouchAction: function () { }, reset: function () { } }, j(Z, V, { defaults: { pointers: 1 }, attrTest: function (a) { var b = this.options.pointers; return 0 === b || a.pointers.length === b }, process: function (a) { var b = this.state, c = a.eventType, d = b & (fc | gc), e = this.attrTest(a); return d && (c & Bb || !e) ? b | jc : d || e ? c & Ab ? b | hc : b & fc ? b | gc : fc : kc } }), j($, Z, { defaults: { event: "pan", threshold: 10, pointers: 1, direction: Jb }, getTouchAction: function () { var a = this.options.direction, b = []; return a & Hb && b.push(dc), a & Ib && b.push(cc), b }, directionTest: function (a) { var b = this.options, c = !0, d = a.distance, e = a.direction, f = a.deltaX, g = a.deltaY; return e & b.direction || (b.direction & Hb ? (e = 0 === f ? Cb : 0 > f ? Db : Eb, c = f != this.pX, d = Math.abs(a.deltaX)) : (e = 0 === g ? Cb : 0 > g ? Fb : Gb, c = g != this.pY, d = Math.abs(a.deltaY))), a.direction = e, c && d > b.threshold && e & b.direction }, attrTest: function (a) { return Z.prototype.attrTest.call(this, a) && (this.state & fc || !(this.state & fc) && this.directionTest(a)) }, emit: function (a) { this.pX = a.deltaX, this.pY = a.deltaY; var b = X(a.direction); b && this.manager.emit(this.options.event + b, a), this._super.emit.call(this, a) } }), j(_, Z, { defaults: { event: "pinch", threshold: 0, pointers: 2 }, getTouchAction: function () { return [bc] }, attrTest: function (a) { return this._super.attrTest.call(this, a) && (Math.abs(a.scale - 1) > this.options.threshold || this.state & fc) }, emit: function (a) { if (this._super.emit.call(this, a), 1 !== a.scale) { var b = a.scale < 1 ? "in" : "out"; this.manager.emit(this.options.event + b, a) } } }), j(ab, V, { defaults: { event: "press", pointers: 1, time: 500, threshold: 5 }, getTouchAction: function () { return [_b] }, process: function (a) { var b = this.options, c = a.pointers.length === b.pointers, d = a.distance < b.threshold, f = a.deltaTime > b.time; if (this._input = a, !d || !c || a.eventType & (Ab | Bb) && !f) this.reset(); else if (a.eventType & yb) this.reset(), this._timer = e(function () { this.state = ic, this.tryEmit() }, b.time, this); else if (a.eventType & Ab) return ic; return kc }, reset: function () { clearTimeout(this._timer) }, emit: function (a) { this.state === ic && (a && a.eventType & Ab ? this.manager.emit(this.options.event + "up", a) : (this._input.timeStamp = nb(), this.manager.emit(this.options.event, this._input))) } }), j(bb, Z, { defaults: { event: "rotate", threshold: 0, pointers: 2 }, getTouchAction: function () { return [bc] }, attrTest: function (a) { return this._super.attrTest.call(this, a) && (Math.abs(a.rotation) > this.options.threshold || this.state & fc) } }), j(cb, Z, { defaults: { event: "swipe", threshold: 10, velocity: .65, direction: Hb | Ib, pointers: 1 }, getTouchAction: function () { return $.prototype.getTouchAction.call(this) }, attrTest: function (a) { var b, c = this.options.direction; return c & (Hb | Ib) ? b = a.velocity : c & Hb ? b = a.velocityX : c & Ib && (b = a.velocityY), this._super.attrTest.call(this, a) && c & a.direction && a.distance > this.options.threshold && mb(b) > this.options.velocity && a.eventType & Ab }, emit: function (a) { var b = X(a.direction); b && this.manager.emit(this.options.event + b, a), this.manager.emit(this.options.event, a) } }), j(db, V, { defaults: { event: "tap", pointers: 1, taps: 1, interval: 300, time: 250, threshold: 2, posThreshold: 10 }, getTouchAction: function () { return [ac] }, process: function (a) { var b = this.options, c = a.pointers.length === b.pointers, d = a.distance < b.threshold, f = a.deltaTime < b.time; if (this.reset(), a.eventType & yb && 0 === this.count) return this.failTimeout(); if (d && f && c) { if (a.eventType != Ab) return this.failTimeout(); var g = this.pTime ? a.timeStamp - this.pTime < b.interval : !0, h = !this.pCenter || I(this.pCenter, a.center) < b.posThreshold; this.pTime = a.timeStamp, this.pCenter = a.center, h && g ? this.count += 1 : this.count = 1, this._input = a; var i = this.count % b.taps; if (0 === i) return this.hasRequireFailures() ? (this._timer = e(function () { this.state = ic, this.tryEmit() }, b.interval, this), fc) : ic } return kc }, failTimeout: function () { return this._timer = e(function () { this.state = kc }, this.options.interval, this), kc }, reset: function () { clearTimeout(this._timer) }, emit: function () { this.state == ic && (this._input.tapCount = this.count, this.manager.emit(this.options.event, this._input)) } }), eb.VERSION = "2.0.4", eb.defaults = { domEvents: !1, touchAction: $b, enable: !0, inputTarget: null, inputClass: null, preset: [[bb, { enable: !1 }], [_, { enable: !1 }, ["rotate"]], [cb, { direction: Hb }], [$, { direction: Hb }, ["swipe"]], [db], [db, { event: "doubletap", taps: 2 }, ["tap"]], [ab]], cssProps: { userSelect: "none", touchSelect: "none", touchCallout: "none", contentZooming: "none", userDrag: "none", tapHighlightColor: "rgba(0,0,0,0)" } }; var lc = 1, mc = 2; fb.prototype = { set: function (a) { return h(this.options, a), a.touchAction && this.touchAction.update(), a.inputTarget && (this.input.destroy(), this.input.target = a.inputTarget, this.input.init()), this }, stop: function (a) { this.session.stopped = a ? mc : lc }, recognize: function (a) { var b = this.session; if (!b.stopped) { this.touchAction.preventDefaults(a); var c, d = this.recognizers, e = b.curRecognizer; (!e || e && e.state & ic) && (e = b.curRecognizer = null); for (var f = 0; f < d.length;) c = d[f], b.stopped === mc || e && c != e && !c.canRecognizeWith(e) ? c.reset() : c.recognize(a), !e && c.state & (fc | gc | hc) && (e = b.curRecognizer = c), f++ } }, get: function (a) { if (a instanceof V) return a; for (var b = this.recognizers, c = 0; c < b.length; c++) if (b[c].options.event == a) return b[c]; return null }, add: function (a) { if (f(a, "add", this)) return this; var b = this.get(a.options.event); return b && this.remove(b), this.recognizers.push(a), a.manager = this, this.touchAction.update(), a }, remove: function (a) { if (f(a, "remove", this)) return this; var b = this.recognizers; return a = this.get(a), b.splice(s(b, a), 1), this.touchAction.update(), this }, on: function (a, b) { var c = this.handlers; return g(r(a), function (a) { c[a] = c[a] || [], c[a].push(b) }), this }, off: function (a, b) { var c = this.handlers; return g(r(a), function (a) { b ? c[a].splice(s(c[a], b), 1) : delete c[a] }), this }, emit: function (a, b) { this.options.domEvents && hb(a, b); var c = this.handlers[a] && this.handlers[a].slice(); if (c && c.length) { b.type = a, b.preventDefault = function () { b.srcEvent.preventDefault() }; for (var d = 0; d < c.length;) c[d](b), d++ } }, destroy: function () { this.element && gb(this, !1), this.handlers = {}, this.session = {}, this.input.destroy(), this.element = null } }, h(eb, { INPUT_START: yb, INPUT_MOVE: zb, INPUT_END: Ab, INPUT_CANCEL: Bb, STATE_POSSIBLE: ec, STATE_BEGAN: fc, STATE_CHANGED: gc, STATE_ENDED: hc, STATE_RECOGNIZED: ic, STATE_CANCELLED: jc, STATE_FAILED: kc, DIRECTION_NONE: Cb, DIRECTION_LEFT: Db, DIRECTION_RIGHT: Eb, DIRECTION_UP: Fb, DIRECTION_DOWN: Gb, DIRECTION_HORIZONTAL: Hb, DIRECTION_VERTICAL: Ib, DIRECTION_ALL: Jb, Manager: fb, Input: y, TouchAction: T, TouchInput: Q, MouseInput: M, PointerEventInput: N, TouchMouseInput: S, SingleTouchInput: O, Recognizer: V, AttrRecognizer: Z, Tap: db, Pan: $, Swipe: cb, Pinch: _, Rotate: bb, Press: ab, on: n, off: o, each: g, merge: i, extend: h, inherit: j, bindFn: k, prefixed: v }), typeof define == kb && define.amd ? define(function () { return eb }) : "undefined" != typeof module && module.exports ? module.exports = eb : a[c] = eb }(window, document, "Hammer"); }

(function (n, t) { "use strict"; function g(t) { var i, u, f; for (t = n.extend({}, h, d, t), s = bt(), i = n(this), u = 0, f = i.length; u < f; u++) nt(i.eq(u), t); return r = n(".zoomer-element"), pt(), i } function nt(t, i) { var f, r; if (!t.data("zoomer")) { i = n.extend({}, i, t.data("zoomer-options")); f = t.parent(); i.$target = t; i.marginReal = i.marginMin * 2; i.originalDOM = i.$target.html(); i.$target.find("img").length > 0 && (i.source = [], i.$target.find("img").each(function () { i.source.push(n(this).attr("src")) }), i.$target.empty()); i = b(i); r = '<div class="zoomer ' + i.customClass + '">'; r += '<div class="zoomer-positioner">'; r += '<div class="zoomer-holder">'; r += "<\/div>"; r += "<\/div>"; r += "<\/div>"; i.$zoomer = n(r); i.$target.addClass("zoomer-element").html(i.$zoomer); i.controls.zoomIn || i.controls.zoomOut || i.controls.next || i.controls.previous ? (i.controls.$zoomIn = n(i.controls.zoomIn, f), i.controls.$zoomOut = n(i.controls.zoomOut, f), i.controls.$next = n(i.controls.next, f), i.controls.$previous = n(i.controls.previous, f)) : (r = '<div class="zoomer-controls zoomer-controls-' + i.controls.position + '">', r += '<span class="zoomer-previous">&lsaquo;<\/span>', r += '<span class="zoomer-zoom-out" onclick="zoomcheck(this)"><i class="fa fa-minus-circle" aria-hidden="true"><\/i><\/span>', r += '<span class="zoomer-zoom-in" onclick="zoomcheck(this)" ><i class="fa fa-plus-circle" aria-hidden="true"><\/i><\/span>', r += '<span class="zoomer-next">&rsaquo;<\/span>', r += "<\/div>", i.$zoomer.append(r), i.controls.$default = i.$zoomer.find(".zoomer-controls"), i.controls.$zoomIn = i.$zoomer.find(".zoomer-zoom-in"), i.controls.$zoomOut = i.$zoomer.find(".zoomer-zoom-out"), i.controls.$next = i.$zoomer.find(".zoomer-next"), i.controls.$previous = i.$zoomer.find(".zoomer-previous")); i.$positioner = i.$zoomer.find(".zoomer-positioner"); i.$holder = i.$zoomer.find(".zoomer-holder"); i.controls.$zoomIn.on("touchstart.zoomer mousedown.zoomer", i, ot).on("touchend.zoomer mouseup.zoomer", i, p); i.controls.$zoomOut.on("touchstart.zoomer mousedown.zoomer", i, st).on("touchend.zoomer mouseup.zoomer", i, p); i.controls.$next.on("click.zoomer", i, ft); i.controls.$previous.on("click.zoomer", i, et); i.$zoomer.on("mousedown.zoomer", i, ht).on("touchstart.zoomer MSPointerDown.zoomer", ":not(.zoomer-controls)", i, l); i.$target.data("zoomer", i); u.resize.apply(i.$target); i.images.length > 0 && e.apply(i.$target, [i]) } } function e(n) { n.gallery ? n.$zoomer.addClass("zoomer-gallery") : n.$zoomer.removeClass("zoomer-gallery"); typeof n.$image != "undefined" ? n.$holder.animate({ opacity: 0 }, 300, function () { u.unload.apply(n.$target); a.apply(n.$target, [n, n.images[n.index]]) }) : a.apply(n.$target, [n, n.images[n.index]]) } function a(t, i) { var u, r, f; if (t.loading = !0, t.tiled) { t.tilesTotal = 0; t.tilesLoaded = 0; u = '<div class="zoomer-tiles">'; for (r in t.images[0]) if (t.images[0].hasOwnProperty(r)) for (f in t.images[0][r]) t.images[0][r].hasOwnProperty(f) && (u += '<img class="zoomer-image zoomer-tile" src="' + t.images[0][r][f] + '" data-zoomer-tile="' + r + "-" + f + '" />', t.tilesTotal++); u += "<\/div>"; t.$image = n(u); t.$tiles = t.$image.find("img"); t.$tiles.each(function (i, r) { var u = n(r); u.one("load", t, tt); u[0].complete && u.trigger("load") }) } else t.$image = n('<img class="zoomer-image" />'), t.$image.one("load.zoomer", t, v).attr("src", i), t.$image[0].complete && t.$image.trigger("load") } function tt(n) { var t = n.data; t.tilesLoaded++; t.tilesLoaded === t.tilesTotal && (t.tiledRows = t.images[0].length, t.tiledColumns = t.images[0][0].length, t.tiledHeight = t.$tiles.eq(0)[0].naturalHeight * t.tiledRows, t.tiledWidth = t.$tiles.eq(0)[0].naturalWidth * t.tiledColumns, v({ data: t })) } function v(t) { var i = t.data, r, u; i.tiled ? (i.naturalHeight = i.tiledHeight, i.naturalWidth = i.tiledWidth) : (i.naturalHeight = i.$image[0].naturalHeight, i.naturalWidth = i.$image[0].naturalWidth); i.retina && (i.naturalHeight /= 2, i.naturalWidth /= 2); i.$holder.css({ height: i.naturalHeight, width: i.naturalWidth }); i.targetImageHeight = i.minHeight = i.maxHeight = i.naturalHeight; i.targetImageWidth = i.minWidth = i.maxWidth = i.naturalWidth; i.imageRatioWide = i.naturalWidth / i.naturalHeight; i.imageRatioTall = i.naturalHeight / i.naturalWidth; (i.naturalHeight > i.frameHeight - i.marginReal || i.naturalWidth > i.frameWidth - i.marginReal) && (i = y(i), i.targetImageHeight = i.minHeight, i.targetImageWidth = i.minWidth); i.positionerLeft = i.targetPositionerLeft = i.centerLeft; i.positionerTop = i.targetPositionerTop = i.centerTop; i.imageLeft = i.targetImageLeft = Math.round(-i.targetImageWidth / 2); i.imageTop = i.targetImageTop = Math.round(-i.targetImageHeight / 2); i.imageHeight = i.targetImageHeight; i.imageWidth = i.targetImageWidth; s ? (r = i.imageWidth / i.naturalWidth, u = i.imageHeight / i.naturalHeight, i.$positioner.css(o("transform", "translate3d(" + i.positionerLeft + "px, " + i.positionerTop + "px, 0)")), i.$holder.css(o("transform", "translate3d(-50%, -50%, 0) scale(" + r + "," + u + ")"))) : (i.$positioner.css({ left: i.positionerLeft, top: i.positionerTop }), i.$holder.css({ left: i.imageLeft, top: i.imageTop, height: i.imageHeight, width: i.imageWidth })); i.$holder.append(i.$image); i.tiled && (i.$holder.css({ background: "url(" + i.tiledThumbnail + ") no-repeat left top", backgroundSize: "100% 100%" }), i.tileHeightPercentage = 100 / i.tiledRows, i.tileWidthPercentage = 100 / i.tiledColumns, i.$tiles.css({ height: i.tileHeightPercentage + "%", width: i.tileWidthPercentage + "%" }), i.$tiles.each(function (t, r) { var u = n(r), f = u.data("zoomer-tile").split("-"); u.css({ left: i.tileWidthPercentage * parseInt(f[1], 10) + "%", top: i.tileHeightPercentage * parseInt(f[0], 10) + "%" }) })); i.$holder.animate({ opacity: 1 }, 300); i.loading = !1; i.gallery && it(i) } function it(t) { t.index > 0 && n('<img src="' + t.images[t.index - 1] + '">'); t.index < t.images.length - 1 && n('<img src="' + t.images[t.index + 1] + '">') } function y(n) { return n.naturalHeight > n.naturalWidth ? (n.aspect = "tall", n.minHeight = Math.round(n.frameHeight - n.marginReal), n.minWidth = Math.round(n.minHeight / n.imageRatioTall), n.minWidth > n.frameWidth - n.marginReal && (n.minWidth = Math.round(n.frameWidth - n.marginReal), n.minHeight = Math.round(n.minWidth / n.imageRatioWide))) : (n.aspect = "wide", n.minWidth = Math.round(n.frameWidth - n.marginReal), n.minHeight = Math.round(n.minWidth / n.imageRatioWide), n.minHeight > n.frameHeight - n.marginReal && (n.minHeight = Math.round(n.frameHeight - n.marginReal), n.minWidth = Math.round(n.minHeight / n.imageRatioTall))), n } function rt() { for (var n, u, f, t = 0, i = r.length; t < i; t++) n = r.eq(t).data("zoomer"), typeof n == "object" && (n = ut(n), n.lastAction = n.action, s ? (u = n.imageWidth / n.naturalWidth, f = n.imageHeight / n.naturalHeight, n.$positioner.css(o("transform", "translate3d(" + n.positionerLeft + "px, " + n.positionerTop + "px, 0)")), n.$holder.css(o("transform", "translate3d(-50%, -50%, 0) scale(" + u + "," + f + ")"))) : (n.$positioner.css({ left: n.positionerLeft, top: n.positionerTop }), n.$holder.css({ left: n.imageLeft, top: n.imageTop, width: n.imageWidth, height: n.imageHeight })), n.callback && n.callback.apply(n.$zoomer, [(n.imageWidth - n.minWidth) / (n.maxWidth - n.minWidth)])) } function ut(n) { if (n.action === "zoom_in" || n.action === "zoom_out") { n.keyDownTime += n.increment; var t = (n.action === "zoom_out" ? -1 : 1) * Math.round(n.imageWidth * n.keyDownTime - n.imageWidth); n.aspect === "tall" ? (n.targetImageHeight += t, n.targetImageWidth = Math.round(n.targetImageHeight / n.imageRatioTall)) : (n.targetImageWidth += t, n.targetImageHeight = Math.round(n.targetImageWidth / n.imageRatioWide)) } return n.aspect === "tall" ? n.targetImageHeight < n.minHeight ? (n.targetImageHeight = n.minHeight, n.targetImageWidth = Math.round(n.targetImageHeight / n.imageRatioTall)) : n.targetImageHeight > n.maxHeight && (n.targetImageHeight = n.maxHeight, n.targetImageWidth = Math.round(n.targetImageHeight / n.imageRatioTall)) : n.targetImageWidth < n.minWidth ? (n.targetImageWidth = n.minWidth, n.targetImageHeight = Math.round(n.targetImageWidth / n.imageRatioWide)) : n.targetImageWidth > n.maxWidth && (n.targetImageWidth = n.maxWidth, n.targetImageHeight = Math.round(n.targetImageWidth / n.imageRatioWide)), n.targetImageLeft = Math.round(-n.targetImageWidth * .5), n.targetImageTop = Math.round(-n.targetImageHeight * .5), n.action === "drag" || n.action === "pinch" ? (n.imageWidth = n.targetImageWidth, n.imageHeight = n.targetImageHeight, n.imageLeft = n.targetImageLeft, n.imageTop = n.targetImageTop) : (n.imageWidth += Math.round((n.targetImageWidth - n.imageWidth) * n.enertia), n.imageHeight += Math.round((n.targetImageHeight - n.imageHeight) * n.enertia), n.imageLeft += Math.round((n.targetImageLeft - n.imageLeft) * n.enertia), n.imageTop += Math.round((n.targetImageTop - n.imageTop) * n.enertia)), n.boundsLeft = Math.round(n.frameWidth - n.targetImageWidth * .5 - n.marginMax), n.boundsRight = Math.round(n.targetImageWidth * .5 + n.marginMax), n.boundsTop = Math.round(n.frameHeight - n.targetImageHeight * .5 - n.marginMax), n.boundsBottom = Math.round(n.targetImageHeight * .5 + n.marginMax), n.targetPositionerLeft < n.boundsLeft && (n.targetPositionerLeft = n.boundsLeft), n.targetPositionerLeft > n.boundsRight && (n.targetPositionerLeft = n.boundsRight), n.targetPositionerTop < n.boundsTop && (n.targetPositionerTop = n.boundsTop), n.targetPositionerTop > n.boundsBottom && (n.targetPositionerTop = n.boundsBottom), n.zoomPositionTop > 0 && n.zoomPositionLeft > 0 && (n.targetPositionerLeft = n.centerLeft - n.targetImageLeft - n.targetImageWidth * n.zoomPositionLeft, n.targetPositionerTop = n.centerTop - n.targetImageTop - n.targetImageHeight * n.zoomPositionTop), n.action !== "pinch" && (n.targetImageWidth < n.frameWidth && (n.targetPositionerLeft = n.centerLeft), n.targetImageHeight < n.frameHeight && (n.targetPositionerTop = n.centerTop)), n.action === "drag" || n.action === "pinch" ? (n.positionerLeft = n.targetPositionerLeft, n.positionerTop = n.targetPositionerTop) : (n.positionerLeft += Math.round((n.targetPositionerLeft - n.positionerLeft) * n.enertia), n.positionerTop += Math.round((n.targetPositionerTop - n.positionerTop) * n.enertia)), n.oldImageWidth = n.imageWidth, n.oldImageHeight = n.imageHeight, n } function ft(n) { var t = n.data; !t.loading && t.index + 1 < t.images.length && (t.index++, e.apply(t.$target, [t])) } function et(n) { var t = n.data; !t.loading && t.index - 1 >= 0 && (t.index--, e.apply(t.$target, [t])) } function ot(n) { n.preventDefault(); n.stopPropagation(); var t = n.data; t = c(t); t.keyDownTime = 1; t.action = "zoom_in" } function st(n) { n.preventDefault(); n.stopPropagation(); var t = n.data; t = c(t); t.keyDownTime = 1; t.action = "zoom_out" } function p(n) { n.preventDefault(); n.stopPropagation(); var t = n.data; t = w(t); t.keyDownTime = 0; t.action = "" } function c(n, t, i) { return t = t || n.imageWidth * .5, i = i || n.imageHeight * .5, n.zoomPositionLeft = (t - (n.positionerLeft - n.centerLeft)) / n.imageWidth, n.zoomPositionTop = (i - (n.positionerTop - n.centerTop)) / n.imageHeight, n } function w(n) { return n.zoomPositionTop = 0, n.zoomPositionLeft = 0, n } function ht(n) { n.preventDefault && (n.preventDefault(), n.stopPropagation()); var t = n.data; t.action = "drag"; t.mouseX = n.pageX; t.mouseY = n.pageY; t.targetPositionerLeft = t.positionerLeft; t.targetPositionerTop = t.positionerTop; i.on("mousemove.zoomer", t, ct).on("mouseup.zoomer", t, lt) } function ct(n) { n.preventDefault && (n.preventDefault(), n.stopPropagation()); var t = n.data; n.pageX && n.pageY && (t.targetPositionerLeft -= Math.round(t.mouseX - n.pageX), t.targetPositionerTop -= Math.round(t.mouseY - n.pageY), t.mouseX = n.pageX, t.mouseY = n.pageY) } function lt(n) { n.preventDefault && (n.preventDefault(), n.stopPropagation()); var t = n.data; t.action = ""; i.off("mousemove.zoomer mouseup.zoomer") } function l(t) { var r, i, f, u; if (!(n(t.target).parent(".zoomer-controls").length > 0)) { if (t.preventManipulation && t.preventManipulation(), t.preventDefault(), t.stopPropagation(), r = t.data, i = t.originalEvent, i.type.match(/(up|end)$/i)) { yt(r, i); return } if (i.pointerId) { f = !1; for (u in r.touches) r.touches[u].identifier === i.pointerId && (f = !0, r.touches[u].pageX = i.clientX, r.touches[u].pageY = i.clientY); f || r.touches.push({ identifier: i.pointerId, pageX: i.clientX, pageY: i.clientY }) } else r.touches = i.touches; i.type.match(/(down|start)$/i) ? at(r) : i.type.match(/move$/i) && vt(r) } } function at(n) { if (!n.touchEventsBound) { n.touchEventsBound = !0; i.on("touchmove.zoomer MSPointerMove.zoomer", n, l).on("touchend.zoomer MSPointerUp.zoomer", n, l) } n.zoomPercentage = 1; n.touches.length >= 2 && (n.offset = n.$zoomer.offset(), n.pinchStartX0 = n.touches[0].pageX - n.offset.left, n.pinchStartY0 = n.touches[0].pageY - n.offset.top, n.pinchStartX1 = n.touches[1].pageX - n.offset.left, n.pinchStartY1 = n.touches[1].pageY - n.offset.top, n.pinchStartX = (n.pinchStartX0 + n.pinchStartX1) / 2, n.pinchStartY = (n.pinchStartY0 + n.pinchStartY1) / 2, n.imageWidthStart = n.imageWidth, n.imageHeightStart = n.imageHeight, c(n), n.pinchDeltaStart = Math.sqrt(Math.pow(n.pinchStartX1 - n.pinchStartX0, 2) + Math.pow(n.pinchStartY1 - n.pinchStartY0, 2))); n.mouseX = n.touches[0].pageX; n.mouseY = n.touches[0].pageY } function vt(n) { n.touches.length === 1 ? (n.action = "drag", n.targetPositionerLeft -= n.mouseX - n.touches[0].pageX, n.targetPositionerTop -= n.mouseY - n.touches[0].pageY) : n.touches.length >= 2 && (n.action = "pinch", n.pinchEndX0 = n.touches[0].pageX - n.offset.left, n.pinchEndY0 = n.touches[0].pageY - n.offset.top, n.pinchEndX1 = n.touches[1].pageX - n.offset.left, n.pinchEndY1 = n.touches[1].pageY - n.offset.top, (n.pinchEndX0 !== n.lastPinchEndX0 || n.pinchEndY0 !== n.lastPinchEndY0 || n.pinchEndX1 !== n.lastPinchEndX1 || n.pinchEndY1 !== n.lastPinchEndY1) && (n.pinchDeltaEnd = Math.sqrt(Math.pow(n.pinchEndX1 - n.pinchEndX0, 2) + Math.pow(n.pinchEndY1 - n.pinchEndY0, 2)), n.zoomPercentage = n.pinchDeltaEnd / n.pinchDeltaStart, n.targetImageWidth = Math.round(n.imageWidthStart * n.zoomPercentage), n.targetImageHeight = Math.round(n.imageHeightStart * n.zoomPercentage), n.pinchEndX = (n.pinchEndX0 + n.pinchEndX1) / 2, n.pinchEndY = (n.pinchEndY0 + n.pinchEndY1) / 2, n.lastPinchEndX0 = n.pinchEndX0, n.lastPinchEndY0 = n.pinchEndY0, n.lastPinchEndX1 = n.pinchEndX1, n.lastPinchEndY1 = n.pinchEndY1)); n.mouseX = n.touches[0].pageX; n.mouseY = n.touches[0].pageY } function yt(n, t) { if (n.action = "", n.lastPinchEndX0 = n.pinchEndX0 = n.pinchStartX0 = 0, n.lastPinchEndY0 = n.pinchEndY0 = n.pinchStartY0 = 0, n.lastPinchEndX1 = n.pinchEndX1 = n.pinchStartX1 = 0, n.lastPinchEndY1 = n.pinchEndY1 = n.pinchStartY1 = 0, n.pinchStartX = n.pinchEndX = 0, n.pinchStartY = n.pinchEndX = 0, w(n), t.pointerId) for (var r in n.touches) n.touches[r].identifier === t.pointerId && n.touches.splice(r, 1); i.off(".zoomer"); n.touchEventsBound = !1 } function b(n) { return n.tiled = !1, n.gallery = !1, typeof n.source == "string" ? n.images = [n.source] : typeof n.source[0] == "string" ? (n.images = n.source, n.images.length > 1 && (n.gallery = !0)) : (n.tiledThumbnail = n.source.thumbnail, n.images = [n.source.tiles], n.tiled = !0), n } function pt() { f || (f = !0, k()) } function wt() { f = !1 } function k() { f && (t.requestAnimationFrame(k), rt()) } function o(n, t) { var i = {}; return i["-webkit-" + n] = t, i["-moz-" + n] = t, i["-ms-" + n] = t, i["-o-" + n] = t, i[n] = t, i } function bt() { var n = document.createElement("p"), i, u = { webkitTransform: "-webkit-transform", OTransform: "-o-transform", msTransform: "-ms-transform", MozTransform: "-moz-transform", transform: "transform" }, r; document.body.insertBefore(n, null); for (r in u) n.style[r] !== undefined && (n.style[r] = "translate3d(1px,1px,1px)", i = t.getComputedStyle(n).getPropertyValue(u[r])); return document.body.removeChild(n), i !== undefined && i.length > 0 && i !== "none" } var i = n(t), r, f = !1, s = !1, h = { callback: n.noop, controls: { position: "bottom", zoomIn: null, zoomOut: null, next: null, previous: null }, customClass: "", enertia: .2, increment: .01, marginMin: 30, marginMax: 100, retina: !1, source: null }, d = { images: [], aspect: "", action: "", lastAction: "", keyDownTime: 0, marginReal: 0, originalDOM: "", gallery: !1, index: 0, $tiles: null, tiled: !1, tilesTotal: 0, tilesLoaded: 0, tiledColumns: 0, tiledRows: 0, tiledHeight: 0, tiledWidth: 0, tiledThumbnail: null, centerLeft: 0, centerTop: 0, frameHeight: 0, frameWidth: 0, naturalHeight: 0, naturalWidth: 0, imageRatioWide: 0, imageRatioTall: 0, minHeight: null, minWidth: null, maxHeight: 0, maxWidth: 0, boundsTop: 0, boundsBottom: 0, boundsLeft: 0, boundsRight: 0, imageWidth: 0, imageHeight: 0, imageLeft: 0, imageTop: 0, targetImageWidth: 0, targetImageHeight: 0, targetImageLeft: 0, targetImageTop: 0, oldImageWidth: 0, oldImageHeight: 0, positionerLeft: 0, positionerTop: 0, targetPositionerLeft: 0, targetPositionerTop: 0, zoomPositionLeft: 0, zoomPositionTop: 0, offset: null, touches: [], zoomPercentage: 1, pinchStartX0: 0, pinchStartX1: 0, pinchStartY0: 0, pinchStartY1: 0, pinchEndX0: 0, pinchEndX1: 0, pinchEndY0: 0, pinchEndY1: 0, lastPinchEndX0: 0, lastPinchEndY0: 0, lastPinchEndX1: 0, lastPinchEndY1: 0, pinchDeltaStart: 0, pinchDeltaEnd: 0 }, u = { defaults: function (t) { return h = n.extend(h, t || {}), typeof this == "object" ? n(this) : !0 }, destroy: function () { var t = n(this).each(function (t, r) { var u = n(r).data("zoomer"); u && (i.off(".zoomer"), u.$holder.off(".zoomer"), u.$zoomer.off(".zoomer"), u.controls.$zoomIn.off(".zoomer"), u.controls.$zoomOut.off(".zoomer"), u.controls.$next.off(".zoomer"), u.controls.$previous.off(".zoomer"), u.$target.removeClass("zoomer-element").data("zoomer", null).empty().append(u.originalDOM)) }); return r = n(".zoomer-element"), r.length < 1 && wt(), t }, load: function (t) { return n(this).each(function (i, r) { var u = n(r).data("zoomer"); u && (u.source = t, u.index = 0, u = b(u), e(u)) }) }, pan: function (t, i) { return n(this).each(function (r, u) { var f = n(u).data("zoomer"); f && (t /= 100, i /= 100, f.targetPositionerLeft = Math.round(f.centerLeft - f.targetImageLeft - f.targetImageWidth * t), f.targetPositionerTop = Math.round(f.centerTop - f.targetImageTop - f.targetImageHeight * i)) }) }, resize: function () { return n(this).each(function (t, i) { var r = n(i).data("zoomer"); r && (r.frameWidth = r.$target.outerWidth(), r.frameHeight = r.$target.outerHeight(), r.centerLeft = Math.round(r.frameWidth * .5), r.centerTop = Math.round(r.frameHeight * .5), r.minHeight = r.naturalHeight, r.minWidth = r.naturalWidth, (r.naturalHeight > r.frameHeight - r.marginReal || r.naturalWidth > r.frameWidth - r.marginReal) && (r = y(r))) }) }, unload: function () { return n(this).each(function () { var t = n(this).data("zoomer"); t && typeof t.$image != "undefined" && t.$image.remove() }) } }; n.fn.zoomer = function (n) { return u[n] ? u[n].apply(this, Array.prototype.slice.call(arguments, 1)) : typeof n == "object" || !n ? g.apply(this, arguments) : this }; n.zoomer = function (n) { n === "defaults" && u.defaults.apply(this, Array.prototype.slice.call(arguments, 1)) } })(jQuery, window);


/*!
* The Final Countdown for jQuery v2.1.0 (http://hilios.github.io/jQuery.countdown/)
* Copyright (c) 2015 Edson Hilios
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
!function (a) { "use strict"; "function" == typeof define && define.amd ? define(["jquery"], a) : a(jQuery) }(function (a) { "use strict"; function b(a) { if (a instanceof Date) return a; if (String(a).match(g)) return String(a).match(/^[0-9]*$/) && (a = Number(a)), String(a).match(/\-/) && (a = String(a).replace(/\-/g, "/")), new Date(a); throw new Error("Couldn't cast `" + a + "` to a date object.") } function c(a) { var b = a.toString().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); return new RegExp(b) } function d(a) { return function (b) { var d = b.match(/%(-|!)?[A-Z]{1}(:[^;]+;)?/gi); if (d) for (var f = 0, g = d.length; g > f; ++f) { var h = d[f].match(/%(-|!)?([a-zA-Z]{1})(:[^;]+;)?/), j = c(h[0]), k = h[1] || "", l = h[3] || "", m = null; h = h[2], i.hasOwnProperty(h) && (m = i[h], m = Number(a[m])), null !== m && ("!" === k && (m = e(l, m)), "" === k && 10 > m && (m = "0" + m.toString()), b = b.replace(j, m.toString())) } return b = b.replace(/%%/, "%") } } function e(a, b) { var c = "s", d = ""; return a && (a = a.replace(/(:|;|\s)/gi, "").split(/\,/), 1 === a.length ? c = a[0] : (d = a[0], c = a[1])), 1 === Math.abs(b) ? d : c } var f = [], g = [], h = { precision: 100, elapse: !1 }; g.push(/^[0-9]*$/.source), g.push(/([0-9]{1,2}\/){2}[0-9]{4}( [0-9]{1,2}(:[0-9]{2}){2})?/.source), g.push(/[0-9]{4}([\/\-][0-9]{1,2}){2}( [0-9]{1,2}(:[0-9]{2}){2})?/.source), g = new RegExp(g.join("|")); var i = { Y: "years", m: "months", n: "daysToMonth", w: "weeks", d: "daysToWeek", D: "totalDays", H: "hours", M: "minutes", S: "seconds" }, j = function (b, c, d) { this.el = b, this.$el = a(b), this.interval = null, this.offset = {}, this.options = a.extend({}, h), this.instanceNumber = f.length, f.push(this), this.$el.data("countdown-instance", this.instanceNumber), d && ("function" == typeof d ? (this.$el.on("update.countdown", d), this.$el.on("stoped.countdown", d), this.$el.on("finish.countdown", d)) : this.options = a.extend({}, h, d)), this.setFinalDate(c), this.start() }; a.extend(j.prototype, { start: function () { null !== this.interval && clearInterval(this.interval); var a = this; this.update(), this.interval = setInterval(function () { a.update.call(a) }, this.options.precision) }, stop: function () { clearInterval(this.interval), this.interval = null, this.dispatchEvent("stoped") }, toggle: function () { this.interval ? this.stop() : this.start() }, pause: function () { this.stop() }, resume: function () { this.start() }, remove: function () { this.stop.call(this), f[this.instanceNumber] = null, delete this.$el.data().countdownInstance }, setFinalDate: function (a) { this.finalDate = b(a) }, update: function () { if (0 === this.$el.closest("html").length) return void this.remove(); var b, c = void 0 !== a._data(this.el, "events"), d = new Date; b = this.finalDate.getTime() - d.getTime(), b = Math.ceil(b / 1e3), b = !this.options.elapse && 0 > b ? 0 : Math.abs(b), this.totalSecsLeft !== b && c && (this.totalSecsLeft = b, this.elapsed = d >= this.finalDate, this.offset = { seconds: this.totalSecsLeft % 60, minutes: Math.floor(this.totalSecsLeft / 60) % 60, hours: Math.floor(this.totalSecsLeft / 60 / 60) % 24, days: Math.floor(this.totalSecsLeft / 60 / 60 / 24) % 7, daysToWeek: Math.floor(this.totalSecsLeft / 60 / 60 / 24) % 7, daysToMonth: Math.floor(this.totalSecsLeft / 60 / 60 / 24 % 30.4368), totalDays: Math.floor(this.totalSecsLeft / 60 / 60 / 24), weeks: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 7), months: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 30.4368), years: Math.abs(this.finalDate.getFullYear() - d.getFullYear()) }, this.options.elapse || 0 !== this.totalSecsLeft ? this.dispatchEvent("update") : (this.stop(), this.dispatchEvent("finish"))) }, dispatchEvent: function (b) { var c = a.Event(b + ".countdown"); c.finalDate = this.finalDate, c.elapsed = this.elapsed, c.offset = a.extend({}, this.offset), c.strftime = d(this.offset), this.$el.trigger(c) } }), a.fn.countdown = function () { var b = Array.prototype.slice.call(arguments, 0); return this.each(function () { var c = a(this).data("countdown-instance"); if (void 0 !== c) { var d = f[c], e = b[0]; j.prototype.hasOwnProperty(e) ? d[e].apply(d, b.slice(1)) : null === String(e).match(/^[$A-Z_][0-9A-Z_$]*$/i) ? (d.setFinalDate.call(d, e), d.start()) : a.error("Method %s does not exist on jQuery.countdown".replace(/\%s/gi, e)) } else new j(this, b[0], b[1]) }) } });


/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var pluses = /\+/g;

    function encode(s) {
        return config.raw ? s : encodeURIComponent(s);
    }

    function decode(s) {
        return config.raw ? s : decodeURIComponent(s);
    }

    function stringifyCookieValue(value) {
        return encode(config.json ? JSON.stringify(value) : String(value));
    }

    function parseCookieValue(s) {
        if (s.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape...
            s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }

        try {
            // Replace server-side written pluses with spaces.
            // If we can't decode the cookie, ignore it, it's unusable.
            // If we can't parse the cookie, ignore it, it's unusable.
            s = decodeURIComponent(s.replace(pluses, ' '));
            return config.json ? JSON.parse(s) : s;
        } catch(e) {}
    }

    function read(s, converter) {
        var value = config.raw ? s : parseCookieValue(s);
        return $.isFunction(converter) ? converter(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // Write

        if (value !== undefined && !$.isFunction(value)) {
            options = $.extend({}, config.defaults, options);

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setTime(+t + days * 864e+5);
            }

            return (document.cookie = [
				encode(key), '=', stringifyCookieValue(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
            ].join(''));
        }

        // Read

        var result = key ? undefined : {};

        // 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 $.cookie().
        var cookies = document.cookie ? document.cookie.split('; ') : [];

        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = parts.join('=');

            if (key && key === name) {
                // If second argument (value) is a function it's a converter...
                result = read(cookie, value);
                break;
            }

            // Prevent storing a cookie that we couldn't decode.
            if (!key && (cookie = read(cookie)) !== undefined) {
                result[name] = cookie;
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) === undefined) {
            return false;
        }

        // Must not alter options, thus extending a fresh object...
        $.cookie(key, '', $.extend({}, options, { expires: -1 }));
        return !$.cookie(key);
    };

}));

/*
 *
 * Copyright (c) 2006-2014 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 1.4.1
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 */
(function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(window.jQuery); } }(function ($) { $.fn.numeric = function (config, callback) { if (typeof config === "boolean") { config = { decimal: config, negative: true, decimalPlaces: -1 } } config = config || {}; if (typeof config.negative == "undefined") { config.negative = true } var decimal = config.decimal === false ? "" : config.decimal || "."; var negative = config.negative === true ? true : false; var decimalPlaces = typeof config.decimalPlaces == "undefined" ? -1 : config.decimalPlaces; callback = typeof callback == "function" ? callback : function () { }; return this.data("numeric.decimal", decimal).data("numeric.negative", negative).data("numeric.callback", callback).data("numeric.decimalPlaces", decimalPlaces).keypress($.fn.numeric.keypress).keyup($.fn.numeric.keyup).blur($.fn.numeric.blur) }; $.fn.numeric.keypress = function (e) { var decimal = $.data(this, "numeric.decimal"); var negative = $.data(this, "numeric.negative"); var decimalPlaces = $.data(this, "numeric.decimalPlaces"); var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; if (key == 13 && this.nodeName.toLowerCase() == "input") { return true } else if (key == 13) { return false } var allow = false; if (e.ctrlKey && key == 97 || e.ctrlKey && key == 65) { return true } if (e.ctrlKey && key == 120 || e.ctrlKey && key == 88) { return true } if (e.ctrlKey && key == 99 || e.ctrlKey && key == 67) { return true } if (e.ctrlKey && key == 122 || e.ctrlKey && key == 90) { return true } if (e.ctrlKey && key == 118 || e.ctrlKey && key == 86 || e.shiftKey && key == 45) { return true } if (key < 48 || key > 57) { var value = $(this).val(); if ($.inArray("-", value.split("")) !== 0 && negative && key == 45 && (value.length === 0 || parseInt($.fn.getSelectionStart(this), 10) === 0)) { return true } if (decimal && key == decimal.charCodeAt(0) && $.inArray(decimal, value.split("")) != -1) { allow = false } if (key != 8 && key != 9 && key != 13 && key != 35 && key != 36 && key != 37 && key != 39 && key != 46) { allow = false } else { if (typeof e.charCode != "undefined") { if (e.keyCode == e.which && e.which !== 0) { allow = true; if (e.which == 46) { allow = false } } else if (e.keyCode !== 0 && e.charCode === 0 && e.which === 0) { allow = true } } } if (decimal && key == decimal.charCodeAt(0)) { if ($.inArray(decimal, value.split("")) == -1) { allow = true } else { allow = false } } } else { allow = true; if (decimal && decimalPlaces > 0) { var dot = $.inArray(decimal, $(this).val().split("")); if (dot >= 0 && $(this).val().length > dot + decimalPlaces) { allow = false } } } return allow }; $.fn.numeric.keyup = function (e) { var val = $(this).val(); if (val && val.length > 0) { var carat = $.fn.getSelectionStart(this); var selectionEnd = $.fn.getSelectionEnd(this); var decimal = $.data(this, "numeric.decimal"); var negative = $.data(this, "numeric.negative"); var decimalPlaces = $.data(this, "numeric.decimalPlaces"); if (decimal !== "" && decimal !== null) { var dot = $.inArray(decimal, val.split("")); if (dot === 0) { this.value = "0" + val; carat++; selectionEnd++ } if (dot == 1 && val.charAt(0) == "-") { this.value = "-0" + val.substring(1); carat++; selectionEnd++ } val = this.value } var validChars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "-", decimal]; var length = val.length; for (var i = length - 1; i >= 0; i--) { var ch = val.charAt(i); if (i !== 0 && ch == "-") { val = val.substring(0, i) + val.substring(i + 1) } else if (i === 0 && !negative && ch == "-") { val = val.substring(1) } var validChar = false; for (var j = 0; j < validChars.length; j++) { if (ch == validChars[j]) { validChar = true; break } } if (!validChar || ch == " ") { val = val.substring(0, i) + val.substring(i + 1) } } var firstDecimal = $.inArray(decimal, val.split("")); if (firstDecimal > 0) { for (var k = length - 1; k > firstDecimal; k--) { var chch = val.charAt(k); if (chch == decimal) { val = val.substring(0, k) + val.substring(k + 1) } } } if (decimal && decimalPlaces > 0) { var dot = $.inArray(decimal, val.split("")); if (dot >= 0) { val = val.substring(0, dot + decimalPlaces + 1); selectionEnd = Math.min(val.length, selectionEnd) } } this.value = val; $.fn.setSelection(this, [carat, selectionEnd]) } }; $.fn.numeric.blur = function () { var decimal = $.data(this, "numeric.decimal"); var callback = $.data(this, "numeric.callback"); var negative = $.data(this, "numeric.negative"); var val = this.value; if (val !== "") { var re = new RegExp("^" + (negative ? "-?" : "") + "\\d+$|^" + (negative ? "-?" : "") + "\\d*" + decimal + "\\d+$"); if (!re.exec(val)) { callback.apply(this) } } }; $.fn.removeNumeric = function () { return this.data("numeric.decimal", null).data("numeric.negative", null).data("numeric.callback", null).data("numeric.decimalPlaces", null).unbind("keypress", $.fn.numeric.keypress).unbind("keyup", $.fn.numeric.keyup).unbind("blur", $.fn.numeric.blur) }; $.fn.getSelectionStart = function (o) { if (o.type === "number") { return undefined } else if (o.createTextRange && document.selection) { var r = document.selection.createRange().duplicate(); r.moveEnd("character", o.value.length); if (r.text == "") return o.value.length; return Math.max(0, o.value.lastIndexOf(r.text)) } else { try { return o.selectionStart } catch (e) { return 0 } } }; $.fn.getSelectionEnd = function (o) { if (o.type === "number") { return undefined } else if (o.createTextRange && document.selection) { var r = document.selection.createRange().duplicate(); r.moveStart("character", -o.value.length); return r.text.length } else return o.selectionEnd }; $.fn.setSelection = function (o, p) { if (typeof p == "number") { p = [p, p] } if (p && p.constructor == Array && p.length == 2) { if (o.type === "number") { o.focus() } else if (o.createTextRange) { var r = o.createTextRange(); r.collapse(true); r.moveStart("character", p[0]); r.moveEnd("character", p[1] - p[0]); r.select() } else { o.focus(); try { if (o.setSelectionRange) { o.setSelectionRange(p[0], p[1]) } } catch (e) { } } } } }));


/*
 * jQuery Autocomplete plugin
 */
; (function ($, $win) {
    'use strict';

    $.fn.uiAutocomplete = function () {
        var termTemplate = '<strong class="ui-autocomplete-term">%s</strong>';

        return this.each(function () {
            var $input = $(this);
            var data = $input.data('autocomplete') || {};
            var uiInstance;

            if (data.highlight) {
                data.open = function (e, ui) {
                    uiInstance.menu.element.find('li').each(function () {
                        var $link = $(this);
                        var regex = new RegExp(uiInstance.term, 'gi');

                        $link.html($link.text().replace(regex, function (matched) {
                            return termTemplate.replace('%s', matched);
                        }));
                    });
                };
            }

            $.Deferred(function (defer) {
                if (data.source) {
                    $.getJSON(data.source)
 					 .done(defer.resolve)
 					 .fail(defer.reject);
                } else defer.resolve();
            }).then(function (source) {
                uiInstance = $input.autocomplete($.extend({}, data, {
                    source: source || data.request
                })).data('ui-autocomplete');
            });
        });
    };
}(jQuery, jQuery(window)));

/*!
 * jQuery UI Core 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/category/ui-core/
 */
!function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : e(jQuery) }(function (e) { function t(t, n) { var s, o, u, r = t.nodeName.toLowerCase(); return "area" === r ? (s = t.parentNode, o = s.name, t.href && o && "map" === s.nodeName.toLowerCase() ? (u = e("img[usemap='#" + o + "']")[0], !!u && i(u)) : !1) : (/^(input|select|textarea|button|object)$/.test(r) ? !t.disabled : "a" === r ? t.href || n : n) && i(t) } function i(t) { return e.expr.filters.visible(t) && !e(t).parents().addBack().filter(function () { return "hidden" === e.css(this, "visibility") }).length } e.ui = e.ui || {}, e.extend(e.ui, { version: "1.11.4", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }), e.fn.extend({ scrollParent: function (t) { var i = this.css("position"), n = "absolute" === i, s = t ? /(auto|scroll|hidden)/ : /(auto|scroll)/, o = this.parents().filter(function () { var t = e(this); return n && "static" === t.css("position") ? !1 : s.test(t.css("overflow") + t.css("overflow-y") + t.css("overflow-x")) }).eq(0); return "fixed" !== i && o.length ? o : e(this[0].ownerDocument || document) }, uniqueId: function () { var e = 0; return function () { return this.each(function () { this.id || (this.id = "ui-id-" + ++e) }) } }(), removeUniqueId: function () { return this.each(function () { /^ui-id-\d+$/.test(this.id) && e(this).removeAttr("id") }) } }), e.extend(e.expr[":"], { data: e.expr.createPseudo ? e.expr.createPseudo(function (t) { return function (i) { return !!e.data(i, t) } }) : function (t, i, n) { return !!e.data(t, n[3]) }, focusable: function (i) { return t(i, !isNaN(e.attr(i, "tabindex"))) }, tabbable: function (i) { var n = e.attr(i, "tabindex"), s = isNaN(n); return (s || n >= 0) && t(i, !s) } }), e("<a>").outerWidth(1).jquery || e.each(["Width", "Height"], function (t, i) { function n(t, i, n, o) { return e.each(s, function () { i -= parseFloat(e.css(t, "padding" + this)) || 0, n && (i -= parseFloat(e.css(t, "border" + this + "Width")) || 0), o && (i -= parseFloat(e.css(t, "margin" + this)) || 0) }), i } var s = "Width" === i ? ["Left", "Right"] : ["Top", "Bottom"], o = i.toLowerCase(), u = { innerWidth: e.fn.innerWidth, innerHeight: e.fn.innerHeight, outerWidth: e.fn.outerWidth, outerHeight: e.fn.outerHeight }; e.fn["inner" + i] = function (t) { return void 0 === t ? u["inner" + i].call(this) : this.each(function () { e(this).css(o, n(this, t) + "px") }) }, e.fn["outer" + i] = function (t, s) { return "number" != typeof t ? u["outer" + i].call(this, t) : this.each(function () { e(this).css(o, n(this, t, !0, s) + "px") }) } }), e.fn.addBack || (e.fn.addBack = function (e) { return this.add(null == e ? this.prevObject : this.prevObject.filter(e)) }), e("<a>").data("a-b", "a").removeData("a-b").data("a-b") && (e.fn.removeData = function (t) { return function (i) { return arguments.length ? t.call(this, e.camelCase(i)) : t.call(this) } }(e.fn.removeData)), e.ui.ie = !!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()), e.fn.extend({ focus: function (t) { return function (i, n) { return "number" == typeof i ? this.each(function () { var t = this; setTimeout(function () { e(t).focus(), n && n.call(t) }, i) }) : t.apply(this, arguments) } }(e.fn.focus), disableSelection: function () { var e = "onselectstart" in document.createElement("div") ? "selectstart" : "mousedown"; return function () { return this.bind(e + ".ui-disableSelection", function (e) { e.preventDefault() }) } }(), enableSelection: function () { return this.unbind(".ui-disableSelection") }, zIndex: function (t) { if (void 0 !== t) return this.css("zIndex", t); if (this.length) for (var i, n, s = e(this[0]) ; s.length && s[0] !== document;) { if (i = s.css("position"), ("absolute" === i || "relative" === i || "fixed" === i) && (n = parseInt(s.css("zIndex"), 10), !isNaN(n) && 0 !== n)) return n; s = s.parent() } return 0 } }), e.ui.plugin = { add: function (t, i, n) { var s, o = e.ui[t].prototype; for (s in n) o.plugins[s] = o.plugins[s] || [], o.plugins[s].push([i, n[s]]) }, call: function (e, t, i, n) { var s, o = e.plugins[t]; if (o && (n || e.element[0].parentNode && 11 !== e.element[0].parentNode.nodeType)) for (s = 0; s < o.length; s++) e.options[o[s][0]] && o[s][1].apply(e.element, i) } } });

/*!
 * jQuery UI Widget 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/jQuery.widget/
 */
!function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : e(jQuery) }(function (e) { var t = 0, i = Array.prototype.slice; e.cleanData = function (t) { return function (i) { var n, s, a; for (a = 0; null != (s = i[a]) ; a++) try { n = e._data(s, "events"), n && n.remove && e(s).triggerHandler("remove") } catch (o) { } t(i) } }(e.cleanData), e.widget = function (t, i, n) { var s, a, o, r, u = {}, l = t.split(".")[0]; return t = t.split(".")[1], s = l + "-" + t, n || (n = i, i = e.Widget), e.expr[":"][s.toLowerCase()] = function (t) { return !!e.data(t, s) }, e[l] = e[l] || {}, a = e[l][t], o = e[l][t] = function (e, t) { return this._createWidget ? void (arguments.length && this._createWidget(e, t)) : new o(e, t) }, e.extend(o, a, { version: n.version, _proto: e.extend({}, n), _childConstructors: [] }), r = new i, r.options = e.widget.extend({}, r.options), e.each(n, function (t, n) { return e.isFunction(n) ? void (u[t] = function () { var e = function () { return i.prototype[t].apply(this, arguments) }, s = function (e) { return i.prototype[t].apply(this, e) }; return function () { var t, i = this._super, a = this._superApply; return this._super = e, this._superApply = s, t = n.apply(this, arguments), this._super = i, this._superApply = a, t } }()) : void (u[t] = n) }), o.prototype = e.widget.extend(r, { widgetEventPrefix: a ? r.widgetEventPrefix || t : t }, u, { constructor: o, namespace: l, widgetName: t, widgetFullName: s }), a ? (e.each(a._childConstructors, function (t, i) { var n = i.prototype; e.widget(n.namespace + "." + n.widgetName, o, i._proto) }), delete a._childConstructors) : i._childConstructors.push(o), e.widget.bridge(t, o), o }, e.widget.extend = function (t) { for (var n, s, a = i.call(arguments, 1), o = 0, r = a.length; r > o; o++) for (n in a[o]) s = a[o][n], a[o].hasOwnProperty(n) && void 0 !== s && (t[n] = e.isPlainObject(s) ? e.isPlainObject(t[n]) ? e.widget.extend({}, t[n], s) : e.widget.extend({}, s) : s); return t }, e.widget.bridge = function (t, n) { var s = n.prototype.widgetFullName || t; e.fn[t] = function (a) { var o = "string" == typeof a, r = i.call(arguments, 1), u = this; return o ? this.each(function () { var i, n = e.data(this, s); return "instance" === a ? (u = n, !1) : n ? e.isFunction(n[a]) && "_" !== a.charAt(0) ? (i = n[a].apply(n, r), i !== n && void 0 !== i ? (u = i && i.jquery ? u.pushStack(i.get()) : i, !1) : void 0) : e.error("no such method '" + a + "' for " + t + " widget instance") : e.error("cannot call methods on " + t + " prior to initialization; attempted to call method '" + a + "'") }) : (r.length && (a = e.widget.extend.apply(null, [a].concat(r))), this.each(function () { var t = e.data(this, s); t ? (t.option(a || {}), t._init && t._init()) : e.data(this, s, new n(a, this)) })), u } }, e.Widget = function () { }, e.Widget._childConstructors = [], e.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: !1, create: null }, _createWidget: function (i, n) { n = e(n || this.defaultElement || this)[0], this.element = e(n), this.uuid = t++, this.eventNamespace = "." + this.widgetName + this.uuid, this.bindings = e(), this.hoverable = e(), this.focusable = e(), n !== this && (e.data(n, this.widgetFullName, this), this._on(!0, this.element, { remove: function (e) { e.target === n && this.destroy() } }), this.document = e(n.style ? n.ownerDocument : n.document || n), this.window = e(this.document[0].defaultView || this.document[0].parentWindow)), this.options = e.widget.extend({}, this.options, this._getCreateOptions(), i), this._create(), this._trigger("create", null, this._getCreateEventData()), this._init() }, _getCreateOptions: e.noop, _getCreateEventData: e.noop, _create: e.noop, _init: e.noop, destroy: function () { this._destroy(), this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)), this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName + "-disabled ui-state-disabled"), this.bindings.unbind(this.eventNamespace), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus") }, _destroy: e.noop, widget: function () { return this.element }, option: function (t, i) { var n, s, a, o = t; if (0 === arguments.length) return e.widget.extend({}, this.options); if ("string" == typeof t) if (o = {}, n = t.split("."), t = n.shift(), n.length) { for (s = o[t] = e.widget.extend({}, this.options[t]), a = 0; a < n.length - 1; a++) s[n[a]] = s[n[a]] || {}, s = s[n[a]]; if (t = n.pop(), 1 === arguments.length) return void 0 === s[t] ? null : s[t]; s[t] = i } else { if (1 === arguments.length) return void 0 === this.options[t] ? null : this.options[t]; o[t] = i } return this._setOptions(o), this }, _setOptions: function (e) { var t; for (t in e) this._setOption(t, e[t]); return this }, _setOption: function (e, t) { return this.options[e] = t, "disabled" === e && (this.widget().toggleClass(this.widgetFullName + "-disabled", !!t), t && (this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus"))), this }, enable: function () { return this._setOptions({ disabled: !1 }) }, disable: function () { return this._setOptions({ disabled: !0 }) }, _on: function (t, i, n) { var s, a = this; "boolean" != typeof t && (n = i, i = t, t = !1), n ? (i = s = e(i), this.bindings = this.bindings.add(i)) : (n = i, i = this.element, s = this.widget()), e.each(n, function (n, o) { function r() { return t || a.options.disabled !== !0 && !e(this).hasClass("ui-state-disabled") ? ("string" == typeof o ? a[o] : o).apply(a, arguments) : void 0 } "string" != typeof o && (r.guid = o.guid = o.guid || r.guid || e.guid++); var u = n.match(/^([\w:-]*)\s*(.*)$/), l = u[1] + a.eventNamespace, h = u[2]; h ? s.delegate(h, l, r) : i.bind(l, r) }) }, _off: function (t, i) { i = (i || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace, t.unbind(i).undelegate(i), this.bindings = e(this.bindings.not(t).get()), this.focusable = e(this.focusable.not(t).get()), this.hoverable = e(this.hoverable.not(t).get()) }, _delay: function (e, t) { function i() { return ("string" == typeof e ? n[e] : e).apply(n, arguments) } var n = this; return setTimeout(i, t || 0) }, _hoverable: function (t) { this.hoverable = this.hoverable.add(t), this._on(t, { mouseenter: function (t) { e(t.currentTarget).addClass("ui-state-hover") }, mouseleave: function (t) { e(t.currentTarget).removeClass("ui-state-hover") } }) }, _focusable: function (t) { this.focusable = this.focusable.add(t), this._on(t, { focusin: function (t) { e(t.currentTarget).addClass("ui-state-focus") }, focusout: function (t) { e(t.currentTarget).removeClass("ui-state-focus") } }) }, _trigger: function (t, i, n) { var s, a, o = this.options[t]; if (n = n || {}, i = e.Event(i), i.type = (t === this.widgetEventPrefix ? t : this.widgetEventPrefix + t).toLowerCase(), i.target = this.element[0], a = i.originalEvent) for (s in a) s in i || (i[s] = a[s]); return this.element.trigger(i, n), !(e.isFunction(o) && o.apply(this.element[0], [i].concat(n)) === !1 || i.isDefaultPrevented()) } }, e.each({ show: "fadeIn", hide: "fadeOut" }, function (t, i) { e.Widget.prototype["_" + t] = function (n, s, a) { "string" == typeof s && (s = { effect: s }); var o, r = s ? s === !0 || "number" == typeof s ? i : s.effect || i : t; s = s || {}, "number" == typeof s && (s = { duration: s }), o = !e.isEmptyObject(s), s.complete = a, s.delay && n.delay(s.delay), o && e.effects && e.effects.effect[r] ? n[t](s) : r !== t && n[r] ? n[r](s.duration, s.easing, a) : n.queue(function (i) { e(this)[t](), a && a.call(n[0]), i() }) } }); e.widget });

/*!
 * jQuery UI Position 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */
!function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : e(jQuery) }(function (e) { !function () { function t(e, t, i) { return [parseFloat(e[0]) * (m.test(e[0]) ? t / 100 : 1), parseFloat(e[1]) * (m.test(e[1]) ? i / 100 : 1)] } function i(t, i) { return parseInt(e.css(t, i), 10) || 0 } function s(t) { var i = t[0]; return 9 === i.nodeType ? { width: t.width(), height: t.height(), offset: { top: 0, left: 0 } } : e.isWindow(i) ? { width: t.width(), height: t.height(), offset: { top: t.scrollTop(), left: t.scrollLeft() } } : i.preventDefault ? { width: 0, height: 0, offset: { top: i.pageY, left: i.pageX } } : { width: t.outerWidth(), height: t.outerHeight(), offset: t.offset() } } e.ui = e.ui || {}; var n, a, o = Math.max, r = Math.abs, u = Math.round, l = /left|center|right/, h = /top|center|bottom/, c = /[\+\-]\d+(\.[\d]+)?%?/, d = /^\w+/, m = /%$/, p = e.fn.position; e.position = { scrollbarWidth: function () { if (void 0 !== n) return n; var t, i, s = e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"), a = s.children()[0]; return e("body").append(s), t = a.offsetWidth, s.css("overflow", "scroll"), i = a.offsetWidth, t === i && (i = s[0].clientWidth), s.remove(), n = t - i }, getScrollInfo: function (t) { var i = t.isWindow || t.isDocument ? "" : t.element.css("overflow-x"), s = t.isWindow || t.isDocument ? "" : t.element.css("overflow-y"), n = "scroll" === i || "auto" === i && t.width < t.element[0].scrollWidth, a = "scroll" === s || "auto" === s && t.height < t.element[0].scrollHeight; return { width: a ? e.position.scrollbarWidth() : 0, height: n ? e.position.scrollbarWidth() : 0 } }, getWithinInfo: function (t) { var i = e(t || window), s = e.isWindow(i[0]), n = !!i[0] && 9 === i[0].nodeType; return { element: i, isWindow: s, isDocument: n, offset: i.offset() || { left: 0, top: 0 }, scrollLeft: i.scrollLeft(), scrollTop: i.scrollTop(), width: s || n ? i.width() : i.outerWidth(), height: s || n ? i.height() : i.outerHeight() } } }, e.fn.position = function (n) { if (!n || !n.of) return p.apply(this, arguments); n = e.extend({}, n); var m, f, v, g, _, y, b = e(n.of), k = e.position.getWithinInfo(n.within), D = e.position.getScrollInfo(k), x = (n.collision || "flip").split(" "), w = {}; return y = s(b), b[0].preventDefault && (n.at = "left top"), f = y.width, v = y.height, g = y.offset, _ = e.extend({}, g), e.each(["my", "at"], function () { var e, t, i = (n[this] || "").split(" "); 1 === i.length && (i = l.test(i[0]) ? i.concat(["center"]) : h.test(i[0]) ? ["center"].concat(i) : ["center", "center"]), i[0] = l.test(i[0]) ? i[0] : "center", i[1] = h.test(i[1]) ? i[1] : "center", e = c.exec(i[0]), t = c.exec(i[1]), w[this] = [e ? e[0] : 0, t ? t[0] : 0], n[this] = [d.exec(i[0])[0], d.exec(i[1])[0]] }), 1 === x.length && (x[1] = x[0]), "right" === n.at[0] ? _.left += f : "center" === n.at[0] && (_.left += f / 2), "bottom" === n.at[1] ? _.top += v : "center" === n.at[1] && (_.top += v / 2), m = t(w.at, f, v), _.left += m[0], _.top += m[1], this.each(function () { var s, l, h = e(this), c = h.outerWidth(), d = h.outerHeight(), p = i(this, "marginLeft"), y = i(this, "marginTop"), M = c + p + i(this, "marginRight") + D.width, T = d + y + i(this, "marginBottom") + D.height, C = e.extend({}, _), I = t(w.my, h.outerWidth(), h.outerHeight()); "right" === n.my[0] ? C.left -= c : "center" === n.my[0] && (C.left -= c / 2), "bottom" === n.my[1] ? C.top -= d : "center" === n.my[1] && (C.top -= d / 2), C.left += I[0], C.top += I[1], a || (C.left = u(C.left), C.top = u(C.top)), s = { marginLeft: p, marginTop: y }, e.each(["left", "top"], function (t, i) { e.ui.position[x[t]] && e.ui.position[x[t]][i](C, { targetWidth: f, targetHeight: v, elemWidth: c, elemHeight: d, collisionPosition: s, collisionWidth: M, collisionHeight: T, offset: [m[0] + I[0], m[1] + I[1]], my: n.my, at: n.at, within: k, elem: h }) }), n.using && (l = function (e) { var t = g.left - C.left, i = t + f - c, s = g.top - C.top, a = s + v - d, u = { target: { element: b, left: g.left, top: g.top, width: f, height: v }, element: { element: h, left: C.left, top: C.top, width: c, height: d }, horizontal: 0 > i ? "left" : t > 0 ? "right" : "center", vertical: 0 > a ? "top" : s > 0 ? "bottom" : "middle" }; c > f && r(t + i) < f && (u.horizontal = "center"), d > v && r(s + a) < v && (u.vertical = "middle"), u.important = o(r(t), r(i)) > o(r(s), r(a)) ? "horizontal" : "vertical", n.using.call(this, e, u) }), h.offset(e.extend(C, { using: l })) }) }, e.ui.position = { fit: { left: function (e, t) { var i, s = t.within, n = s.isWindow ? s.scrollLeft : s.offset.left, a = s.width, r = e.left - t.collisionPosition.marginLeft, u = n - r, l = r + t.collisionWidth - a - n; t.collisionWidth > a ? u > 0 && 0 >= l ? (i = e.left + u + t.collisionWidth - a - n, e.left += u - i) : e.left = l > 0 && 0 >= u ? n : u > l ? n + a - t.collisionWidth : n : u > 0 ? e.left += u : l > 0 ? e.left -= l : e.left = o(e.left - r, e.left) }, top: function (e, t) { var i, s = t.within, n = s.isWindow ? s.scrollTop : s.offset.top, a = t.within.height, r = e.top - t.collisionPosition.marginTop, u = n - r, l = r + t.collisionHeight - a - n; t.collisionHeight > a ? u > 0 && 0 >= l ? (i = e.top + u + t.collisionHeight - a - n, e.top += u - i) : e.top = l > 0 && 0 >= u ? n : u > l ? n + a - t.collisionHeight : n : u > 0 ? e.top += u : l > 0 ? e.top -= l : e.top = o(e.top - r, e.top) } }, flip: { left: function (e, t) { var i, s, n = t.within, a = n.offset.left + n.scrollLeft, o = n.width, u = n.isWindow ? n.scrollLeft : n.offset.left, l = e.left - t.collisionPosition.marginLeft, h = l - u, c = l + t.collisionWidth - o - u, d = "left" === t.my[0] ? -t.elemWidth : "right" === t.my[0] ? t.elemWidth : 0, m = "left" === t.at[0] ? t.targetWidth : "right" === t.at[0] ? -t.targetWidth : 0, p = -2 * t.offset[0]; 0 > h ? (i = e.left + d + m + p + t.collisionWidth - o - a, (0 > i || i < r(h)) && (e.left += d + m + p)) : c > 0 && (s = e.left - t.collisionPosition.marginLeft + d + m + p - u, (s > 0 || r(s) < c) && (e.left += d + m + p)) }, top: function (e, t) { var i, s, n = t.within, a = n.offset.top + n.scrollTop, o = n.height, u = n.isWindow ? n.scrollTop : n.offset.top, l = e.top - t.collisionPosition.marginTop, h = l - u, c = l + t.collisionHeight - o - u, d = "top" === t.my[1], m = d ? -t.elemHeight : "bottom" === t.my[1] ? t.elemHeight : 0, p = "top" === t.at[1] ? t.targetHeight : "bottom" === t.at[1] ? -t.targetHeight : 0, f = -2 * t.offset[1]; 0 > h ? (s = e.top + m + p + f + t.collisionHeight - o - a, (0 > s || s < r(h)) && (e.top += m + p + f)) : c > 0 && (i = e.top - t.collisionPosition.marginTop + m + p + f - u, (i > 0 || r(i) < c) && (e.top += m + p + f)) } }, flipfit: { left: function () { e.ui.position.flip.left.apply(this, arguments), e.ui.position.fit.left.apply(this, arguments) }, top: function () { e.ui.position.flip.top.apply(this, arguments), e.ui.position.fit.top.apply(this, arguments) } } }, function () { var t, i, s, n, o, r = document.getElementsByTagName("body")[0], u = document.createElement("div"); t = document.createElement(r ? "div" : "body"), s = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }, r && e.extend(s, { position: "absolute", left: "-1000px", top: "-1000px" }); for (o in s) t.style[o] = s[o]; t.appendChild(u), i = r || document.documentElement, i.insertBefore(t, i.firstChild), u.style.cssText = "position: absolute; left: 10.7432222px;", n = e(u).offset().left, a = n > 10 && 11 > n, t.innerHTML = "", i.removeChild(t) }() }(); e.ui.position });

/*!
 * jQuery UI Autocomplete 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/autocomplete/
 */
!function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : e(jQuery) }(function (e) { e.widget("ui.autocomplete", { version: "1.11.4", defaultElement: "<input>", options: { appendTo: null, autoFocus: !1, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, requestIndex: 0, pending: 0, _create: function () { var t, i, s, n = this.element[0].nodeName.toLowerCase(), o = "textarea" === n, u = "input" === n; this.isMultiLine = o ? !0 : u ? !1 : this.element.prop("isContentEditable"), this.valueMethod = this.element[o || u ? "val" : "text"], this.isNewMenu = !0, this.element.addClass("ui-autocomplete-input").attr("autocomplete", "off"), this._on(this.element, { keydown: function (n) { if (this.element.prop("readOnly")) return t = !0, s = !0, void (i = !0); t = !1, s = !1, i = !1; var o = e.ui.keyCode; switch (n.keyCode) { case o.PAGE_UP: t = !0, this._move("previousPage", n); break; case o.PAGE_DOWN: t = !0, this._move("nextPage", n); break; case o.UP: t = !0, this._keyEvent("previous", n); break; case o.DOWN: t = !0, this._keyEvent("next", n); break; case o.ENTER: this.menu.active && (t = !0, n.preventDefault(), this.menu.select(n)); break; case o.TAB: this.menu.active && this.menu.select(n); break; case o.ESCAPE: this.menu.element.is(":visible") && (this.isMultiLine || this._value(this.term), this.close(n), n.preventDefault()); break; default: i = !0, this._searchTimeout(n) } }, keypress: function (s) { if (t) return t = !1, void ((!this.isMultiLine || this.menu.element.is(":visible")) && s.preventDefault()); if (!i) { var n = e.ui.keyCode; switch (s.keyCode) { case n.PAGE_UP: this._move("previousPage", s); break; case n.PAGE_DOWN: this._move("nextPage", s); break; case n.UP: this._keyEvent("previous", s); break; case n.DOWN: this._keyEvent("next", s) } } }, input: function (e) { return s ? (s = !1, void e.preventDefault()) : void this._searchTimeout(e) }, focus: function () { this.selectedItem = null, this.previous = this._value() }, blur: function (e) { return this.cancelBlur ? void delete this.cancelBlur : (clearTimeout(this.searching), this.close(e), void this._change(e)) } }), this._initSource(), this.menu = e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({ role: null }).hide().menu("instance"), this._on(this.menu.element, { mousedown: function (t) { t.preventDefault(), this.cancelBlur = !0, this._delay(function () { delete this.cancelBlur }); var i = this.menu.element[0]; e(t.target).closest(".ui-menu-item").length || this._delay(function () { var t = this; this.document.one("mousedown", function (s) { s.target === t.element[0] || s.target === i || e.contains(i, s.target) || t.close() }) }) }, menufocus: function (t, i) { var s, n; return this.isNewMenu && (this.isNewMenu = !1, t.originalEvent && /^mouse/.test(t.originalEvent.type)) ? (this.menu.blur(), void this.document.one("mousemove", function () { e(t.target).trigger(t.originalEvent) })) : (n = i.item.data("ui-autocomplete-item"), !1 !== this._trigger("focus", t, { item: n }) && t.originalEvent && /^key/.test(t.originalEvent.type) && this._value(n.value), s = i.item.attr("aria-label") || n.value, void (s && e.trim(s).length && (this.liveRegion.children().hide(), e("<div>").text(s).appendTo(this.liveRegion)))) }, menuselect: function (e, t) { var i = t.item.data("ui-autocomplete-item"), s = this.previous; this.element[0] !== this.document[0].activeElement && (this.element.focus(), this.previous = s, this._delay(function () { this.previous = s, this.selectedItem = i })), !1 !== this._trigger("select", e, { item: i }) && this._value(i.value), this.term = this._value(), this.close(e), this.selectedItem = i } }), this.liveRegion = e("<span>", { role: "status", "aria-live": "assertive", "aria-relevant": "additions" }).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body), this._on(this.window, { beforeunload: function () { this.element.removeAttr("autocomplete") } }) }, _destroy: function () { clearTimeout(this.searching), this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"), this.menu.element.remove(), this.liveRegion.remove() }, _setOption: function (e, t) { this._super(e, t), "source" === e && this._initSource(), "appendTo" === e && this.menu.element.appendTo(this._appendTo()), "disabled" === e && t && this.xhr && this.xhr.abort() }, _appendTo: function () { var t = this.options.appendTo; return t && (t = t.jquery || t.nodeType ? e(t) : this.document.find(t).eq(0)), t && t[0] || (t = this.element.closest(".ui-front")), t.length || (t = this.document[0].body), t }, _initSource: function () { var t, i, s = this; e.isArray(this.options.source) ? (t = this.options.source, this.source = function (i, s) { s(e.ui.autocomplete.filter(t, i.term)) }) : "string" == typeof this.options.source ? (i = this.options.source, this.source = function (t, n) { s.xhr && s.xhr.abort(), s.xhr = e.ajax({ url: i, data: t, dataType: "json", success: function (e) { n(e) }, error: function () { n([]) } }) }) : this.source = this.options.source }, _searchTimeout: function (e) { clearTimeout(this.searching), this.searching = this._delay(function () { var t = this.term === this._value(), i = this.menu.element.is(":visible"), s = e.altKey || e.ctrlKey || e.metaKey || e.shiftKey; (!t || t && !i && !s) && (this.selectedItem = null, this.search(null, e)) }, this.options.delay) }, search: function (e, t) { return e = null != e ? e : this._value(), this.term = this._value(), e.length < this.options.minLength ? this.close(t) : this._trigger("search", t) !== !1 ? this._search(e) : void 0 }, _search: function (e) { this.pending++, this.element.addClass("ui-autocomplete-loading"), this.cancelSearch = !1, this.source({ term: e }, this._response()) }, _response: function () { var t = ++this.requestIndex; return e.proxy(function (e) { t === this.requestIndex && this.__response(e), this.pending--, this.pending || this.element.removeClass("ui-autocomplete-loading") }, this) }, __response: function (e) { e && (e = this._normalize(e)), this._trigger("response", null, { content: e }), !this.options.disabled && e && e.length && !this.cancelSearch ? (this._suggest(e), this._trigger("open")) : this._close() }, close: function (e) { this.cancelSearch = !0, this._close(e) }, _close: function (e) { this.menu.element.is(":visible") && (this.menu.element.hide(), this.menu.blur(), this.isNewMenu = !0, this._trigger("close", e)) }, _change: function (e) { this.previous !== this._value() && this._trigger("change", e, { item: this.selectedItem }) }, _normalize: function (t) { return t.length && t[0].label && t[0].value ? t : e.map(t, function (t) { return "string" == typeof t ? { label: t, value: t } : e.extend({}, t, { label: t.label || t.value, value: t.value || t.label }) }) }, _suggest: function (t) { var i = this.menu.element.empty(); this._renderMenu(i, t), this.isNewMenu = !0, this.menu.refresh(), i.show(), this._resizeMenu(), i.position(e.extend({ of: this.element }, this.options.position)), this.options.autoFocus && this.menu.next() }, _resizeMenu: function () { var e = this.menu.element; e.outerWidth(Math.max(e.width("").outerWidth() + 1, this.element.outerWidth())) }, _renderMenu: function (t, i) { var s = this; e.each(i, function (e, i) { s._renderItemData(t, i) }) }, _renderItemData: function (e, t) { return this._renderItem(e, t).data("ui-autocomplete-item", t) }, _renderItem: function (t, i) { return e("<li>").text(i.label).appendTo(t) }, _move: function (e, t) { return this.menu.element.is(":visible") ? this.menu.isFirstItem() && /^previous/.test(e) || this.menu.isLastItem() && /^next/.test(e) ? (this.isMultiLine || this._value(this.term), void this.menu.blur()) : void this.menu[e](t) : void this.search(null, t) }, widget: function () { return this.menu.element }, _value: function () { return this.valueMethod.apply(this.element, arguments) }, _keyEvent: function (e, t) { (!this.isMultiLine || this.menu.element.is(":visible")) && (this._move(e, t), t.preventDefault()) } }), e.extend(e.ui.autocomplete, { escapeRegex: function (e) { return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") }, filter: function (t, i) { var s = RegExp(e.ui.autocomplete.escapeRegex(i), "i"); return e.grep(t, function (e) { return s.test(e.label || e.value || e) }) } }), e.widget("ui.autocomplete", e.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function (e) { return e + (e > 1 ? " results are" : " result is") + " available, use up and down arrow keys to navigate." } } }, __response: function (t) { var i; this._superApply(arguments), this.options.disabled || this.cancelSearch || (i = t && t.length ? this.options.messages.results(t.length) : this.options.messages.noResults, this.liveRegion.children().hide(), e("<div>").text(i).appendTo(this.liveRegion)) } }); e.ui.autocomplete });

/*!
 * jQuery UI Menu 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/menu/
 */
!function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : e(jQuery) }(function (e) { e.widget("ui.menu", { version: "1.11.4", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, items: "> *", menus: "ul", position: { my: "left-1 top", at: "right top" }, role: "menu", blur: null, focus: null, select: null }, _create: function () { this.activeMenu = this.element, this.mouseHandled = !1, this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons", !!this.element.find(".ui-icon").length).attr({ role: this.options.role, tabIndex: 0 }), this.options.disabled && this.element.addClass("ui-state-disabled").attr("aria-disabled", "true"), this._on({ "mousedown .ui-menu-item": function (e) { e.preventDefault() }, "click .ui-menu-item": function (t) { var i = e(t.target); !this.mouseHandled && i.not(".ui-state-disabled").length && (this.select(t), t.isPropagationStopped() || (this.mouseHandled = !0), i.has(".ui-menu").length ? this.expand(t) : !this.element.is(":focus") && e(this.document[0].activeElement).closest(".ui-menu").length && (this.element.trigger("focus", [!0]), this.active && 1 === this.active.parents(".ui-menu").length && clearTimeout(this.timer))) }, "mouseenter .ui-menu-item": function (t) { if (!this.previousFilter) { var i = e(t.currentTarget); i.siblings(".ui-state-active").removeClass("ui-state-active"), this.focus(t, i) } }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function (e, t) { var i = this.active || this.element.find(this.options.items).eq(0); t || this.focus(e, i) }, blur: function (t) { this._delay(function () { e.contains(this.element[0], this.document[0].activeElement) || this.collapseAll(t) }) }, keydown: "_keydown" }), this.refresh(), this._on(this.document, { click: function (e) { this._closeOnDocumentClick(e) && this.collapseAll(e), this.mouseHandled = !1 } }) }, _destroy: function () { this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(), this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function () { var t = e(this); t.data("ui-menu-submenu-carat") && t.remove() }), this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content") }, _keydown: function (t) { var i, s, n, a, o = !0; switch (t.keyCode) { case e.ui.keyCode.PAGE_UP: this.previousPage(t); break; case e.ui.keyCode.PAGE_DOWN: this.nextPage(t); break; case e.ui.keyCode.HOME: this._move("first", "first", t); break; case e.ui.keyCode.END: this._move("last", "last", t); break; case e.ui.keyCode.UP: this.previous(t); break; case e.ui.keyCode.DOWN: this.next(t); break; case e.ui.keyCode.LEFT: this.collapse(t); break; case e.ui.keyCode.RIGHT: this.active && !this.active.is(".ui-state-disabled") && this.expand(t); break; case e.ui.keyCode.ENTER: case e.ui.keyCode.SPACE: this._activate(t); break; case e.ui.keyCode.ESCAPE: this.collapse(t); break; default: o = !1, s = this.previousFilter || "", n = String.fromCharCode(t.keyCode), a = !1, clearTimeout(this.filterTimer), n === s ? a = !0 : n = s + n, i = this._filterMenuItems(n), i = a && -1 !== i.index(this.active.next()) ? this.active.nextAll(".ui-menu-item") : i, i.length || (n = String.fromCharCode(t.keyCode), i = this._filterMenuItems(n)), i.length ? (this.focus(t, i), this.previousFilter = n, this.filterTimer = this._delay(function () { delete this.previousFilter }, 1e3)) : delete this.previousFilter } o && t.preventDefault() }, _activate: function (e) { this.active.is(".ui-state-disabled") || (this.active.is("[aria-haspopup='true']") ? this.expand(e) : this.select(e)) }, refresh: function () { var t, i, s = this, n = this.options.icons.submenu, a = this.element.find(this.options.menus); this.element.toggleClass("ui-menu-icons", !!this.element.find(".ui-icon").length), a.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({ role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" }).each(function () { var t = e(this), i = t.parent(), s = e("<span>").addClass("ui-menu-icon ui-icon " + n).data("ui-menu-submenu-carat", !0); i.attr("aria-haspopup", "true").prepend(s), t.attr("aria-labelledby", i.attr("id")) }), t = a.add(this.element), i = t.find(this.options.items), i.not(".ui-menu-item").each(function () { var t = e(this); s._isDivider(t) && t.addClass("ui-widget-content ui-menu-divider") }), i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({ tabIndex: -1, role: this._itemRole() }), i.filter(".ui-state-disabled").attr("aria-disabled", "true"), this.active && !e.contains(this.element[0], this.active[0]) && this.blur() }, _itemRole: function () { return { menu: "menuitem", listbox: "option" }[this.options.role] }, _setOption: function (e, t) { "icons" === e && this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu), "disabled" === e && this.element.toggleClass("ui-state-disabled", !!t).attr("aria-disabled", t), this._super(e, t) }, focus: function (e, t) { var i, s; this.blur(e, e && "focus" === e.type), this._scrollIntoView(t), this.active = t.first(), s = this.active.addClass("ui-state-focus").removeClass("ui-state-active"), this.options.role && this.element.attr("aria-activedescendant", s.attr("id")), this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"), e && "keydown" === e.type ? this._close() : this.timer = this._delay(function () { this._close() }, this.delay), i = t.children(".ui-menu"), i.length && e && /^mouse/.test(e.type) && this._startOpening(i), this.activeMenu = t.parent(), this._trigger("focus", e, { item: t }) }, _scrollIntoView: function (t) { var i, s, n, a, o, r; this._hasScroll() && (i = parseFloat(e.css(this.activeMenu[0], "borderTopWidth")) || 0, s = parseFloat(e.css(this.activeMenu[0], "paddingTop")) || 0, n = t.offset().top - this.activeMenu.offset().top - i - s, a = this.activeMenu.scrollTop(), o = this.activeMenu.height(), r = t.outerHeight(), 0 > n ? this.activeMenu.scrollTop(a + n) : n + r > o && this.activeMenu.scrollTop(a + n - o + r)) }, blur: function (e, t) { t || clearTimeout(this.timer), this.active && (this.active.removeClass("ui-state-focus"), this.active = null, this._trigger("blur", e, { item: this.active })) }, _startOpening: function (e) { clearTimeout(this.timer), "true" === e.attr("aria-hidden") && (this.timer = this._delay(function () { this._close(), this._open(e) }, this.delay)) }, _open: function (t) { var i = e.extend({ of: this.active }, this.options.position); clearTimeout(this.timer), this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden", "true"), t.show().removeAttr("aria-hidden").attr("aria-expanded", "true").position(i) }, collapseAll: function (t, i) { clearTimeout(this.timer), this.timer = this._delay(function () { var s = i ? this.element : e(t && t.target).closest(this.element.find(".ui-menu")); s.length || (s = this.element), this._close(s), this.blur(t), this.activeMenu = s }, this.delay) }, _close: function (e) { e || (e = this.active ? this.active.parent() : this.element), e.find(".ui-menu").hide().attr("aria-hidden", "true").attr("aria-expanded", "false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active") }, _closeOnDocumentClick: function (t) { return !e(t.target).closest(".ui-menu").length }, _isDivider: function (e) { return !/[^\-\u2014\u2013\s]/.test(e.text()) }, collapse: function (e) { var t = this.active && this.active.parent().closest(".ui-menu-item", this.element); t && t.length && (this._close(), this.focus(e, t)) }, expand: function (e) { var t = this.active && this.active.children(".ui-menu ").find(this.options.items).first(); t && t.length && (this._open(t.parent()), this._delay(function () { this.focus(e, t) })) }, next: function (e) { this._move("next", "first", e) }, previous: function (e) { this._move("prev", "last", e) }, isFirstItem: function () { return this.active && !this.active.prevAll(".ui-menu-item").length }, isLastItem: function () { return this.active && !this.active.nextAll(".ui-menu-item").length }, _move: function (e, t, i) { var s; this.active && (s = "first" === e || "last" === e ? this.active["first" === e ? "prevAll" : "nextAll"](".ui-menu-item").eq(-1) : this.active[e + "All"](".ui-menu-item").eq(0)), s && s.length && this.active || (s = this.activeMenu.find(this.options.items)[t]()), this.focus(i, s) }, nextPage: function (t) { var i, s, n; return this.active ? void (this.isLastItem() || (this._hasScroll() ? (s = this.active.offset().top, n = this.element.height(), this.active.nextAll(".ui-menu-item").each(function () { return i = e(this), i.offset().top - s - n < 0 }), this.focus(t, i)) : this.focus(t, this.activeMenu.find(this.options.items)[this.active ? "last" : "first"]()))) : void this.next(t) }, previousPage: function (t) { var i, s, n; return this.active ? void (this.isFirstItem() || (this._hasScroll() ? (s = this.active.offset().top, n = this.element.height(), this.active.prevAll(".ui-menu-item").each(function () { return i = e(this), i.offset().top - s + n > 0 }), this.focus(t, i)) : this.focus(t, this.activeMenu.find(this.options.items).first()))) : void this.next(t) }, _hasScroll: function () { return this.element.outerHeight() < this.element.prop("scrollHeight") }, select: function (t) { this.active = this.active || e(t.target).closest(".ui-menu-item"); var i = { item: this.active }; this.active.has(".ui-menu").length || this.collapseAll(t, !0), this._trigger("select", t, i) }, _filterMenuItems: function (t) { var i = t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"), s = RegExp("^" + i, "i"); return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function () { return s.test(e.trim(e(this).text())) }) } }) });
;
// page init
jQuery(function() {
    initValidation();
});
var subscriptionEmail = null;
var impressionScript;
var productDataArray;
var positionArray;
$(document).ready(function () {
    subscriptionEmail = null;
    $("#nav .category-nav > li > a").on("click", function() {
        $('html, body').scrollTop(0,0);
        $('html, body').scrollTop(0,0);
    });

    $(".btnPostalCodeRIS").on("click", function () {        
        BootstrapDialog.show({
            cssClass: 'postalCodePopUp',
            message: $('<div></div>').load(globalConstants.rootUrl + "/ShoppingCart/StoreLookUp"),
            type: BootstrapDialog.defaultMessage
        });

    });

    $("#btnOpenHpos").on("click", function () {
        var sposSKU = $('#productSku').val();
        if (sposSKU == undefined || sposSKU == null || sposSKU.length<=0) {          
            $('#skuRequiredMessage').show()
        }
        else {            
            window.open(globalConstants.rootUrl + "/Product/GetItemBySku?productSku=" + sposSKU, 'HposPopup', 'width=600,height=500,menubar=no,resizeable=no,scrollbars=yes,status=no,toolbar=no');
        }

    });

    $('#cartIcon').popover({ content: "Item successfully added to your cart.", placement: "bottom", animation :'true' , trigger : 'manual' });

    $('#cartIcon').on('shown.bs.popover', function () {
        window.setTimeout(function () { $('#cartIcon').popover('hide'); }, 3000);
        });

    $('.angularAddToCartPopOver').popover({ content: "Item successfully added to your cart.", placement: "top", animation: 'true', trigger: 'manual', container: 'body' });

    $('.angularAddToCartPopOver').on('shown.bs.popover', function () {
        window.setTimeout(function () {
            $('.angularAddToCartPopOver').popover('hide');
        }, 3000);
    });

    $('.addToCartPopOver').popover({ content: "Item successfully added to your cart.", placement: "top", animation: 'true', trigger: 'manual', container: 'body' });

    $('.addToCartPopOver').on('shown.bs.popover', function () {
        window.setTimeout(function () {
            $('.addToCartPopOver').popover('hide');
        }, 3000);
    });

    $('.addToWishListPopOver').popover({ content: "Item successfully added to your wishlist.", placement: "top", animation: 'true', trigger: 'manual', container: 'body' });

    $('.addToWishListPopOver').on('shown.bs.popover', function () {
        window.setTimeout(function () {
            $('.addToWishListPopOver').popover('hide');
        }, 3000);
    });   

    //this prevents los of focus of your modal when you have a second modal pop up
    $(document).on('hidden.bs.modal', function (event) {
        if ($('.modal:visible').length) {
            $('body').addClass('modal-open');
        }
    });

//check for mobiler device
    var isMobile = false; //initiate as false
    // device detection
    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
        || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;

    //Comment by OD GD
    //$("#inptHeaderSearch").autocomplete({
    //    source: function (request, response) {
    //        $.ajax({
    //            dataType: 'json',
    //            cache: true,
    //            url: globalConstants.rootUrl + "/api/QuickSearchService/GetProducts?term=" + $("#inptHeaderSearch").val(),
    //            type: "GET",
    //            success: function (data) {
    //                response($.map(data, function (item) {
    //                    return {
    //                        label: item.SearchTerm,
    //                        url: item.SearchPage.replace("<B>", "").replace("</B>", ""),
    //                        header: item.Header,
    //                        value: item.SearchTerm.replace("<B>", "").replace("</B>", "")
    //                    }
    //                }));
    //            }
    //        });
    //    },
    //    minLength: 3,
    //    focus: function (event, ui) {
    //        if (ui.item.header != 'true') {
    //            if (isMobile) {
    //                window.location.href = ui.item.url;
    //            } else {
    //                $('#inptHeaderSearch').val(ui.item.label.replace("<B>", "").replace("</B>", ""));
    //            }
    //        }
    //        return false;
    //    },
    //    select: function (event, ui) {
    //        if (ui.item.header != 'true') {
    //            $('#inptHeaderSearch').val(ui.item.label.replace("<B>", "").replace("</B>", ""));
    //            window.location.href = globalConstants.rootUrl + '/' + ui.item.url;
    //            return true;
    //        } else {
    //            return false;
    //        }
    //    }

    //}).data("ui-autocomplete");

    //This overwrites all instances of autocomplete to properly escape HTML in the labels
    $["ui"]["autocomplete"].prototype["_renderItem"] = function (ul, item) {
        if (item.header == 'true') {
            return $("<li class='ui-menu-category'></li>")
			  .data("item.autocomplete", item).html(item.label).appendTo(ul);
        } else {
            return $("<li></li>")
			  .data("item.autocomplete", item)
			  .append($("<a></a>").html(item.label))
			  .appendTo(ul);
        }
    };

    $(".btnWish").on("click", function () {
        $(this).css("color", "Red");
    });

    getStoreData();


    //jquery plugin for numbers
    //$(".numeric").numeric();
    //$(".integer").numeric(false, function () { alert("Integers only"); this.value = ""; this.focus(); });
    //$(".positive").numeric({ negative: false }, function () { alert("No negative values"); this.value = ""; this.focus(); });
    //$(".positive-integer").numeric({ decimal: false, negative: false }, function () { alert("Positive integers only"); this.value = ""; this.focus(); });
    $(".decimal-2-places").numeric({
        decimalPlaces: 2,
        negative: false
    });

    $(".disabled").on("click", function () { return false; });

    $("#btnRemove").click(function () {
        $('input:checkbox.checktoremove:checked').parents("tr").remove();
        return false;
    });

    $(".removeProduct").click(function () {

        $.cookie('prodCompIDs', $(this).attr("rel"), { path: "/" });
        return true;
    });


    $(".btn-cart").on("click", function () {
        BootstrapDialog.closeAll();
    });

    //activates the first tab on the product page
    $(function() {
        var tab = $("ul.details-tab li:first > a");
        tab.trigger("click");
    });
   

    $("input:checkbox.warranty").on('click', function () {
        // in the handler, 'this' refers to the box clicked on
        var $box = $(this);
        if ($box.is(":checked")) {
            // the name of the box is retrieved using the .attr() method
            // as it is assumed and expected to be immutable
            var group = "input:checkbox[name='" + $box.attr("name") + "']";
            // the checked state of the group/box on the other hand will change
            // and the current value is retrieved using .prop() method
            $(group).prop("checked", false);
            $box.prop("checked", true);
        } else {
            $box.prop("checked", false);
        }
    });

    $("#readReviews").on("click", function() {
        $("#lnkReviewTab").trigger("click");
        $('html, body').scrollTop($(".product-details-holder").offset().top);
    });

    $(".help.rating").on("click", function () {
        $("#usedRatingLnk").trigger("click");
        $('html, body').scrollTop($("#usedRatingLnk").offset().top);
    });

    $("#readOverview").on("click", function () {

        if($("#overviewDrop").hasClass("opener collapsed")) {
            $("#overviewDrop").trigger("click").addClass("opener");
            $('html, body').scrollTop($(".product-details-holder").offset().top);
        }

        if ($("#overviewDrop").hasClass("collapsed opener")) {
            $("#overviewDrop").trigger("click").addClass("opener");
            $('html, body').scrollTop($(".product-details-holder").offset().top);
        }
        else {
            $('html, body').scrollTop($(".product-details-holder").offset().top);
        }
       
    });

    $("#showPromoModal").on("click", function () {
        $('html, body').scrollTop(0, 0);
        $("#special-offer-modal").slideToggle(function () {
            // Animation complete.
        });
    }); 

    $("#closePromoModal").on("click touchend", function () {
        $("#special-offer-modal").slideToggle(function() {

            // Animation complete.

        });

    });

    $(function() {
        var url = window.location.href;
        if (url.indexOf("#specialOffers") > -1 || url.indexOf("#/specialOffers") > -1) {
            $("#showPromoModal").trigger("click");
        } else if (url.indexOf("#reviews") > -1 || url.indexOf("#/reviews") > -1) {
            $("#readReviews").trigger("click");
        } 
    });
    
});

function openStore() {
    $(".location-box").toggleClass("in");
       
}

function closeStore() {
    $(".store-opener").click();
    $(".location-box").removeClass("in");
}


function showQuickViewBtn(obj) {
    $(obj).children(".btnQuickView").css('display', 'block');
   
}

function hideQuickViewBtn(obj) {
    $(obj).children(".btnQuickView").css('display', 'none');

}

function loadQuickView(id) {
    //why? because infinite scroll doesnt bind ng-click 
    //for those products loaded after page 1
    //yay for angualr
    var scope = angular.element(".loadQuickView").scope();
    scope.loadQuickView(id);
}

//warranty modal on category page
function getStoreData() {
    $.ajax({
        url: globalConstants.rootUrl + '/Stores/StoreData',
        dataType: 'html',
        success: function (data) {
            $('#myStoreContainer').html(data);
        },
    });
}

function disableWarrantyModal() {

    $("#warranty-modal").slideUp(function () {
        // Animation complete.
        $.cookie("WarrantyModalCookie", true, { path: "/" });
    });

}

function hideWarrantymodal() {

    $("#warranty-modal").slideUp(function () {
        // Animation complete.
    });

}

$("#closeWelcomeModal").on("click touchend", function () {
    $(".welcome-modal").slideUp();
});

function ClearComparisons() {
    $.cookie('prodCompIDs', null, { path: "/" });
    location.reload();
}

//this wierd mehtod checks if we need the grey out the zoom buttons on product page img or not
//the zoom comes form p2H without documentation so this is the only way i found to do this
function zoomcheck(event) {
    window.setTimeout(function () {
        var img = $(".mask > .slideset > .slide.active").find(".zoomer-holder");
        if ($(img).css("transform") == "matrix3d(0.998, 0, 0, 0, 0, 0.998, 0, 0, 0, 0, 1, 0, -500, -500, 0, 1)" ||
            $(img).css("transform") == "matrix(0.998, 0, 0, 0.998, -500, -500)") {
            $(".zoomer-zoom-in").css("color", "#dcdfe0");
            $(".zoomer-zoom-out").css("color", "#f78f1e");
        } else if ($(img).css("transform") == "matrix3d(0.335, 0, 0, 0, 0, 0.335, 0, 0, 0, 0, 1, 0, -500, -500, 0, 1)" ||
            $(img).css("transform") == "matrix3d(0.337, 0, 0, 0, 0, 0.337, 0, 0, 0, 0, 1, 0, -500, -500, 0, 1)"
		|| $(img).css("transform") == "matrix(0.337, 0, 0, 0.337, -500, -500)" ||
            $(img).css("transform") == "matrix(0.335, 0, 0, 0.335, -500, -500)") {
            $(".zoomer-zoom-in").css("color", "#f78f1e");
            $(".zoomer-zoom-out").css("color", "#dcdfe0");
        } else {
            $(".zoomer-zoom-in").css("color", "#f78f1e");
            $(".zoomer-zoom-out").css("color", "#f78f1e");
        }
    }, 500);
}



function delayClick(section) {
    window.setTimeout(function () {
        jQuery(section).click();
    }, 500);
}

// scroll gallery init
function initProductPageCarousel() {
    jQuery('#productCarousel').scrollGallery({
        mask: '.mask1',
        slider: '.slideset1',
        slides: '.slide1',
        btnPrev: 'a.btn-prev',
        btnNext: 'a.btn-next',
        generatePagination: '.pagination-links',
        disableWhileAnimating: true,
        autoRotation: false,
        switchTime: 3000,
        animSpeed: 500,
        step: 1
    });
}

function showSpinner(text) {
        $("#spinnermodal").show();
        $("#spinnertext").text(text);
        $("#spinnerfade").show();
}

function hideSpinner() {
    $("#spinnermodal").hide();
    $("#spinnerfade").hide();
}
function showUsedpopUp() {
    BootstrapDialog.show({
        title: "<span class=\"logo-img\"><img src=\"/content/images/logo.png\" alt=\"Henry's\"></span><span class=\"text\" style=\"color:#fff;\">CANADA'S GREATEST CAMERA STORE</span>",
        cssClass: 'Henrys-dialog',
        message: '<div class="used-flyout"><h1>Used Product Condition Codes</h1>' +
            '<ul><li><span class="usedcondition">10</span>: Never sold to a customer and never used. New as shipped by the manufacturer or ' +
            'distributor with all original packing and instruction manuals. </li>' +
            '<li><span class="usedcondition">9</span>: 100% original finish. Just like factory new, but may not include original packing ' +
            'material or instruction books.</li>' +
            '<li><span class="usedcondition">8+</span>: 90-99% of original finish. Used very little, but obviously used. No major marring ' +
            'of the finish or brassing. Optics perfect. Mechanics perfect.</li>' +
            '<li><span class="usedcondition">8</span>: 80-89% of original finish. May have a finish flaw or two that detract from appearance,' +
            'but must be optically and mechanically perfect.</li>' +
            '<li><span class="usedcondition">8-</span>: 70-79% of original finish. May have relatively large flaws in finish that does ' +
            'not affect functionality. Must be optically and mechanically perfect.</li>' +
            '<li><span class="usedcondition">7</span>: 60-69% of original finish. Must be complete, but may be scratched or scuffed. ' +
            'Metal may show wear but should have no corrosion, rust or pits. Must be optically and mechanically perfect.</li>' +
            '</ul></div>',
        buttons: [
            {
                label: 'OK',
                cssClass: 'btn-primary',
                action: function (dialogItself) {
                    dialogItself.close();
                }
            }
        ]
    });
}

function showHenrysMsg(msg) {
    BootstrapDialog.show({
        title: "<span class=\"logo-img\"><img src=\"/content/images/logo.png\" alt=\"Henry's\"></span><span class=\"text\" style=\"color:#fff;\">CANADA'S GREATEST CAMERA STORE</span>",
        cssClass: 'Henrys-dialog',
        message: "<p style='font-size:16px;'>" + msg  + "</p>",
        buttons: [
            {
                label: 'OK',
                cssClass: 'btn-primary',
                action: function (dialogItself) {
                    dialogItself.close();
                }
            }
        ]
    });
}

function addWarrantyItem(event, mainProduct) { //adds warranty item if checkd
    var id = event.id.replace("btnAddToCart", "");
    if (id == "") {
        //this happens if this is in a caruousel 
        //the repeated producs have their ids removed so add this pid
        //attribute instead and check the value
        //example:gift-cards.aspx
      id =  $(event).attr("pid").replace("btnAddToCart", "");
    }
    var showWarrantyPanel = true;
    //if they selected a warranty item add it
    if (mainProduct) {
        $('input:checkbox.warranty').each(function (index, value) {
            if ($(this).is(":checked")) {
                var iId = $(this).attr('id');
                var pId = $(this).attr('productId');
                globalCartHelper.AddToCart(iId, pId, false, 0, 1, false);
                showWarrantyPanel = false;
            }
        });
    }


    var quickViewModal = angular.element('#quickViewModal').scope();
    var compareModal = $(".compare-product-modal");
    var giftCard = $(".gift-card-item");
    var wishlistHolder = $(".wish-lists-holder");
    //if we are inisde quick view close it
    if (quickViewModal != undefined) {
        quickViewModal.$close();
    }
    //not main product check if there are any warranty items 
    if (showWarrantyPanel && $.cookie("WarrantyModalCookie") == undefined) {
        $.ajax({
            url: globalConstants.rootUrl + '/Product/ShowWarrantyModal?id=' + id,
            dataType: 'html',
            success: function (data) {
                if ((data.length > 0 && giftCard.length == 0) ||
                    quickViewModal != undefined ||
                    compareModal.length > 0 ||
                    giftCard.length > 0 ||
                    wishlistHolder.length > 0) {
                    //show top bubble
                    $('#warrantyContainer').html(data);
                        window.scrollTo(0, 0);
                        $('#cartIcon').popover('show');
                        $("#warranty-modal").slideDown(function () {
                            // Animation complete.
                        });
                  
                } else {
                    //show button bubble
                    $('.btnPopOver' + id).popover('show');
                    $('.another-look #btnAddToCart' + id).popover('show');
                    $('.experts-recommend #btnAddToCart' + id).popover('show');
                    $('.product-compare-item #btnAddToCart' + id).popover('show');
                    $('.kit-footer #btnAddToCart' + id).popover('show');
                    $('.gift-card-item #btnAddToCart' + id).popover('show');
                 
                }
            },
        });
      
    } else {
        $('.btnPopOver' + id).popover('show');
        $('.another-look #btnAddToCart' + id).popover('show');
        $('.experts-recommend #btnAddToCart' + id).popover('show');
        $('.product-compare-item #btnAddToCart' + id).popover('show');
        $('.kit-footer #btnAddToCart' + id).popover('show');
        $('.gift-card-item #btnAddToCart' + id).popover('show');
    }
}

//This is for the newsletter sign up
function initValidation() {
    var errorClass = 'error';
    var successClass = 'success';
    var regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var regPhone = /^[0-9]+$/;
    var charNumber = 0;

    //This is for the newsletter sign up
    jQuery('form.newsletter-form, form.validate-form').each(function () {
        var form = jQuery(this).attr('novalidate', 'novalidate');
        var successFlag = true;
        var inputs = form.find('input, textarea, select');

        // form validation function
        function validateForm(e) {
            successFlag = true;

            inputs.each(checkField);

            if (!successFlag) {
                e.preventDefault();
            }
            return successFlag;
        }

        // check field
        function checkField(i, obj) {
            var currentObject = jQuery(obj);
            var currentParent = form;

            // not empty fields
            if (currentObject.hasClass('required')) {
                setState(currentParent, currentObject, !currentObject.val().length || currentObject.val() === currentObject.prop('defaultValue'));
            }
            // correct email fields
            if (currentObject.hasClass('required-email')) {
                setState(currentParent, currentObject, !regEmail.test(currentObject.val()));
            }
            // correct number fields
            if (currentObject.hasClass('required-number')) {
                setState(currentParent, currentObject, !regPhone.test(currentObject.val()));
            }
            // something selected
            if (currentObject.hasClass('required-select')) {
                setState(currentParent, currentObject, currentObject.get(0).selectedIndex === 0);
            }
        }

        // set state
        function setState(hold, field, error) {
            hold.removeClass(errorClass).removeClass(successClass);
            if (error) {
                hold.addClass(errorClass);
                field.one('focus', function () { hold.removeClass(errorClass).removeClass(successClass); });
                successFlag = false;
            } else {
                hold.addClass(successClass);
            }
        }

        // form event handlers
        form.submit(function (e) {

            if (validateForm(e)) {
                  e.preventDefault();
                var email = $('input[name="email"]').val();
                if (subscriptionEmail != email) {
                    subscriptionEmail = email;
                    jQuery.ajax({
                        type: form.attr('method') || 'post',
                        url: form.attr('action'),
                        data: form.serialize(),
                        error: function() {
                            alert('AJAX error!');

                        },
                        success: function () {
                            
                            BootstrapDialog.show({
                                title:
                                    "<span class=\"logo-img\"><img src=\"/content/images/logo.png\" alt=\"Henry's\"></span><span class=\"text\" style=\"color:#fff;\">Canada’s Greatest Camera Store</span>",
                                cssClass: 'Henrys-dialog',
                                message:
                                    '<h3>Success!</h3><p style="font-size:16px;">You should be receiving an email shortly.</p> <p style="font-size:16px;">Please click on the link in your email to complete the subscription! You can look forward to finding out the latest products, current sales, etc…</p>',
                                onshown: function(dialogRef) {
                                    //window.setTimeout(function () {
                                    //    if (dialogRef && dialogRef.close) {
                                    //        dialogRef.close();
                                    //    }
                                    //}, 2000);
                                },
                                buttons: [
                                    {
                                        label: 'OK',
                                        cssClass: 'btn-primary',
                                        action: function(dialogItself) {
                                            dialogItself.close();
                                        }
                                    }
                                ]
                            });
                        }
                    });
                }
                else
                {
                   BootstrapDialog.show({
                            title:
                                "<span class=\"logo-img\"><img src=\"/content/images/logo.png\" alt=\"Henry's\"></span><span class=\"text\" style=\"color:#fff;\">Canada’s Greatest Camera Store</span>",
                            cssClass: 'Henrys-dialog',
                            message:
                                '<p style="font-size:16px;">This email has already been registered.</p> <p style="font-size:16px;"></p>',
                            onshown: function(dialogRef) {
                            },
                            buttons: [
                                {
                                    label: 'OK',
                                    cssClass: 'btn-primary',
                                    action: function(dialogItself) {
                                        dialogItself.close();
                                    }
                                }
                            ]
                        });
                    }
                

            } else {
                BootstrapDialog.show({
                    title: "<span class=\"logo-img\"><img src=\"/content/images/logo.png\" alt=\"Henry's\"></span><span class=\"text\" style=\"color:#fff;\">Canada’s Greatest Camera Store</span>",
                    cssClass: 'Henrys-dialog',
                    message: '<p style="font-size:16px;">Please enter a valid email address.</p>',
                    onshown: function (dialogRef) {
                        //window.setTimeout(function () {
                        //    if (dialogRef && dialogRef.close) {
                        //        dialogRef.close();
                        //    }
                        //}, 2000);
                    },
                    buttons: [{
                        label: 'OK',
                        cssClass: 'btn-primary',
                        action: function (dialogItself) {
                            dialogItself.close();
                        }
                    }]

                });
            }
        });
    });
}

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

//enhanced ecommerce scripts
function FireProductData(productId, action) {
    var pId = "";
    var name = "";
    var cats = "";
    var brand = "";
    var price = "";
    var event = "AddToCart";
    var page = window.location.href;
    var pos = 1;
    var product;
    $.ajax({
        url: globalConstants.rootUrl + '/EnhancedEcommerce/GetProductData?id=' + productId,
        method: "POST",
        contentType: "application/json; charset=utf-8",
        error: function () {
        },
        success: function (data) {
            if (data != null) {
              
                var stuff = data.split(":");
                pId = stuff[0];
                name = stuff[1];
                cats = stuff[2];
                brand = stuff[3];
                price = stuff[4].toLowerCase();

                
                //initializing the product object ot send to datalayer
                window.productDataArray = [];
                
                //removing quotes from name as per client request
               // name = name.replace(/[''"@#!$%^&*\/.]+/gi, '');
                if (action == "AddToCart") {

                    if (page.includes("Categories")) {
                        event = "categoriesAddToCart";
                    } else {
                        event = "addToCart";
                    }
                    product = { 'id': pId, 'name': name, 'category': cats, 'brand': brand, 'price': price, 'quantity': 1 };
                    window.productDataArray.push(product);
                    dataLayer.push({
                        "event": event,
                        "ecommerce": {
                            "currencyCode": "CAD",
                            "add": {
                                "products": productDataArray
                            }
                        }
                    });
                }
                else if (action == "ReserveInStore") {
                    if (page.includes("Categories")) {
                        event = "categoriesReserveInStore";
                    } else {
                        event = "reserveInStore";
                    }
                    product = { 'id': pId, 'name': name, 'category': cats, 'brand': brand, 'price': price, 'quantity': 1 };
                    window.productDataArray.push(product);
                    dataLayer.push({
                        "event": event,
                        "ecommerce": {
                            "currencyCode": "CAD",
                            "add": {
                                "products": productDataArray
                            }
                        }
                    });
                }
                else {
                    product = { 'id': pId, 'name': name, 'category': cats, 'brand': brand, 'price': price};
                    window.productDataArray.push(product);
                    event = "productDetailView";
                    dataLayer.push({
                        "event": event,
                        "ecommerce": {
                            "currencyCode": "CAD",
                            "detail": {
                                "products": productDataArray
                            }
                        }
                    });
                }
            }

        }
    });

}

function FireImpressionData(impArray, addToIndex) {

    var productsTosend = [];
    if (!positionArray) {
        positionArray = [];
    }
   
    for (var i = 0; i < impArray.length; i++) {
       var products = {
           'id': impArray[i].ProductId,
           'name': impArray[i].Name,
           'category': impArray[i].Category,
           'brand': impArray[i].Brand,
           'list': impArray[i].List,
            'position': (addToIndex + (i+1))
       };
       positionArray.push({ 'id': impArray[i].ProductId, 'position': (addToIndex + (i + 1)) });
        productsTosend.push(products);
    }
    dataLayer.push({
        'event': 'caegoryListView',
            "ecommerce": {
                "impressions":  productsTosend
            }
        });
    
    //ending script
}

function FireProductClickDataEvent(productId, productUrl) {

    var pId = "";
    var name = "";
    var cats = "";
    var brand = "";
    var price = "";
    var list = "";
    var pos = 1;
        $.ajax({
            url: globalConstants.rootUrl + '/EnhancedEcommerce/GetProductData?id=' + productId,
            method: "POST",
            contentType: "application/json; charset=utf-8",
            error: function() {
                console.log("Ecommerce Product Click Event Not fired");
                window.location = globalConstants.rootUrl + "/" + productUrl;
            },
            success: function(data) {
                if (data != null) {

                    var stuff = data.split(":");
                    pId = stuff[0];
                    name = stuff[1];
                    cats = stuff[2];
                    brand = stuff[3];
                    price = stuff[4];
                    list = stuff[5];
                    
                    if (positionArray) {
                        for (var i = 0; i < positionArray.length; i++) {
                            if (positionArray[i].id == pId) {
                                pos = positionArray[i].position;
                                break;
                            }
                        }
                    }
                   
                    dataLayer.push({
                        'event': 'productClick',
                        'ecommerce': {
                            'click': {
                                'actionField': { 'list': list },
                                'products': [
                                    {
                                        'name': name,
                                        'id': pId,
                                        'price': price,
                                        'brand': brand,
                                        'category': cats,
                                        'position': pos
                                    }
                                ]
                            }
                        },
                        'eventCallback': function() {
                            window.location = globalConstants.rootUrl + "/" + productUrl;
                        }
                    });
                }
            }
        });
}


function FireCheckoutClickDataEvent(items, step) {

    if (items) {

        var itemData = [];
        for (var x = 0; x < items.length; x++) {
            if (items[x].ItemCode != '889EHF021') {
                itemData.push({
                    'name': items[x].ProductDisplayName,
                    'id': items[x].ItemCode,
                    'price': items[x].UnitPrice.toFixed(2),
                    'brand': items[x].BrandName,
                    'category': items[x].CategoryString,
                    'quantity': items[x].Quantity
                });
            }
        }
        if (itemData.length > 0) {
            switch (step) {
                case 0:
                    dataLayer.push({
                        'event': 'checkout',
                        'ecommerce': {
                            'checkout': {
                                'actionField': { 'step': 1, 'option': 'Login' },
                                'products': itemData
                            }
                        }
                    });
                    // Set initial data in state
                    var data = {
                        currentStage: 1,
                        currentStageName: "Login"
                    };

                    var hostName = window.location.hostname;
                    var protocol = window.location.protocol;
                    hostName = hostName + globalConstants.rootUrl;
                    var absUrl = protocol + '//' + hostName + "/";
                    absUrl = absUrl + 'account/SignIn?ReturnUrl=' +globalConstants.rootUrl + '%2fCheckout';
                    history.pushState(data, data.currentStageName, absUrl);
                    break;
            case 1:
                dataLayer.push({
                    'event': 'checkout',
                    'ecommerce': {
                        'checkout': {
                            'actionField': { 'step': 2, 'option': 'Shipping Address' },
                            'products': itemData
                        }
                    }
                });
                AddHistoryUrl(2, "Shipping Address", "shippingAddressAnchor");
                break;
            case 2:
                dataLayer.push({
                    'event': 'checkoutOption',
                    'ecommerce': {
                        'checkout': {
                            'actionField': { 'step': 3, 'option': 'Shipping Method' },
                            'products': itemData
                        }
                    }
                });
                AddHistoryUrl(3, "Shipping Method", "shippingAnchor");
                break;
            case 3:
                dataLayer.push({
                    'event': 'checkoutOption',
                    'ecommerce': {
                        'checkout': {
                            'actionField': { 'step': 4, 'option': 'Payment Details' },
                            'products': itemData
                        }
                    }
                });
                AddHistoryUrl(4, "Payment Details", "paymentAnchor");
                break;
            case 4:
                dataLayer.push({
                    'event': 'checkoutOption',
                    'ecommerce': {
                        'checkout': {
                            'actionField': { 'step': 5, 'option': 'Billing Address' },
                            'products': itemData
                        }
                    }
                });
                AddHistoryUrl(5, "Billing Address", "billing-address");
                break;
            case 5:
                dataLayer.push({
                    'event': 'checkoutOption',
                    'ecommerce': {
                        'checkout': {
                            'actionField': { 'step': 6, 'option': 'Final Review' },
                            'products': itemData
                        }
                    }
                });
               AddHistoryUrl(6, "Final Review", "final-review");
                break;
            }

        } else {
            console.log("Checkout data not recorded for enhanced e-commerce");
        }
    }
}

function closeSuggestionBoxIfTab(e) {
    var TABKEY = 9;
    if (e.keyCode == TABKEY) {       
        $('body').click();       
    }    
}

function AddHistoryUrl(stage, stageName, stageAnchor) {
    var hostName = window.location.hostname;
    var protocol = window.location.protocol;
    hostName = hostName + globalConstants.rootUrl;
    var absUrl = protocol + '//' + hostName + "/";

    var data = {
        currentStage: stage,
        currentStageName: stageName
    };
    var anchorpart = "Checkout";
    if (stageAnchor.length > 0) {
        anchorpart = anchorpart + "#" + stageAnchor;
    }
    absUrl = absUrl + anchorpart;
    history.pushState(data, data.currentStageName, absUrl);
}

$(window).on('popstate', function (e) {
    var state = e.originalEvent.state;
    if (state !== null ) {
        if (state.currentStage !== null && state.currentStage !== -1) {
            angular.element(document.getElementById('viewcheckoutcontainer')).scope().loadcheckoutstep(state);
        } else {
            angular.element(document.getElementById('viewcheckoutcontainer')).scope().showConfirmDialog(state);
        }
    } else {
        console.log('not found');
    }
});

function CheckForNumbers(e) {
    var numbersRegex = /^\d+$/;
    if (!numbersRegex.exec(String.fromCharCode(e.which))) e.preventDefault();
}

//bvc - new unbxd
$(document).ready(function () {
    if ($("#unbxd_category_top_sellers").length > 0) {
        CheckUnbxdContentCat("unbxd_category_top_sellers", "category (" + UnbxdWidgetsConf.category + ")");
    }

    if ($("#unbxd_top_sellers").length > 0) {
        CheckUnbxdContent("unbxd_top_sellers", "home");
    }

    if ($("#unbxd_recently_viewed").length > 0) {
        CheckUnbxdContent("unbxd_recently_viewed", "home");
    }

    if ($("#unbxd_complete_the_look").length > 0) {
        CheckUnbxdContentPDP("unbxd_complete_the_look", "product (" + UnbxdWidgetsConf.pid + ")");
    }

    if ($("#unbxd_also_bought").length > 0) {
        CheckUnbxdContentPDP("unbxd_also_bought", "product (" + UnbxdWidgetsConf.pid + ")");
    }

});

function CheckUnbxdContent(unbxdDiv, page) {
    window.setTimeout(function () {
        var unbxdContent = $("#" + unbxdDiv);
        if (unbxdContent.length > 0) {
            if (unbxdContent.html().length > 0) {
                console.log(page + " - " + unbxdDiv + " > OK");
            } else {
                console.log(page + " - " + unbxdDiv + " > No content");
            }
        } else {
            console.log(page + " - " + unbxdDiv + " > Inactive");
        }
    }, 1000);
}

function CheckUnbxdContentCat(unbxdDiv, page) {
    window.setTimeout(function () {
        var unbxdContent = $("#" + unbxdDiv);
        if (unbxdContent.length > 0) {
            if (unbxdContent.html().length > 0) {
                $(".recordCountDiv > div").hide();
                $(".unbxdRecordCountDiv").show();
                console.log(page + " - " + unbxdDiv + " > OK");
            } else {
                $(".unbxdCatTopSellDiv").hide();
                $(".unbxdRecordCountDiv").hide();
                $(".recordCountDiv > div").show();
                console.log(page + " - " + unbxdDiv + " > No content");
            }
        } else {
            $(".unbxdCatTopSellDiv").hide();
            $(".unbxdRecordCountDiv").hide();
            $(".recordCountDiv > div").show();
            console.log(page + " - " + unbxdDiv + " > Inactive");
        }
    }, 500);
}

function CheckUnbxdContentPDP(unbxdDiv, page) {
    window.setTimeout(function () {
        var unbxdContent = $("#" + unbxdDiv);
        if (unbxdContent.length > 0) {
            if (unbxdContent.html().length > 0) {
                console.log(page + " - " + unbxdDiv + " > OK");
            } else {
                //$("#" + unbxdDiv).parent().parent().hide();
                $("#ProdAccessories").show();
                console.log(page + " - " + unbxdDiv + " > No content");
            }
        } else {
            $("#" + unbxdDiv).parent().parent().hide();
            $("#ProdAccessories").show();
            console.log(page + " - " + unbxdDiv + " > Inactive");
        }
    }, 500);
}

function PostalCodeCheck(event) {
    var alphaNumericRegX = /^[a-z0-9]+$/i;
    if (!alphaNumericRegX.exec(String.fromCharCode(event.which))) event.preventDefault();
};
/** 
This script below is dependant on 1 plugins along with jquery located in Scripts/jquery.inview.js - 
 - jquery inview plugin
**/

var isInfiniteScrollActive = true;
var moreResults = true;
var inCallBack = false;
var title;

$(window).load(function (e) {
    if (isInfiniteScrollActive) {
        title = $(document).find('title').text();

        //Below is where all the magic happens to determine if our empty scrollTrigger div is in view to get more results
        $('.load-more').on('click', function (event) {

            //if (visible == true) {
                if (moreResults && !inCallBack) {
                    inCallBack = true;
                    //$('#productsLoader').show();
                    LoadNextPage(decodeURI(document.URL));
                    inCallBack = false;
                }
            //}
        });
    }
});

function LoadNextPage(Url) {
    showSpinner("Loading more products...");
    var container = $('*[data-scroll="scrollContainer"]');
    window.impressionScript = [];
    var controller = ReturnController(Url);

    if (controller != "empty") {
        var url = rootRel + controller + '/GetNextPage/1/' + identifier + '/' + pageNum + '/' + filters;

        //Below we are getting the results back from the controller (above) and appending them onto the current product list/grid
        //We are also maintaining what page we are on to determine if there are more results to return from further scolling
        $.getJSON(url, function (results) {
            container.append(results.Products);
            
            FireImpressionData(impressionScript, (pageNum*12));
            updateQueryStringParameter(document.URL, "offset", results.Offset);
         
            $('.addToCartPopOver').popover({ content: "Item successfully added to your cart.", placement: "top", animation: 'true', trigger: 'manual' });
            $('.addToCartPopOver').on('shown.bs.popover', function () {
                window.setTimeout(function () {
                    $('.addToCartPopOver').popover('hide');
                }, 3000);
            });

            if (results.PageNum === results.TotalPages) {
                moreResults = false;
                $(".load-more").hide();
            }
            pageNum++;
           
            $(".results").html("1 - " + results.Offset + " of <span style='font-weight:bold;'>" + results.TotalRecords + "</span>");
       
            hideSpinner();
        });
    } else {
        console.error("Return Controller Method in InfiniteScroll.js returned 'empty'");
        hideSpinner();
    }
}

function updateQueryStringParameter(uri, key, value) {
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    var newuri;
    if (uri.match(re)) {
        newuri = uri.replace(re, '$1' + key + "=" + value + '$2');
    }
    else {
        newuri = uri + separator + key + "=" + value;
    }

    history.pushState(null, "", newuri);
}

function ReturnController(url) {
    //Regex Patterns would need to be added/removed depending on project or client URL requirements
    var catPattern = new RegExp("/Categories/([0-9]*)-[0-9A-Za-z_-]*\\.aspx(.*)", "i");
    var brandPattern = new RegExp("/Brands/([0-9]*)-*[0-9A-Za-z_-]*\\.aspx(.*)", "i");
    var searchPattern = new RegExp("/Search/(.*)\\.aspx(.*)", "i");

    if (url.match(catPattern)) {
        return "Categories";
    }
    if (url.match(brandPattern)) {
        return "Brands";
    }
    if (url.match(searchPattern)) {
        return "Search";
    }

    return "empty";
}
;
/* ========================================================================
 * Bootstrap (plugin): validator.js v0.8.1
 * ========================================================================
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Cina Saffary.
 * Made by @1000hz in the style of Bootstrap 3 era @fat
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * ======================================================================== */


+function ($) {
    'use strict';

    var inputSelector = ':input:not([type="submit"], button):enabled:visible'
    // VALIDATOR CLASS DEFINITION
    // ==========================

    var Validator = function (element, options) {
        this.$element = $(element)
        this.options = options

        options.errors = $.extend({}, Validator.DEFAULTS.errors, options.errors)

        for (var custom in options.custom) {
            if (!options.errors[custom]) throw new Error('Missing default error message for custom validator: ' + custom)
        }

        $.extend(Validator.VALIDATORS, options.custom)

        this.$element.attr('novalidate', true) // disable automatic native validation
        this.toggleSubmit()

        this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.validateInput, this))
        this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))

        this.$element.find('[data-match]').each(function () {
            var $this = $(this)
            var target = $this.data('match')

            $(target).on('input.bs.validator', function (e) {
                $this.val() && $this.trigger('input.bs.validator')
            })
        })
    }

    Validator.DEFAULTS = {
        delay: 500,
        html: false,
        disable: true,
        custom: {},
        errors: {
            match: 'Does not match',
            minlength: 'Not long enough'
        },
        feedback: {
            success: 'glyphicon-ok',
            error: 'glyphicon-warning-sign'
        }
    }

    Validator.VALIDATORS = {
        native: function ($el) {
            var el = $el[0]
            return el.checkValidity ? el.checkValidity() : true
        },
        match: function ($el) {
            var target = $el.data('match')
            return !$el.val() || $el.val() === $(target).val()
        },
        minlength: function ($el) {
            var minlength = $el.data('minlength')
            return !$el.val() || $el.val().length >= minlength
        }
    }

    Validator.prototype.validateInput = function (e) {
        var $el = $(e.target)
        var prevErrors = $el.data('bs.validator.errors')
        var errors

        if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')

        this.$element.trigger(e = $.Event('validate.bs.validator', { relatedTarget: $el[0] }))

        if (e.isDefaultPrevented()) return

        var self = this

        this.runValidators($el).done(function (errors) {
            $el.data('bs.validator.errors', errors)

            errors.length ? self.showErrors($el) : self.clearErrors($el)

            if (!prevErrors || errors.toString() !== prevErrors.toString()) {
                e = errors.length
                  ? $.Event('invalid.bs.validator', { relatedTarget: $el[0], detail: errors })
                  : $.Event('valid.bs.validator', { relatedTarget: $el[0], detail: prevErrors })

                self.$element.trigger(e)
            }

            self.toggleSubmit()

            self.$element.trigger($.Event('validated.bs.validator', { relatedTarget: $el[0] }))
        })
    }


    Validator.prototype.runValidators = function ($el) {
        var errors = []
        var deferred = $.Deferred()
        var options = this.options

        $el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
        $el.data('bs.validator.deferred', deferred)

        function getErrorMessage(key) {
            return $el.data(key + '-error')
              || $el.data('error')
              || key == 'native' && $el[0].validationMessage
              || options.errors[key]
        }

        $.each(Validator.VALIDATORS, $.proxy(function (key, validator) {
            if (($el.data(key) || key == 'native') && !validator.call(this, $el)) {
                var error = getErrorMessage(key)
                !~errors.indexOf(error) && errors.push(error)
            }
        }, this))

        if (!errors.length && $el.val() && $el.data('remote')) {
            this.defer($el, function () {
                var data = {}
                data[$el.attr('name')] = $el.val()
                $.get($el.data('remote'), data)
                  .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
                  .always(function () { deferred.resolve(errors) })
            })
        } else deferred.resolve(errors)

        return deferred.promise()
    }

    Validator.prototype.validate = function () {
        var delay = this.options.delay

        this.options.delay = 0
        this.$element.find(inputSelector).trigger('input.bs.validator')
        this.options.delay = delay

        return this
    }

    Validator.prototype.showErrors = function ($el) {
        var method = this.options.html ? 'html' : 'text'

        this.defer($el, function () {
            var $group = $el.closest('.form-group')
            var $block = $group.find('.help-block.with-errors')
            var $feedback = $group.find('.form-control-feedback')
            var errors = $el.data('bs.validator.errors')

            if (!errors.length) return

            errors = $('<ul/>')
              .addClass('list-unstyled')
              .append($.map(errors, function (error) { return $('<li/>')[method](error) }))

            $block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
            $block.empty().append(errors)
            $group.addClass('has-error')

            $feedback.length
              && $feedback.removeClass(this.options.feedback.success)
              && $feedback.addClass(this.options.feedback.error)
              && $group.removeClass('has-success')
        })
    }

    Validator.prototype.clearErrors = function ($el) {
        var $group = $el.closest('.form-group')
        var $block = $group.find('.help-block.with-errors')
        var $feedback = $group.find('.form-control-feedback')

        $block.html($block.data('bs.validator.originalContent'))
        $group.removeClass('has-error')

        $feedback.length
          && $feedback.removeClass(this.options.feedback.error)
          && $feedback.addClass(this.options.feedback.success)
          && $group.addClass('has-success')
    }

    Validator.prototype.hasErrors = function () {
        function fieldErrors() {
            return !!($(this).data('bs.validator.errors') || []).length
        }

        return !!this.$element.find(inputSelector).filter(fieldErrors).length
    }

    Validator.prototype.isIncomplete = function () {
        function fieldIncomplete() {
            return this.type === 'checkbox' ? !this.checked :
                   this.type === 'radio' ? !$('[name="' + this.name + '"]:checked').length :
                                              $.trim(this.value) === ''
        }

        return !!this.$element.find(inputSelector).filter('[required]').filter(fieldIncomplete).length
    }

    Validator.prototype.onSubmit = function (e) {
        this.validate()
        if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
    }

    Validator.prototype.toggleSubmit = function () {
        if (!this.options.disable) return
        var $btn = $('button[type="submit"], input[type="submit"]')
          .filter('[form="' + this.$element.attr('id') + '"]')
          .add(this.$element.find('input[type="submit"], button[type="submit"]'))
        $btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
          .css({ 'pointer-events': 'all', 'cursor': 'pointer' })
    }

    Validator.prototype.defer = function ($el, callback) {
        callback = $.proxy(callback, this)
        if (!this.options.delay) return callback()
        window.clearTimeout($el.data('bs.validator.timeout'))
        $el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
    }

    Validator.prototype.destroy = function () {
        this.$element
          .removeAttr('novalidate')
          .removeData('bs.validator')
          .off('.bs.validator')

        this.$element.find(inputSelector)
          .off('.bs.validator')
          .removeData(['bs.validator.errors', 'bs.validator.deferred'])
          .each(function () {
              var $this = $(this)
              var timeout = $this.data('bs.validator.timeout')
              window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
          })

        this.$element.find('.help-block.with-errors').each(function () {
            var $this = $(this)
            var originalContent = $this.data('bs.validator.originalContent')

            $this
              .removeData('bs.validator.originalContent')
              .html(originalContent)
        })

        this.$element.find('input[type="submit"], button[type="submit"]').removeClass('disabled')

        this.$element.find('.has-error').removeClass('has-error')

        return this
    }

    // VALIDATOR PLUGIN DEFINITION
    // ===========================


    function Plugin(option) {
        return this.each(function () {
            var $this = $(this)
            var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
            var data = $this.data('bs.validator')

            if (!data && option == 'destroy') return
            if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
            if (typeof option == 'string') data[option]()
        })
    }

    var old = $.fn.validator

    $.fn.validator = Plugin
    $.fn.validator.Constructor = Validator


    // VALIDATOR NO CONFLICT
    // =====================

    $.fn.validator.noConflict = function () {
        $.fn.validator = old
        return this
    }


    // VALIDATOR DATA-API
    // ==================

    $(window).on('load', function () {
        $('form[data-toggle="validator"]').each(function () {
            var $form = $(this)
            Plugin.call($form, $form.data())
        })
    })

}(jQuery);

;
