var o = {},
    e = {},
    priceAuto,
    autoFrameAnim,
    autoHoverAnim,
    nextOffer = 0,
    currentScreen = 0,
    oldScreenY = -1,
    currentScreenOffers = [],
    gallery = {
        enabled: false
    },
    planche = {
        enabled: false
    },
    enlarger = {
        enabled: false
    },
    multiscreen = {
        enabled: false
    },
	currentZoom = window.devicePixelRatio,
    choosen = [],
	canvases = [],
	customClickTracking = {
	    enabled: false,
	    offerTrackingLimit: -1,
	    globalTrackingLimit: -1,
	    globalTrackingCounter: 0
	},
    banner = {
        flags: {
            displayPrice: true,
            mouseOnBanner: false,
            theEnd: false,
            dontShowArrows: false,
            dontChangeOffer: false,
            arrowsVisible: false
        },
        options: {
            offersCount: null,
            infiniteAnimAllowed: true,
            offerPriceEnabled: true,
            logoAnimInterval: 3000,
            logoAnimFadeSpeed: 1000,
            maxAnimTime: 24000,
            enlargerAnimEnabled: false,
            initHoverAnim: true,
            hoverAnimInterval: 1000,
            offersWithOldPrice: [],
            screensMargin: 15,
            logoGIFanimation: 'false'
        },
        elements: {},
        init: function (options) {
            this.checkOffers();
            if(customClickTracking.enabled)this.customClickTracking();
            banner.options = $.extend(banner.options, options);
            o = banner.options;
            o.arrowsEnabled = o.arrowsEnabled.toLowerCase() === 'true';
            o.logoGIFanimation = o.logoGIFanimation.toLowerCase() === 'true';
            banner.cacheElem();			
			banner.initCanvases();
			banner.addChangeZoomEvent();
			if(gallery.enabled)gallery.initImages();
			o.enlargeHover = String(o.creativeBannerTrmplateAnimationType).toLowerCase() == 'hover_enlarge';
            banner.initStandardOpt();
			banner.offerPriceAnim.start();

            e.allOffers.css('top', '0px');
            if (banner.flags.arrowsVisible && multiscreen.enabled) multiscreen.arrowActions.disableInactive();
            if (multiscreen.enabled) multiscreen.checkScreen(0);
        },
        bindUIActions: function () {
            e.offer.on('mouseenter', function (ev) {
                var id = $(this).data('id');
				banner.changeOfferZindex(id);
                nextOffer = id === o.offersCount - 1 ? 0 : id + 1;
                if (o.initHoverAnim) {
                    banner.hoverAnim.stop();
                } else {
					clearTimeout(autoFrameAnim);
                    banner.frameAnim.frameHover(id);
                }
                ev.preventDefault();
            });
			e.offer.on('mouseleave',function(){
                banner.frameAnim.frameHover(-1);
			});
            e.offerHover.on('mouseenter', function (ev) {
                banner.flags.mouseOnBanner = true;
                if (o.initHoverAnim) {
                    banner.hoverAnim.stop();
                } else {
                    banner.frameAnim.stop();
                }
                ev.preventDefault();
            });
            e.banner.on('mouseenter', function (ev) {
                banner.flags.mouseOnBanner = true;
                if (multiscreen.enabled) {
					multiscreen.arrowActions.visibility();
					if(e.borders.hasClass('offer-jumping-frame'))banner.frameAnim.frameHover(-1);
				}
            });
            e.banner.on('mouseleave', function (ev) {
                banner.restartOffersAnim();
				ev.preventDefault();
            });
			

        },
		restartOffersAnim: function(){
			banner.flags.mouseOnBanner = false;
			if (multiscreen.enabled) multiscreen.arrowActions.visibility();
			if (banner.flags.theEnd) {
				banner.offerPriceAnim.hideOldPrice();
				return;
			}
			if ((!enlarger.enabled||o.enlargeHover)&&!e.borders.hasClass('offer-jumping-frame')) {
				if (o.initHoverAnim) {
					banner.hoverAnim.start();
				} else {
					banner.frameAnim.start();
				}
			}
		},
        checkOffers: function () {
            var temp = [],
                that = this;
            $.each(offers, function (i, el) {
                if (el.oldPrice.length) {
                    temp.push({
                        idx: i,
                        el: el
                    });
                }
            });
            $.each(temp, function (i, el) {
                that.options.offersWithOldPrice.push('.offer-container:eq('+el.idx+') .offer-price-container')
            });
            that.options.offersWithOldPrice = that.options.offersWithOldPrice.join(',');
        },
        initStandardOpt: function () {
            banner.screenOffers = o.screenOffers.split(',');
            banner.screensCount = banner.screenOffers.length;
            var tmp = 0;
            for (var i = 0; i <= banner.screensCount; i++) {
                currentScreenOffers[i] = banner.screenOffers[i] - tmp;
                tmp = banner.screenOffers[i];
            }
            e.logoContainer.first().css('display', 'inline-block');
            o.containerHeight += o.screensMargin;
            if (e.logoContainer.length > 1 && !o.logoGIFanimation)
                this.logoAnim.start(e.logoContainer);
            if (!o.infiniteAnimAllowed) {
                setTimeout(function () {
                    banner.flags.theEnd = o.animAgain.toLowerCase() === 'false';
                    $('.offer-oldprice-container').css('display', 'none');
                    $(banner.options.offersWithOldPrice).css('display', 'inline-block');
                    banner.logoAnim.stop(e.logoContainer);
                    banner.hoverAnim.stop();
                    banner.frameAnim.stop();
					$('body').addClass('end-of-animation');
                    if (!banner.flags.theEnd) banner.offerPriceAnim.stop();
                    if (planche.enabled||planche.vid) {
                        planche.plancheAnim.hide();
						planche.enabled = planche.flags.active = false
                        clearTimeout(planche.autoShowTimeout);
                    }
                    if (enlarger.enabled && !banner.flags.mouseOnBanner) {
                        enlarger.clearAllTimeout();
                        enlarger.enlargerAnim.hide();
                    }
                    if (gallery.enabled) {
                        gallery.galleryAnim.stop();
                    }
                    if (!banner.flags.mouseOnBanner && multiscreen.enabled) multiscreen.checkScreen(0);
                }, o.maxAnimTime);
            }

            if (!o.offerPriceEnabled) {
                this.hideElem($('div.offer-enlarger-price-container'));
                this.hideElem($('div.offer-oldprice-container, div.offer-price-container'));
            }

            if (supportTransition)
                $.fn.anim = $.fn.transit;
            else
                $.fn.anim = $.fn.animate;

            if ((!o.enlargerAnimEnabled && String(o.creativeBannerTrmplateAnimationType).toLowerCase() != 'none')||o.enlargeHover) {
                if (gallery.enabled && !o.enlargeHover) {
                    gallery.bindGalleryUIActions();
                    gallery.galleryAnim.start();
                } else if (o.initHoverAnim) {
                    banner.bindUIActions();
                    banner.hoverAnim.start();
                } else {
                    if(!o.enlargeHover) banner.bindUIActions();
                    banner.frameAnim.start();
                }
            }
            if (multiscreen.enabled) multiscreen.arrowActions.init();
        },
        offerPriceAnim: {
            start: function () {
                priceAuto = setTimeout('banner.offerPriceAnim.start()', 1000);
                if (banner.flags.theEnd && !banner.flags.mouseOnBanner) {
                    banner.offerPriceAnim.hideOldPrice();
                    return;
                }
                $(banner.options.offersWithOldPrice).css('display', banner.flags.displayPrice ? 'inline-block' : 'none');
                $('.offer-oldprice-container').css('display', banner.flags.displayPrice ? 'none' : 'inline-block');
                banner.flags.displayPrice = !banner.flags.displayPrice;
            },
            stop: function () {
                clearTimeout(priceAuto);
                banner.offerPriceAnim.hideOldPrice();
            },
            hideOldPrice: function () {
                $('.offer-oldprice-container').css('display', 'none');
                $(banner.options.offersWithOldPrice).css('display', 'inline-block');
                banner.flags.displayPrice = false;
            }
        },
        cacheElem: function () {
            this.elements = {
                banner: $('body'),
                logoContainer: $('#logo-container .logo-box'),
                offer: $('.offer-container'),
                offerHover: $('.offer-hover-container'),
                offerBtn: $('.offer-button-wrapper'),
                offerName: $('.offer-name-container'),
                allOffers: $('#alloffers-container-relative'),
                arrowPrev: $('.nav.prev'),
                arrowPrevBlock: $('#prev-block'),
                arrowNextBlock: $('#next-block'),
                arrowNext: $('.nav.next'),
                arrows: $('#arrows-container'),
                allContainer: $('#alloffers-container'),
                gallery: $('#galImglery-zoom'),
				borders: $('.border-container')
            };
            e = $.extend(e,this.elements);
			e.offerArr = [];
			for(var i=0; i<e.offer.length; i++){
				e.offerArr.push($(e.offer[i]))
			}
        },
        showElem: function ($el) {
            $el.addClass('show').css('display', 'inline-block');
        },
        hideElem: function ($el) {
            $el.addClass('hide').css('display', 'none');
        },
        logoAnim: {
            idx: 0,
            timeout: null,
            start: function ($el) {
				if(!logoReady){
					setTimeout(function(){banner.logoAnim.start($el)},250)
					return;
				}
                $($el[banner.logoAnim.idx]).fadeIn(o.logoAnimFadeSpeed, function () {
                    banner.logoAnim.idx = (banner.logoAnim.idx < $el.length - 1) ? (banner.logoAnim.idx + 1) : 0;
                    banner.logoAnim.timeout = setTimeout(function () {
                        $el.fadeOut(o.logoAnimFadeSpeed);
                        banner.logoAnim.start($el);
                    }, o.logoAnimInterval);
                });
            },
            stop: function ($el) {
                if (!o.logoGIFanimation) {
                    $el.clearQueue().stop(true, true).not($($el[0])).fadeOut();
                    $el.first().fadeIn(o.logoAnimFadeSpeed);
                    clearTimeout(banner.logoAnim.timeout);
                } else if ($el.length === 2) {
                    ($($el[0])).fadeOut();
                    ($($el[1])).fadeIn();
                }
            }
        },
        hoverAnim: {
            start: function () {
                e.banner.addClass('hover-anim');
                autoHoverAnim = setTimeout(function () {
                    if (multiscreen.enabled) multiscreen.checkScreen(nextOffer);
                    e.offerHover.css('display', 'none');
                    e.offerName.css('marginTop', '');
                    e.offerBtn.css('display', '');
                    $(e.offerHover[nextOffer]).css('display', 'inline-block');
                    $(e.offerName[nextOffer]).css('marginTop', 0);
                    $(e.offerBtn[nextOffer]).css('display', 'inline-block');
                    nextOffer = nextOffer === o.offersCount - 1 ? 0 : nextOffer + 1;
                    banner.hoverAnim.start();
                }, o.hoverAnimInterval);
            },
            stop: function () {
                e.banner.removeClass('hover-anim');
                clearTimeout(autoHoverAnim);
                e.offerHover.css('display', '');
                e.offerBtn.css('display', '');
                e.offerName.css('marginTop', '');
            }
        },
        frameAnim: {
            start: function () {
                if (o.offersCount === 0) return;
                e.banner.addClass('hover-anim');
                clearTimeout(autoFrameAnim);
				if (multiscreen.enabled) multiscreen.checkScreen(nextOffer);
                autoFrameAnim = setTimeout(function () {
                    banner.frameAnim.start();
					if(banner.flags.mouseOnBanner&&multiscreen.enabled&&!gallery.enabled&&!isMobile) return;
                    banner.frameAnim.frameHover(nextOffer);
					banner.changeOfferZindex(nextOffer);
                    nextOffer = nextOffer === o.offersCount - 1 ? 0 : nextOffer + 1;
                }, banner.screensCount > 1 ? o.hoverAnimInterval / currentScreenOffers[currentScreen] * 3 : o.hoverAnimInterval);
            },
			frameHover: function(id){
				e.borders.removeClass('offer-jumping-frame');
				if(id==-1) return;
				if(!e.offer[id].border) e.offer[id].border = $(e.offer[id]).find('.border-container');
				e.offer[id].border.addClass('offer-jumping-frame');
			},
            stop: function () {
                e.banner.removeClass('hover-anim');
                banner.frameAnim.frameHover(-1);
                clearTimeout(autoFrameAnim);
            }
        },
		changeOfferZindex: function (nr) {
			for (var i = 0; i < o.offersCount; i++) {
				$(e.offer[i]).css('z-index', i === nr ? 100 : i);
			}
		},
		initCanvases: function(){
			if (!$(e.offer[0]).find('canvas')) return;
			for (var i = 0; i < o.offersCount; i++) {
				canvases[i] = $($(e.offer[i]).find('canvas'));
			}
		},
		addChangeZoomEvent: function(){
			$(window).resize(
				function(){
					if(canvases.length===0 || currentZoom==window.devicePixelRatio) return;
					currentZoom = window.devicePixelRatio;
					for(var i = 0; i<canvases.length; i++){
						canvases[i].css('image-rendering',currentZoom===1?'pixelated':'auto');
					}
				}
			);
		},
		customClickTracking: function(){
		    var _ = this;
		    $('.custom-tracking-link').on('click', function(e){
		      if($(e.currentTarget).hasClass('offer-enlarger-link')){
		          if((offers[banner.flags.currentOffer].trackingClickCount<Number(customClickTracking.offerTrackingLimit)||customClickTracking.offerTrackingLimit==-1)&&
		            (customClickTracking.globalTrackingCounter<Number(customClickTracking.globalTrackingLimit)||customClickTracking.globalTrackingLimit==-1)){
		                _.countAndTrack(banner.flags.currentOffer, e.currentTarget.dataset.trackingurl)
		          }
		      }else if($(e.currentTarget).hasClass('banner-clickholder')){
		          if((customClickTracking.globalTrackingCounter<Number(customClickTracking.globalTrackingLimit)||customClickTracking.globalTrackingLimit==-1)){
		              _.countAndTrack(false, e.currentTarget.dataset.trackingurl)
		          }
		      }else{
		          if((offers[e.currentTarget.dataset.id].trackingClickCount<Number(customClickTracking.offerTrackingLimit)||customClickTracking.offerTrackingLimit==-1)&&
		            (customClickTracking.globalTrackingCounter<Number(customClickTracking.globalTrackingLimit)||customClickTracking.globalTrackingLimit==-1)){
		                _.countAndTrack(e.currentTarget.dataset.id, e.currentTarget.dataset.trackingurl)
		          }
		      }
		    })
		},
		countAndTrack: function(id, url){
		    customClickTracking.globalTrackingCounter++;
		    if(id){
		        offers[id].trackingClickCount++;
		    }
	        var img = document.createElement("img");
            img.setAttribute("src", url);
		}
    };
	