var lib = {
    $wrapper: null,
    $preloader: null,

    oImageRotator: null,

    easeOut: 'easeOutQuad',
    easeIn: 'easeInQuad',
    easeInOut: 'easeInOutQuad',
	
	// browser support
	IECrap : null,
	
    init: function () {
        lib.$wrapper = $('body > div.wrapper');
        lib.$preloader = $('#preloader');
		
		lib.IECrap = $.browser.msie && Number($.browser.version.substr(0,1)) < 8 ? true : false;	
    },
	
	wall : 
	{
		aFancyTriggers: null,
		aBoxes : null,
		nBoxOuterWidth : 0,
		nBoxWidth : 0,
		nBoxHeight : 0,
		nBoxRatio : null,
		nCounter : 0,
		nTotalImages : 0,
			
		init : function()
		{
			lib.wall.aBoxes = lib.$wrapper.find('div.box');
			lib.wall.aFancyTriggers = lib.wall.aBoxes.children('a');
			
			// SET FANCYBOX TRIGGERS		   
            lib.wall.aFancyTriggers.fancybox({
                'overlayOpacity': 0.95,
                'overlayColor': '#000',
                'padding': 0,
                'speedIn': 500,
                'speedOut': 600,
				'centerOnScroll': true
             })
								
			lib.wall.aBoxes.bind('mouseup', function(ev)
			{
				var _this = $(this);
				
				if(_this.hasClass('image'))
				{
					lib.wall.aFancyTriggers.eq(_this.index()).trigger('click');	
				}					 
								 
				 return false;				  
			})
			.filter(function(){ return $(this).hasClass('image') == true})
			.each(function(index, element)
			{
				lib.wall.loadImg($(this))	
			})
			.find('.over')
			.bind('mouseover mouseenter', function()
			{						 
				 $(this).stop().animate({'opacity':0},300,lib.easeOut);							 
			})
			.bind('mouseout mouseleave', function()
			{
				  $(this).stop().animate({'opacity':0.5},300,lib.easeOut)
			})							
					
					   
			var _first = lib.wall.aBoxes.eq(0);
			lib.wall.nBoxOuterWidth = _first.outerWidth();
			lib.wall.nBoxWidth = _first.width();
			lib.wall.nBoxHeight = _first.outerHeight();	
			lib.wall.nBoxRatio = lib.wall.nBoxHeight/lib.wall.nBoxWidth;
			
			lib.wall.nTotalImages = lib.wall.aBoxes.filter(function(){ return $(this).hasClass('image') == true}).length;
					
			lib.wall.setGrid()
		},
		
		loadImg : function(loader)
		{
			var img = new Image();
			
			img = new Image();			
			img.alt = loader.attr('data-url');
								
			$(img)
			.hide()
			.load(function(){								      
		 
				loader.find('.preloader').animate({'opacity':0},1000,lib.easeInOut, function(){ $(this).remove();})
				loader.find('.image-holder').html($(this))
				
				$(this).show().css('opacity',0).animate({'opacity':1},1000,lib.easeInOut)
				
				lib.wall.nCounter ++;
							
				if(lib.wall.nCounter == lib.wall.nTotalImages || lib.wall.nCounter%10 == 0) // all images loaded, set the grid
				{
					lib.wall.setGrid()	
				}								
															
			})
			.error(function(error)
			{ 	
				//loader.text(loader.attr('data-url'))						
			 })
			.attr('src', loader.attr('data-url'));
		},
		
		setGrid : function()
		{
			var nScope = $.Window.width()
			var nColumn = Math.floor(nScope/(lib.wall.nBoxWidth)-1);
			var nReminder = nScope - (nColumn * lib.wall.nBoxWidth);
			var nAddition = Math.abs(nReminder / nColumn);					
			var nTargetWidth = 0;
			var _this = null;
						
			lib.wall.aBoxes.each(function(index, element)
			{								
				nTargetWidth = (lib.wall.nBoxWidth + nAddition)-(lib.wall.nBoxOuterWidth - lib.wall.nBoxWidth);			
				
				_this  = $(this);					
				_this.css('width',nTargetWidth);	
				_this.css('height',(nTargetWidth * lib.wall.nBoxRatio));				
				
				if(_this.find('img').length > 0)
				{		
					var _img = 	_this.find('img');	
					var _imgHolder = _this.find('.image-holder');													
																			
					_imgHolder.css(
					{
						'top': (_this.outerHeight() - _img.height())/2,
						'left': (_this.outerWidth() - _img.width())/2
					});					
				}																
			})			
		}
	},

    profiler: // COVERS THE FUNCTIONALITY WITHIN THE PROFILE, EXHIBITIONS, PUBLICATIONS SECTIONS 
    {
        $profiler: null,

        init: function () {

            lib.profiler.$profiler = $('#profiler');


            lib.oImageRotator = new Slideshow(lib.profiler.$profiler, {
                autoRun: true,
                element: '.rotate',
                interval: 4000
            });

            // HIDE THE OVERFLOWING TEXT IF JS IS ON
            lib.profiler.$profiler.find('.right').css('overflow', 'hidden');

            // INITIALIZE SCROLLER
            lib.profiler.scroller();
        },


        scroller: function () {
            var $up = $('#scroller-up');
            var $down = $('#scroller-down');
            var $outer = lib.profiler.$profiler.find('div.right');
            var $inner = lib.profiler.$profiler.find('div.scroller');
            var int = 0;
            var nDifference = 0;
            var addOn = 0;
            var speed = 10;
            var snap = 5;

            $down.bind('mousedown', function (ev) {
                $(this).addClass('active')
                clearInterval(int);
                int = setInterval(function () {
                    if ((nDifference + addOn) > Math.abs(parseFloat($inner.css('top')))) {
                        $inner.css({
                            'top': (parseFloat($inner.css('top')) - snap) + 'px'
                        });
                    }

                }, speed)
            }).bind('mouseup', function (ev) {
                $(this).removeClass('active')
                clearInterval(int);

                handleControls()
            })

            $up.bind('mousedown', function (ev) {
                $(this).addClass('active')

                clearInterval(int);
                int = setInterval(function () {
                    if (parseFloat($inner.css('top')) < 0) {
                        $inner.css({
                            'top': (parseFloat($inner.css('top')) + snap) + 'px'
                        });
                    }

                }, speed)
            }).bind('mouseup', function (ev) {
                $(this).removeClass('active')
                clearInterval(int);
                handleControls()
            })

            if ($inner.outerHeight() > $outer.outerHeight()) {
                $down.show('slow');
                $up.show('slow');

                nDifference = $inner.outerHeight() - $outer.outerHeight();
                addOn = $outer.outerHeight() - $outer.height();

                handleControls()
            }


            function handleControls() {
                // TOP CONTROL
                parseFloat($inner.css('top')) < 0 ? $up.css({
                    'opacity': 1
                }) : $up.css({
                    'opacity': 0.3
                });

                // DOWN CONTROL
                Number(nDifference + addOn) > Math.abs(parseFloat($inner.css('top'))) ? $down.css({
                    'opacity': 1
                }) : $down.css({
                    'opacity': 0.3
                });
            }
        }
    },

    gallery: {
        aSlides: null,
        aFancyTriggers: null,
        controlLeft: null,
        controlRight: null,
        target: null,
        selectedIndex: 0,

        init: function () {
            lib.gallery.quickView();

            lib.gallery.target = lib.$wrapper.find('div.gallery');
            lib.gallery.aSlides = lib.gallery.target.find('.slide');
            lib.gallery.aFancyTriggers = lib.gallery.aSlides.find('a.fancy-trigger');
            lib.gallery.controlLeft = $('#control-left');
            lib.gallery.controlRight = $('#control-right');

            // SET TOOLTIPS
			if(!lib.IECrap)
			{
				 lib.gallery.controlLeft.tooltip();
           		 lib.gallery.controlRight.tooltip();	
			}	
			          

            // MAKE SURE THAT THE CONTENT IS VISIBLE WHEN JS IS OFF
            lib.gallery.target.css('overflow', 'hidden')

            lib.gallery.aSlides.find('.content').hover(
            function () {
				if(!lib.IECrap)
				{
					$(this).find('.over').show().css('opacity', 0).stop().animate({
						'opacity': 1
					}, 400, lib.easeOut)
				}
            }, function () {
				if(!lib.IECrap)
				{
					$(this).find('.over').stop().animate({
						'opacity': 0
					}, 200, lib.easeOut, function () {
						$(this).hide()
					})
				}
            }).bind('click', function (ev) {
                lib.gallery.aFancyTriggers.eq($(this).parents('.slide').index()).trigger('click');			
            }).end().css('position', 'absolute') // STACK SLIDES ON TOP OF EACH OTHER WHEN JS IS ON
			
            // SET FANCYBOX TRIGGERS		   
            lib.gallery.aFancyTriggers.fancybox({
                'overlayOpacity': 0.95,
                'overlayColor': '#000',
                'padding': 0,
                'speedIn': 500,
                'speedOut': 600,
				'onComplete'  : function(links, index)
				{
					lib.gallery.slider.goTo(index,true);				
				}
            })

            // SET CLICK HANDLERS TO SLIDER CONTROLS, 
            lib.gallery.controlLeft.bind('click', function (ev) 
			{
                lib.gallery.slider.prev();

            });
            lib.gallery.controlRight.bind('click', function (ev) 
			{
                lib.gallery.slider.next();
            });
			
			$(document).bind('keydown', function()
			{				
				switch(event.keyCode)
				{
					case 39: // RIGHT
						lib.gallery.slider.next();	
					break
					
					case 37 : // LEFT
						lib.gallery.slider.prev();
					break;
				}			
			});			

            lib.gallery.slider.init();
        },

        slider: {
            init: function () {
                lib.gallery.slider.handleControls()
                lib.gallery.aSlides.eq(lib.gallery.selectedIndex).css({
                    'opacity': 1,
                    'left': 0
                }).siblings().css({
                    'left': 10000 + 'px',
                    'opacity': 0
                })
            },
			
			next : function()
			{
				if (lib.gallery.selectedIndex < (lib.gallery.aSlides.length - 1)) {
                    lib.gallery.slider.goTo(Number(lib.gallery.selectedIndex + 1))
                }
			},
			
			prev : function()
			{
				if (lib.gallery.selectedIndex > 0) {
                    lib.gallery.slider.goTo(lib.gallery.selectedIndex - 1)
                }
			},

            goTo: function (slide, b) {
                if (lib.gallery.selectedIndex == slide) return false;

                if (slide > lib.gallery.selectedIndex) {
                    // animate OUT old one
                    lib.gallery.aSlides.eq(lib.gallery.selectedIndex)
					.stop().animate({
                        'left': ($.Window.width() * -1) + 'px',
                        'opacity': 0
                    }, !b ? 1000 : 10, lib.easeOut);

                    // animate IN new one		  
                    lib.gallery.aSlides.eq(slide).css({
                        'left': $.Window.width() + 'px'
                    }).stop().animate({
                        'left': 0,
                        'opacity': 1
                    }, !b ? 1000 : 10, lib.easeOut);

                } else {

                    // animate OUT old one
                    lib.gallery.aSlides.eq(lib.gallery.selectedIndex).stop().animate({
                        'left': ($.Window.width()) + 'px',
                        'opacity': 0
                    }, !b ? 1000 : 10, lib.easeOut);

                    // animate IN new one		  
                    lib.gallery.aSlides.eq(slide).css({
                        'left': $.Window.width() * -1 + 'px',
                        'opacity': 1
                    }).stop().animate({
                        'left': 0
                    }, !b ? 1000 : 10, lib.easeOut);

                }

                lib.gallery.selectedIndex = slide;
                lib.gallery.slider.handleControls()
            },

            handleControls: function () {
                // right control						
                lib.gallery.selectedIndex == (lib.gallery.aSlides.length - 1) ? lib.gallery.controlRight.fadeOut('slow') : lib.gallery.controlRight.fadeIn('slow')

                // left control	
                lib.gallery.selectedIndex == 0 ? lib.gallery.controlLeft.fadeOut('slow') : lib.gallery.controlLeft.fadeIn('slow');
            }
        },

        quickView: function () {
            var nExpanded = 55
            var nCollapsed = 12;
            var aSlides;


            var $quickView = $('#quick-view');
            $quickView.css('display', 'block').find('.trigger').css('display', 'block').end().bind('mouseenter', function (ev) {
                var _content = $(this).children('div.inner');

                if (_content.is(':hidden')) {
                    _content.slideDown(500);
                }
            }).bind('mouseleave', function (ev) {
                var _content = $(this).children('div.inner');

                if (!_content.is(':hidden')) {
                    _content.slideUp(500);
                }
            })

            aSlides = $quickView.find('.slide');
            aSlides.eq(Number(aSlides.length - 1)).css({
                'border-bottom': 'none',
                'height': nExpanded
            }).find('img').css('opacity', 1).end().siblings().css({
                'height': nCollapsed
            }).find('img').css('opacity', 0.3);


            aSlides.bind('mouseover', function (ev) {
                $(this).stop().animate({
                    height: nExpanded + 'px'
                }, 300).find('img').stop().animate({
                    opacity: 1
                }, 300).end().siblings().stop().animate({
                    height: nCollapsed + 'px'
                }, 300).find('img').stop().animate({
                    opacity: 0.3
                }, 300);
            }).bind('click', function (ev) {
                var _index = Number(lib.gallery.aSlides.length - $(this).index());

                lib.gallery.slider.goTo(_index - 1)
                ev.preventDefault();
            })
        }
    },

    intro: {
        aSource: [],
        selectedIndex: 0,
        isPaused: false,
        intID: 0,

        init: function () {
            var _aSource = lib.$wrapper.find('div.img');
            var obj = {}
            var _this;
            $.each(_aSource, function (index, element) {

                _this = $(this);
                obj = {};
                obj['loaded'] = false;
                obj['src'] = 'images/home/big/' + jQuery.trim(_this.attr('data-url'));
                obj['alt'] = jQuery.trim(_this.attr('data-alt'));
                obj['img'] = null;
                lib.intro.aSource.push(obj);

                _this.remove();
            })

            if (lib.intro.aSource.length > 0) {
                lib.intro.selectedIndex = Math.floor(Math.random() * (lib.intro.aSource.length));
                lib.intro.slide(lib.intro.selectedIndex);
                //if (!$.support.opacity) lib.intro.togglePause()
            }
        },

        togglePause: function () {
            if (lib.intro.isPaused) {
                lib.intro.isPaused = false;
                lib.intro.run(true);

            } else {
                lib.intro.isPaused = true;
                if (lib.intro.intID) clearTimeout(lib.intro.intID);
            }
        },

        run: function (b) {
            if (!lib.intro.isPaused) {
                if (lib.intro.intID) clearTimeout(lib.intro.intID);
                lib.intro.intID = setTimeout(function () {
                    lib.intro.slide()
                }, b == null || b == false ? 5000 : 2000);
            }
        },

        fadeIn: function (index) {
            var _new = lib.intro.aSource[index]['img'];
            var _old = lib.intro.aSource[lib.intro.selectedIndex]['img'];

            var _newTop = _new.css('top');
            var _oldTop = _old.css('top');

            if (lib.intro.selectedIndex != index) {
                _old.css('z-index', 1).stop(true).animate({
                    'opacity': 0
                }, 2000, lib.easeOut)
            }

            _new.css({
                'opacity': 0,
                'z-index': 2,
                'top': 50
            }).animate({
                opacity: 1,
                'top': _newTop
            }, 2000, lib.easeInOut, function () {
                lib.intro.run();
            });

            lib.intro.selectedIndex = index;
        },

        slide: function (index) {
            if (index == null) index = (lib.intro.selectedIndex + 1) % (lib.intro.aSource.length);

            var _obj = lib.intro.aSource[index];

            if (_obj) {
                if (_obj['loaded']) {
                    lib.intro.fadeIn(index);

                } else {

                    lib.utility.preloader.show();
                    lib.intro.loadImg(lib.$wrapper, _obj, index);
                }
            }
        },

        loadImg: function (holder, obj, num) {
            var img = new Image();
            var img_src = obj['src'];

            $(img).load(function () {
                var _img = $(this);
                holder.append(_img);

                lib.utility.preloader.hide();
                lib.intro.aSource[num]['img'] = _img;
                lib.intro.aSource[num]['loaded'] = true;
                lib.intro.resize()
                lib.intro.fadeIn(num);

            }).error(function () {
                lib.msgBoxInfo.show({
                    title: 'System Notification',
                    message: "There has been an error loading the requested image. "
                })
            }).attr('src', img_src)
        },

        resize: function () {

            var _array = lib.intro.aSource;
            var _length = _array.length;

            if (_length > 0) {
                for (var i = 0; i < _length; i++) {
                    if (_array[i].loaded) {
                        if (_array[i]['img'].is(':animated')) {
                            _array[i]['img'].stop(false, true);
                        }

                        _array[i].img.fullscreen({
                            elementW: Number(_array[i].img.width()),
                            elementH: Number(_array[i].img.height()),
                            target: lib.$wrapper
                        })
                    }
                }
            }
        }
    },

    utility: {
        preloader: {
            hide: function () {
                lib.$preloader.stop(false, true).animate({
                    'opacity': 0
                }, 250, lib.easeIn, function () {
                    $(this).hide()
                })
            },

            show: function () {
                lib.$preloader.show().css('opacity', 0).stop(false, true).animate({
                    'opacity': 1
                }, 350, lib.easeOut)
            }
        }
    }

}
