jQuery(document).ready(function(){
	jQuery('div.gallery').gallery({
		duration: 500,
		listOfSlides: 'li'
	});
	$('.masonry ').masonry({
		resizeable: true
	});
});

(function($) {
	$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };
	
	function Gallery(context, options) { this.init(context, options); };
	
	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				duration: 700,
				slideElement: 1,
				autoRotation: false,
				effect: false,
				listOfSlides: 'ul > li',
				switcher: false,
				disableBtn: false,
				nextBtn: 'a.link-next, a.btn-next, a.next',
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',
				circle: true,
				direction: false,
				event: 'click',
				IE: false
			}, options || {});
			var _el = $(context).find(this.options.listOfSlides);
			if (this.options.effect) this.list = _el;
			else this.list = _el.parent();
			this.switcher = $(context).find(this.options.switcher);
			this.nextBtn = $(context).find(this.options.nextBtn);
			this.prevBtn = $(context).find(this.options.prevBtn);
			this.count = _el.index(_el.filter(':last'));
			
			if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
			else this.active = _el.index(_el.filter('.active:eq(0)'));
			if (this.active < 0) this.active = 0;
			this.last = this.active;
			
			this.woh = _el.outerWidth(true);
			if (!this.options.direction) this.installDirections(this.list.parent().width());
			else {
				this.woh = _el.outerHeight(true);
				this.installDirections(this.list.parent().height());
			}
			
			if (!this.options.effect) {
				this.rew = this.count - this.wrapHolderW + 1;
				if (!this.options.direction) this.list.css({marginLeft: -(this.woh * this.active)});
				else this.list.css({marginTop: -(this.woh * this.active)});
			}
			else {
				this.rew = this.count;
				this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
				this.switcher.removeClass('active').eq(this.active).addClass('active');
			}
			
			if (this.options.disableBtn) {
				if (this.count < this.wrapHolderW) this.nextBtn.addClass(this.options.disableBtn);
				if (this.active == 0) this.prevBtn.addClass(this.options.disableBtn);
			}
			
			this.initEvent(this, this.nextBtn, this.prevBtn, true);
			this.initEvent(this, this.prevBtn, this.nextBtn, false);
			
			if (this.options.autoRotation) this.runTimer(this);
			
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
		},
		installDirections: function(temp){
			this.wrapHolderW = Math.ceil(temp / this.woh);
			if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderWwrapHolderW--;
		},
		fadeElement: function(){
			if ($.browser.msie && this.options.IE){
				this.list.eq(this.last).css({opacity:0});
				this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
			}
			else{
				this.list.eq(this.last).animate({opacity:0}, {queue:false, duration: this.options.duration});
				this.list.removeClass('active').eq(this.active).addClass('active').animate({
					opacity:1
				}, {queue:false, duration: this.options.duration, complete: function(){
					$(this).css('opacity','auto');
				}});
			}
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function(){
			if (!this.options.direction) this.list.animate({marginLeft: -(this.woh * this.active)}, {queue:false, duration: this.options.duration});
			else this.list.animate({marginTop: -(this.woh * this.active)}, {queue:false, duration: this.options.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			$this._t = setInterval(function(){
				$this.toPrepare($this, true);
			}, this.options.autoRotation);
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(){
				$this.active = $this.switcher.index($(this));
				if($this._t) clearTimeout($this._t);
				if (!$this.options.effect) $this.scrollElement();
				else $this.fadeElement();
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		initEvent: function($this, addEventEl, addDisClass, dir){
			addEventEl.bind($this.options.event, function(){
				if($this._t) clearTimeout($this._t);
				if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) addDisClass.removeClass($this.options.disableBtn);
				$this.toPrepare($this, dir);
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		toPrepare: function($this, side){
			if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
			if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
			for (var i = 0; i < $this.options.slideElement; i++){
				if (side) {
					if ($this.active + 1 > $this.rew) {
						if ($this.options.disableBtn && ($this.count > $this.wrapHolderW)) $this.nextBtn.addClass($this.options.disableBtn);
					}
					else $this.active++;
				}
				else{
					if ($this.active - 1 < 0) {
						if ($this.options.disableBtn && ($this.count > $this.wrapHolderW)) $this.prevBtn.addClass($this.options.disableBtn);
					}
					else $this.active--;
				}
			};
			if ($this.active == $this.rew && side) if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) $this.nextBtn.addClass($this.options.disableBtn);
			if ($this.active == 0 && !side) if ($this.options.disableBtn &&($this.count > $this.wrapHolderW)) $this.prevBtn.addClass($this.options.disableBtn);
			if (!$this.options.effect) $this.scrollElement();
			else $this.fadeElement();
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this._t) clearTimeout(this._t);
			if (this.options.autoRotation) this.runTimer(this);
		}
	}
}(jQuery));









/*************************************************
**  jQuery Masonry version 1.0.1
**  copyright David DeSandro, licensed GPL & MIT
**  http://desandro.com/resources/jquery-masonry
**************************************************/
var _load = true;
;(function($){  

$.fn.masonry = function(options, callback) { 

    function placeBrick($brick, setCount, setY, setSpan, props) {
        var shortCol = 0;
        
        for ( i=0; i < setCount; i++ ) {
            if ( setY[i] < setY[ shortCol ] ) shortCol = i;
        }

        if (_load) {
            _load = false;
            $brick.css({
                top: setY[ shortCol ],
                left: props.colW * shortCol + props.posLeft
            });
        } else {
            $brick.animate({
                top: setY[ shortCol ],
                left: props.colW * shortCol + props.posLeft
            }, {duration:1000});
        }

        for ( i=0; i < setSpan; i++ ) {
            props.colY[ shortCol + i ] = setY[ shortCol ] + $brick.outerHeight(true) ;
        }
    }


    function masonrySetup($wall, opts, props) {
        props.$bricks = opts.itemSelector == undefined ?
                    opts.$brickParent.children() :
                    opts.$brickParent.find(opts.itemSelector);

        if ( opts.columnWidth == undefined) {
            props.colW = props.masoned ?
                    $wall.data('masonry').colW :
                    props.$bricks.outerWidth(true);
        } else {
            props.colW = opts.columnWidth;
        }

        props.colCount = Math.floor( $wall.width() / props.colW ) ;
        props.colCount = Math.max( props.colCount, 1 );
    }


    function masonryArrange($wall, opts, props) {
        // if masonry hasn't been called before
        if( !props.masoned ) $wall.css( 'position', 'relative' );            
        
        if ( !props.masoned || opts.appendedContent != undefined ) {
            // just the new bricks
            props.$bricks.css( 'position', 'absolute' );
        }

        // get top left position of where the bricks should be
        var cursor = $('<div />');
        $wall.prepend( cursor );
        props.posTop =  Math.round( cursor.position().top );
        props.posLeft = Math.round( cursor.position().left );
        cursor.remove();

        // set up column Y array
        if ( props.masoned && opts.appendedContent != undefined ) {
            // if appendedContent is set, use colY from last call
            props.colY = $wall.data('masonry').colY;
            
            /*
            *  in the case that the wall is not resizeable,
            *  but the colCount has changed from the previous time
            *  masonry has been called
            */
            for (i= $wall.data('masonry').colCount; i < props.colCount; i++) {
                props.colY[i] = props.posTop;
            };
            
        } else {
            props.colY = [];
            for ( i=0; i < props.colCount; i++) {
                props.colY[i] = props.posTop;
            }    
        }

        // layout logic
        if ( opts.singleMode ) {
            props.$bricks.each(function(){
                var $brick = $(this);
                placeBrick($brick, props.colCount, props.colY, 1, props);
            });            
        } else {
            props.$bricks.each(function() {
                var $brick = $(this);
            
                //how many columns does this brick span
                var colSpan = Math.ceil( $brick.outerWidth(true) / props.colW);
                colSpan = Math.min( colSpan, props.colCount );

                if ( colSpan == 1 ) {
                    // if brick spans only one column, just like singleMode
                    placeBrick($brick, props.colCount, props.colY, 1, props);
                } else {
                    // brick spans more than one column

                    //how many different places could this brick fit horizontally
                    var groupCount = props.colCount + 1 - colSpan; 
                    var groupY = [0];
                    // for each group potential horizontal position
                    for ( i=0; i < groupCount; i++ ) {
                        groupY[i] = 0;
                        // for each column in that group
                        for ( j=0; j < colSpan; j++ ) {
                            // get the maximum column height in that group
                            groupY[i] = Math.max( groupY[i], props.colY[i+j] );
                        }
                    }
            
                    placeBrick($brick, groupCount, groupY, colSpan, props);
                }
            }); //        /props.bricks.each(function() {
        }  //         /layout logic
    
        // set the height of the wall to the tallest column
        props.wallH = 0;
        for ( i=0; i < props.colCount; i++ ) {
            props.wallH = Math.max( props.wallH, props.colY[i] );
        }
        $wall.height( props.wallH - props.posTop );

        // provide props.bricks as context for the callback
        callback.call( props.$bricks );
        
        // set all data so we can retrieve it for appended appendedContent
        //        or anyone else's crazy jquery fun
        $wall.data('masonry', props );


    } //  /masonryArrange function


    function masonryResize($wall, opts, props) {
        var prevColCount = $wall.data('masonry').colCount;
        masonrySetup($wall, opts, props);
        if ( props.colCount != prevColCount ) masonryArrange($wall, opts, props); 
    }


    /*
    *  let's begin
    *  IN A WORLD...
    */
    return this.each(function() {  

        var $wall = $(this);

        var props = $.extend( {}, $.masonry );

        // checks if masonry has been called before on this object
        props.masoned = $wall.data('masonry') != undefined;
    
        var previousOptions = props.masoned ? $wall.data('masonry').options : {};

        var opts =  $.extend(
                        {},
                        props.defaults,
                        previousOptions,
                        options
                    );  

        // should we save these options for next time?
        props.options = opts.saveOptions ? opts : previousOptions;

        //picked up from Paul Irish
        callback = callback || function(){};

        if ( props.masoned && opts.appendedContent != undefined ) {
            // if we're dealing with appendedContent
            opts.$brickParent = opts.appendedContent;
        } else {
            opts.$brickParent = $wall;
        }
        
        if ( opts.$brickParent.children().length > 0  ) {
            // call masonry layout
            masonrySetup($wall, opts, props);
            masonryArrange($wall, opts, props);
        
            // binding window resizing
            var resizeOn = previousOptions.resizeable;
            if ( !resizeOn && opts.resizeable ) {
                $(window).bind('resize.masonry', function() { masonryResize($wall, opts, props); } );
            }
            if ( resizeOn && !opts.resizeable ) $(window).unbind('resize.masonry');
        } else {
            // brickParent is empty, do nothing, go back home and eat chips
            return this;
        }

    });        //        /return this.each(function()
};            //        /$.fn.masonry = function(options)



$.masonry = {
    defaults : {
        singleMode: false,
        columnWidth: undefined,
        itemSelector: undefined,
        appendedContent: undefined,
        saveOptions: true,
        resizeable: true
    },
    colW: undefined,
    colCount: undefined,
    colY: undefined,
    wallH: undefined,
    masoned: undefined,
    posTop: 0,
    posLeft: 0,
    options: undefined,
    $bricks: undefined,
    $brickParent: undefined
};

})(jQuery);
