AICMedia.PortfolioPage = {

	loaded: false,

	initialize: function() {
		if ( !this.loaded ) {
            var objPortfolioPage = this;
			this.menu = $('#portfolio-menu');
			this.holders = this.menu.find('.holder');
			this.menu.find('a').each(function() {
                var $p = $(this);
                var $ha = objPortfolioPage.getHoverAreaByPointer($p);
                $ha.hover(function(event) {
                    event.target = $p[0];
                    objPortfolioPage.onMouseEnter(event);
                }, function(event) {
                    event.target = $p[0];
                    objPortfolioPage.onMouseLeave(event);
                }).attr('href', $p.attr('href'));
            });
			this.loaded = true;
		}
		this.holders.css('margin-left', '-100%');
	},

	onMouseEnter: function(e) {
		var target = $(e.target);
		var col = $(target).closest('.col');
        if (!col.hasClass('active')) {
            var holder = $(col).find('.holder');
            holder.stop().animate({ marginLeft: 0 }, 300);
            col.addClass('active');
            this.menu.find('.label_'+holder.find('span').text()+':first').show('drop', { direction: 'right' });
        }
	},

	onMouseLeave: function(e) {
		var target = $(e.target);
		var col = $(target).closest('.col');
        if (col.hasClass('active')) {
            var holder = $(col).find('.holder');
            holder.stop().animate({ marginLeft: -$(holder).width() }, 300);
            col.removeClass('active');
            this.menu.find('.label_'+holder.find('span').text()+':first').stop(false, true).hide();
        }
	},

    getHoverAreaByPointer: function(p) {
		var col = $(p).closest('.col');
		var holder = $(col).find('.holder');
		return this.menu.find('.hover-area_'+holder.find('span').text()+':first');
    }
};

var initImageCarousel = function() {
    var $frame = AICMedia.PageLoader.currentFrame;

    if (!$frame.find('.b-scroller .image-carousel').length) {
        return;
    }

     if ($frame.find('.b-scroller.b-scroller_loaded').length) {
         //var $carousel = $frame.find('.j-carousel').data('jcarousel');
         return;
     }

    var HOVER_DURATION = 250;
    var SLIDE_DURATION = 400;
    var $carousel = $frame.find('.j-carousel');
    var imgSize = !AICMedia.mini ? {
        width: 465,
        height: 380
    } : {
        width: 428,
        height: 350
    };

    var mOver = function() {
        var $desc = $('.description', this);
        $desc.css({
            display: 'block',
            height: 0
        }).stop().animate({height: $desc[0].defaultHeight}, HOVER_DURATION);
    };

    var mOut = function() {
        var $desc = $('.description', this);
        $desc.stop().animate({height: 0}, HOVER_DURATION, function() {
            $(this).css({
                display: 'none',
                height: $desc[0].defaultHeight
            });
        });
    };

    $carousel.jcarousel({
        buttonNextHTML: null,
        buttonPrevHTML: null,
        animation: SLIDE_DURATION,
        scroll: 1,
        initCallback: function(carousel) {
            carousel.funcResize = null;

            carousel.list.find('.preview').each(function(index) {
                var $preview = $(this);
                var $desc = $preview.find('.description');
                $desc[0].defaultHeight = $desc.height();
                $preview.find('> a.holder').click(function(event) {
                    if (carousel.first != index + 1) {
                        carousel.scroll(index + 1);
                        event.preventDefault();
                    } else if ($desc.is('a')) {
                        $desc.click();
                        event.preventDefault();
                    }
                });

            }).filter(':gt(0)').css({
                height: imgSize.height * 0.75,
                width: imgSize.width * 0.75,
                marginTop: imgSize.height * 0.125
            });
            carousel.list.find('.preview:first').css({
                height: imgSize.height,
                width: imgSize.width
            });
        },

        itemFirstInCallback: {
            onBeforeAnimation: function(carousel, li, index) {
                $('.preview', li).hover(mOver, mOut).animate({
                    height: imgSize.height,
                    width: imgSize.width,
                    marginTop: 0
                }, SLIDE_DURATION);
                if (index == 1 && index == carousel.list.find('> li').length) {
                    AICMedia.SideArrows.setState('none');
                } else if (index == 1) {
                    AICMedia.SideArrows.setState('right');
                } else if (index == carousel.list.find('> li').length) {
                    AICMedia.SideArrows.setState('left');
                } else {
                    AICMedia.SideArrows.setState('both');
                }
            },

            onAfterAnimation: $.proxy(function(carousel, li, index) {
                this.currentPage = index;
                $('div.text', li).fadeIn();
            }, this)
        },

        itemFirstOutCallback: {
            onBeforeAnimation: function(carousel, li) {
                $('.preview', li).unbind('mouseenter', mOver).unbind('mouseleave', mOut).animate({
                    height: imgSize.height * 0.75,
                    width: imgSize.width * 0.75,
                    marginTop: imgSize.height * 0.1
                }, SLIDE_DURATION);
                $('div.text', li).fadeOut();
            }
        },

        itemVisibleInCallback: {
            onBeforeAnimation: function(carousel, li, index) {
                carousel.list.find('li:gt(' + Math.max(index - 3, 0) + '):lt(' + (index + 1) + ') .preview img[srcOnDemand], li:first .preview img[srcOnDemand]').each(function() {
                    var $img = $(this);
                    $img.load(function() {
                        $(this).closest('.preview').find('.loader').fadeTo(300, 0);
                    });
                    $img.attr('src', $img.attr('srcOnDemand'));
                    $img.removeAttr('srcOnDemand');
                });
            }
        }
    });
    if ($frame.hasClass('b-projects-list')) {
        var h = $carousel.find('li').height();
        if (!AICMedia.mini) {
            $frame.filter('.b-projects-list').find('.b-scroller').css({
                height: h,
                top: '50%',
                marginTop: '-' + (h / 2 - 40) + 'px'
            });
        } else {
            $frame.filter('.b-projects-list').find('.b-scroller').css({
                height: h,
                top: '32%',
                marginTop: '-' + (h / 2 - 149) + 'px'
            });
        }
    } else {
        $carousel.height($carousel.height());
    }

    $('.filter ul.level-1 li a').append('<div class="bg"><span class="l"></span><span class="r"></span></div>');

    $frame.find('.b-scroller').addClass('b-scroller_loaded');
};

AICMedia.PortfolioProjects = {
    initModeText: function() {
        var $frame = AICMedia.PageLoader.currentFrame;

        if (!$frame.hasClass('b-projects-list') || !$frame.find('.b-inner-menu .mode .text.active').length || $frame.hasClass('b-projects-list_loaded')) {
            return;
        }

        AICMedia.PageLoader.currentFrame.find('.scroll-line').each(function() {
            var $this = $(this);
            var $aList = $(this).find('span.project').closest('a');

            var maxHeight = $(window).height() - $this.offset().top - (AICMedia.mini ? 150 : 200);
            var aHeight = $aList.height();
            var aInCol = Math.floor(maxHeight / aHeight);

            var i = 0;
            while($aList.slice(aInCol * i, aInCol * (1 + i++)).wrapAll('<li class="item">').length);
        });

        $('.filter ul.level-1 li a').append('<div class="bg"><span class="l"></span><span class="r"></span></div>');

        $frame.addClass('b-projects-list_loaded');
    },

    initModePreview: function() {
        if (AICMedia.PageLoader.currentFrame.hasClass('b-projects-list')) {
            initImageCarousel();
        }
    }
};

AICMedia.PortfolioCard = {
    $frame: null,
    lightboxImages: null,
    currentPage: 1,
    updateInterface: true,
    backLink: null,

    initialize: function() {
        this.$frame = AICMedia.PageLoader.currentFrame;

        this.initScroller();
        this.initLightbox();
    },

    onStart: function() {
        AICMedia.PortfolioCard.initialize();
        if ($('.frame.prev-page, .frame.cur-page').filter('#project-frame').length == 2) {
            this.updateInterface = false;
        } else {
            this.updateInterface = true;
        }
    },

    onComplete: function() {
        if (this.updateInterface) {
            AICMedia.TopMenu.hide();
            AICMedia.Footer.dropHide();
        }

        AICMedia.PortfolioCard.showBackButton();
        AICMedia.PortfolioCard.showFooter();
        $('body').addClass('project');
    },

    onLoadNext: function() {
        AICMedia.PortfolioCard.hideBackButton();
        AICMedia.PortfolioCard.hideFooter();
    },

    onCompleteNext: function() {
        if (this.updateInterface || !$('.frame.cur-page').is('#project-frame')) {
            AICMedia.TopMenu.show();
            AICMedia.MainMenu.updateBGPosition();
            AICMedia.Footer.dropShow();
            $('body').removeClass('project');
        }
    },

    showBackButton: function() {
        setTimeout($.proxy(function() {
            var $img = AICMedia.PageLoader.currentFrame.find('.header img.back');
            var imgTop = -84;
            $img.css({
                display: 'block',
                top: (imgTop * 2) + 'px',
                opacity: 0
            }).animate({
                top: (imgTop - 10) + 'px',
                opacity: 1
            }, 300);
            $img.hover(function() {
                if (!AICMedia.PageLoader.animationInProcess) {
                    $img.stop().animate({top: imgTop + 'px'}, 200);
                }
            }, function() {
                if (!AICMedia.PageLoader.animationInProcess) {
                    $img.stop().animate({top: (imgTop - 10) + 'px'}, 200);
                }
            });
            if (AICMedia.PageLoader.prevPage) {
                if (this.updateInterface) {
                    this.backLink = '#' + AICMedia.PageLoader.prevPage;
                }
                $img.closest('a').attr('href', this.backLink);
            } else {
                this.backLink = $img.closest('a').attr('href');
            }
        }, this), this.updateInterface ? 500 : 0);
    },

    hideBackButton: function() {
        var imgTop = -84;
        $('.frame.prev-page .header img.back').animate({
            top: (imgTop * 2) + 'px',
            opacity: 0
        }, 300, function() {
            $(this).css({display: 'none'});
        });
    },

    showFooter: function() {
        setTimeout($.proxy(function() {
            $('#project-frame .footer').slideDown(300);
        }, this), this.updateInterface ? 500 : 0);
    },

    hideFooter: function() {
        $('.prev-page .footer').slideUp(300);
    },

    initScroller: initImageCarousel,

    initLightbox: function() {
        this.lightboxImages = [];
        this.$frame.find('.j-carousel .description').each($.proxy(function(index, el) {
            this.lightboxImages.push($(el).attr('href'));
        }, this)).click($.proxy(function(event) {
            this.showFullscreen();
            event.preventDefault();
        }, this));
        this.maxPage = this.lightboxImages.length;
    },

    showFullscreen: function() {
		AICMedia.TransparentBackdrop.show();
		this.overlay = $('#fullscreen-overlay').click($.proxy(function(event) {
            if (!$(event.target).filter('img').length) {
                this.hideFullscreen();
            }
        }, this));
		$(document.body).append(this.overlay);
		AICMedia.ie8 ? this.overlay.show() : this.overlay.fadeIn();
        this.preloader = this.overlay.find('.preloader');
        this.wrap = this.overlay.find('.wrap');
		this.fullscreenImage = this.wrap.find('.image').load($.proxy(function() {
            this.wrap.show('fade', $.proxy(function() {
                this.preloader.hide();
            }, this));
        }, this));
		this.leftControl = this.overlay.find('.left');
		this.rightControl = this.overlay.find('.right');
		this.fullscreenPage = null;
		this.setFullscreenPage(this.currentPage);
	},

	hideFullscreen: function() {
        this.overlay.fadeOut(AICMedia.ie8 ? 0 : 'normal', function() {
            AICMedia.PortfolioCard.fullscreenImage.attr('src', '');
            AICMedia.PageLoader.currentFrame.append($(this).detach());
		    AICMedia.TransparentBackdrop.hide();
        });
	},

	prevFullscreen: function() {
		if ( 0 != this.fullscreenPage - 1 ) this.setFullscreenPage(this.fullscreenPage - 1);

	},

	nextFullscreen: function() {
		if ( this.fullscreenPage + 1 <= this.maxPage  ) this.setFullscreenPage(this.fullscreenPage + 1);

	},

    showPreloader: function() {
        setTimeout($.proxy(function() {
            if (!this.wrap.is(':visible')) {
                this.preloader.show();
            }
        }, this), 50);
    },

	setFullscreenPage: function(id) {
		if ( this.fullscreenPage ) {
			    this.wrap.hide('fade', $.proxy(function(){
				this.fullscreenImage.attr('src', this.lightboxImages[id-1]);
				this.showPreloader();
			}, this));
		} else {
            this.wrap.hide();
            this.fullscreenImage.attr('src', this.lightboxImages[id-1]);
            this.showPreloader();
        }
		this.fullscreenPage = id;
		this.leftControl.show();
		this.rightControl.show();
		if ( this.fullscreenPage + 1 > this.maxPage ) {
			this.rightControl.hide();
		}
		if ( this.fullscreenPage - 1 == 0 ) {
			this.leftControl.hide();
		}
	}
};
