/*
 * simplyScroll 1.0.4 - a scroll-tastic jQuery plugin
 *
 * http://logicbox.net/jquery/simplyscroll
 * http://logicbox.net/blog/simplyscroll-jquery-plugin
 * http://plugins.jquery.com/project/simplyScroll
 *
 * Copyright (c) 2009 Will Kelly - http://logicbox.net
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Last revised: 03/07/2009 21:13
 *
 */

(function($) {

$.fn.simplyScroll = function(o) {
    return this.each(function() {
        new $.simplyScroll(this,o);
    });
};

var defaults = {
    className: 'simply-scroll',
    frameRate: 24, //No of movements per second
    speed: 1, //No of pixels per frame
    horizontal: true,
    autoMode: 'off', //disables buttons 'loop','bounce'
    loop: false,
    pauseOnHover: true,
    startOnLoad: false, //use this if having rendering problems (safari 3 + Mac OSX?)
    localJsonSource: '', //format [{"src":"images/pic.jpg","title":"title","link":"http://"},{etc..}]
    flickrFeed: '',
    jsonImgWidth: 240,
    jsonImgHeight: 180
};
    
$.simplyScroll = function(el,o) {
    
    var self = this;
    
    this.o = $.extend({}, defaults, o || {});
    this.auto = this.o.autoMode!=="off" ? true : false;
    
    //called on ul/ol/div etc
    this.$list = $(el);
    
    
    
    //generate extra markup
    this.$list.addClass('simply-scroll-list')
        .wrap('<div class="simply-scroll-clip"></div>')
        .parent().wrap('<div class="' + this.o.className + ' simply-scroll-container"></div>');
    
    if (!this.o.auto) { //button placeholders
        this.$list.parent().parent()
        .prepend('<div class="simply-scroll-forward"></div>')
        .prepend('<div class="simply-scroll-back"></div>');
    }
    
    //load image data
    if (this.o.flickrFeed) {
        $.getJSON(this.o.flickrFeed + "&format=json&jsoncallback=?",
            function(data) {
                json = [];
                $.each(data.items, function(i,item) {
                    json.push({
                        "src": item.media.m,
                        "title": item.title,
                        "link": item.link
                    });
                });
                self.renderData(json);
            }
        );
    } else if (this.o.localJsonSource) {
        $.getJSON(this.o.localJsonSource,
            function(json) {
                self.renderData(json);
            }
        );
    } else {
        
        if (!this.o.startOnLoad) {
            this.init();
        } else {
            //wait for load before completing setup
            $(window).load(function() { self.init();  });
        }
        
    }
        
};
    
$.simplyScroll.fn = $.simplyScroll.prototype = {};

$.simplyScroll.fn.extend = $.simplyScroll.extend = $.extend;

$.simplyScroll.fn.extend({
    init: function() {
        //shortcuts
        this.$items = this.$list.children();
        this.$clip = this.$list.parent();
        this.$container = this.$clip.parent();
        this.current = 1;
        this.$btn_next       = $('#fp_next');
        this.$btn_prev       = $('#fp_prev');


        if (!this.o.horizontal) {
            this.itemMax = this.$items.eq(0).outerHeight(true); 
            this.clipMax = this.$clip.height();
            this.dimension = 'height';          
            this.moveBackClass = 'simply-scroll-btn-up';
            this.moveForwardClass = 'simply-scroll-btn-down';
        } else {
            this.itemMax = this.$items.eq(0).outerWidth(true);
            if(!this.o.width) {
                this.clipMax = this.$clip.width();          
            }
            else {
                this.clipMax = this.o.width;
            }
            this.dimension = 'width';
            this.moveBackClass = 'simply-scroll-btn-left';
            this.moveForwardClass = 'simply-scroll-btn-right';
        }
        
        $(window).resize($.proxy(function(){
            //console.log("resizing");
            //console.log(this);
            //this.init();
            this.o.width = $("#outer_container").outerWidth(true);
            //console.log(this.o.width);
            $(".simply-scroll").css('width', this.o.width);
            $(".simply-scroll .simply-scroll-clip").css('width', this.o.width);
            /*var img = Math.ceil((this.$clip[0].scrollLeft) / this.itemMax);//alert(this.$clip[0].scrollLeft+"#"+0+"#"+this.itemMax+"#"+img);
            var center = (img*this.itemMax  - (this.$clip.width() / 2) - 10 + (this.itemMax/2))-170 ;
            this.$clip.stop().animate({"scrollLeft" : center}, "fast");*/
        },this));
        
        $(document).mousemove(function(e){
                window.mouseXPos = e.pageX;
                window.mouseYPos = e.pageY;
        });

        this.posMin = 0;
        
        /* 
        IMPORTANT: The script assumes multiple elements within a list are the same width or height 
        to work out how many extra elements to generate to simulate the loop. 
        
        If you want this script to work with unequal sized elements don't modify the next line 
        to do this:
        
        this.$items.each(function() {
            self.posMax += !this.o.horizontal ? $(this).outerHeight(true) : $(this).outerWidth(true);
        });
        
        as it will cause white-space and a jump to appear when elements have wildly different dimensions
        See: http://logicbox.net/jquery/simplyscroll/test_unequalelements.html
        
        Instead simply add an extra wrapper element around your list and init simplyScroll on that, 
        essentially scrolling just one element. Less efficient but it does the job!
        
        */
        $(".simply-scroll").css('width', this.o.width);
        $(".simply-scroll .simply-scroll-clip").css('width', this.o.width);
        this.posMax = this.$items.length * this.itemMax;
        this.$loader = $("#fp_loading");        

        this.$list.css(this.dimension,this.posMax +'px');
        this.itemTotal = this.$items.length;
        
        if (this.o.autoMode=='loop' || this.o.loop==true) {
            this.addItems = Math.ceil(this.clipMax / this.itemMax); //alert(this.clipMax);alert(this.itemMax);alert(this.addItems);
            this.posMax = (this.addItems+this.$items.length) * this.itemMax;
            var endItems = this.$items.slice(0,this.addItems).clone(true);
            var startItems = this.$items.slice(this.itemTotal-this.addItems, this.itemTotal).clone(true);
            startItems.prependTo(this.$list);
            endItems.appendTo(this.$list);
            this.posMax += (this.clipMax - this.o.speed);
            this.$list.css(this.dimension,this.posMax+(this.itemMax*this.addItems*2) +'px');
            this.$clip[0].scrollLeft = this.itemMax*this.addItems;
        }
        
        this.interval = null;   
        this.intervalDelay = Math.floor(1000 / this.o.frameRate);
        
        //ensure that speed is divisible by item width
        while (this.itemMax % this.o.speed !== 0) {
            this.o.speed--;
            if (this.o.speed===0) {
                this.o.speed=1; break;  
            }
        }
        var self = this;
        this.trigger = null;
        this.funcMoveBack = function() { self.trigger=this;self.moveBack(); };
        this.funcMoveForward = function() { self.trigger=this;self.moveForward(); };
        this.funcMoveStop = function() { self.moveStop(); };
        this.funcMoveResume = function() { self.moveResume(); };
        this.funcMoveMouse = function() { self.moveMouse(); }
        this.funcShowNext = function() { self.showNext(); }
        this.funcShowPrev = function() { self.showPrev(); }

        var that = this;
        this.$clip.find("ul > li > img").mousedown(function(e){
            that.moveStop();
            that.movement = "animating";
        });
        this.$clip.find("ul > li > img").mouseup(function(e){
            that.movement = "animating";
            that.centerImage(e.pageX);
        });
        
        this.o.mouseMove=true;
        var middle = this.$clip.width() / 2;
        this.leftStart = middle - (this.itemMax/2);
        this.rightStart = middle + (this.itemMax/2);
        var that = this;
        //console.log(this);
        if (this.o.mouseMove) {
            this.$clip.hover(function() { that.movement = 'stoped'}, function() { clearInterval(that.interval); that.movement='stoped'; });
            this.$clip.mousemove(function(e) {
                if( that.movement == 'animating' || that.movement == 'halted') {
                    return;
                }
                that.mouseCoords=e.pageX-(document.body.clientWidth-middle*2)/2;//alert(that.mouseCoords);alert(that.leftStart);
                if( that.mouseCoords < that.leftStart ) {
                    if(that.interval!=undefined && that.movement=='back') {
                        return;
                    }
                    that.movement = 'back';
                    clearInterval(that.interval);
                    that.interval = setInterval(function() {
                    if (that.o.horizontal && that.$clip[0].scrollLeft>0) {
                            that.$clip[0].scrollLeft -= that.o.speed;
    var img = Math.ceil((that.$clip[0].scrollLeft+window.mouseXPos) / that.itemMax);
    that.$clip.find('li').not('li:nth-child('+parseInt(img)+')').children("img").css("opacity", 0.6);
    that.$clip.find('li:nth-child('+parseInt(img)+')').children("img").css("opacity", 1);
                
                //$(that.$clip[0]).find("img").mousemove();
                        } else if (that.o.autoMode=='loop' || that.o.loop==true) {
                            that.resetPosBack();
                        }
                    },that.intervalDelay);
                }
                else if( that.mouseCoords > that.rightStart ) {
                    if(that.interval!=undefined && that.movement=='forward') {
                        return;
                    }
                    that.movement = 'forward';
                    clearInterval(that.interval);
                    that.interval = setInterval(function() {
                        if (that.o.horizontal && that.$clip[0].scrollLeft < (that.posMax-that.clipMax)) {
                            that.$clip[0].scrollLeft += that.o.speed;
    var img = Math.ceil((that.$clip[0].scrollLeft+window.mouseXPos) / that.itemMax);
    that.$clip.find('li').not('li:nth-child('+parseInt(img)+')').children("img").css("opacity", 0.6);
    that.$clip.find('li:nth-child('+parseInt(img)+')').children("img").css("opacity", 1);
    //console.log(img+" - " +window.mouseXPos);
                //$(that.$clip[0]).find("img").mousemove();
                        } else if (that.o.autoMode=='loop' || that.o.loop==true) {
                            that.resetPos();
                        }
                    },that.intervalDelay);
                }
                else {
                    that.movement='center';
                    clearInterval(that.interval);   
                }
            });
        }
        else if (this.auto) {
            if (this.o.pauseOnHover) {
                this.$clip.hover(this.funcMoveStop,this.funcMoveResume);
            }
            this.moveForward();
        } else {
            this.$btnBack = $('.simply-scroll-back',this.$container)
                .addClass('simply-scroll-btn' + ' ' + this.moveBackClass)
                .hover(this.funcMoveBack,this.funcMoveStop);
            this.$btnForward = $('.simply-scroll-forward',this.$container)
                .addClass('simply-scroll-btn' + ' ' + this.moveForwardClass)
                .hover(this.funcMoveForward,this.funcMoveStop);
        }
        this.$btn_next.bind('click',this.funcShowNext);
        this.$btn_prev.bind('click',this.funcShowPrev);

    },
    moveForward: function() {
        var self = this;
        this.movement = 'forward';
        if (this.trigger !== null) {
            this.$btnBack.removeClass('disabled');
        }
        self.interval = setInterval(function() {
            
            if (!self.o.horizontal && self.$clip[0].scrollTop < (self.posMax-self.clipMax)) {
                self.$clip[0].scrollTop += self.o.speed;
            } else if (self.o.horizontal && self.$clip[0].scrollLeft < (self.posMax-self.clipMax)) {
                self.$clip[0].scrollLeft += self.o.speed; 
            } else if (self.o.autoMode=='loop' || self.o.loop==true) {
                self.resetPos();
            } else {
                self.moveStop(self.movement);
            }
        },self.intervalDelay);
    },
    moveBack: function() {
        var self = this;
        this.movement = 'back';
        if (this.trigger !== null) {
            this.$btnForward.removeClass('disabled');
        }
        self.interval = setInterval(function() {
            if (!self.o.horizontal && self.$clip[0].scrollTop>0) {
                self.$clip[0].scrollTop -= self.o.speed;
            } else if (self.o.horizontal && self.$clip[0].scrollLeft>0) {
                self.$clip[0].scrollLeft -= self.o.speed;
            } else if (self.o.autoMode=='loop' || self.o.loop==true) {
                self.resetPosBack();
            } else {
                self.moveStop(self.movement);
            }
        },self.intervalDelay);
    },
    moveStop: function(moveDir) {
        clearInterval(this.interval);   
        this.movement = 'stopped';
        if (this.trigger!==null) {
            if (typeof moveDir != "undefined") {
                $(this.trigger).addClass('disabled');
            }
            this.trigger = null;
        }
        if (this.auto) {
            if (this.o.autoMode=='bounce') {
                moveDir == 'forward' ? this.moveBack() : this.moveForward();
            }
        }
    },
    moveResume: function() {
        this.movement=='forward' ? this.moveForward() : this.moveBack();
    },
    centerImage: function(mousePos) {
        this.movement='animating';
        clearInterval(this.interval);
        if(this.$clip[0].scrollLeft < (this.itemMax*(this.addItems-2))) {
            this.$clip[0].scrollLeft += this.itemTotal*this.itemMax;
        }
        else if (this.$clip[0].scrollLeft > (this.itemMax*this.itemTotal)) {
            this.$clip[0].scrollLeft -= this.itemTotal*this.itemMax;
        }
        var img = Math.ceil((this.$clip[0].scrollLeft+mousePos) / this.itemMax);//alert(this.$clip[0].scrollLeft+"#"+mousePos+"#"+this.itemMax+"#"+img);
        this.current = img+1 -this.addItems;
        this.$clip.find("img").removeClass("selected");
        this.$clip.find("img").css("opacity", 0.6);
        
        this.$loader.show();
        
        jQuery("#fp_loading").show().css("display","block").css("visibility","visible");
        var that = this;
        var $image = this.$clip.find('li:nth-child('+parseInt(img)+')').children("img");
        var alt = $image.attr('alt');
        if(alt == "vimeo"){
            var $iframe = this.$clip.find('li:nth-child('+parseInt(img+1)+')').children("iframe");
            var $previousPayload = $('img.fp_preview');
            if($previousPayload == null) {
                $previousPayload = $('iframe.fp_preview');
            }
            var $newimg         = $iframe.clone();
            var $currImage  = $previousPayload;
            $currImage.stop();
            $newimg.insertAfter($currImage);
            $newimg.fadeOut(0);
            $newimg.addClass('fp_preview');
            that.$loader.hide();
            $currImage.fadeOut(500,function(){
                $(this).remove();
                $newimg.fadeIn(500);
            });
        }
        else {
            //$('<img class="fp_preview"/>').load(function(){
                var $previousPayload = $('img.fp_preview');
                if($previousPayload.length == 0) {
                    $previousPayload = $('iframe.fp_preview');
                }
                tmp_img = new Image();
    			tmp_img.src = $image.attr('alt');
                var $newimg         =$("<img class=\"fp_preview\" src=\""+$image.attr('alt')+"\" />"); //$(this);
                var $newurl = $image.attr('longdesc');
                var $currImage  = $previousPayload;
                $currImage.stop(false,true);
                $newimg.insertAfter($currImage);
                $newimg.load(function(){
                 $newimg.fadeOut(0);
                 that.$loader.hide();
                 jQuery("#fp_loading").hide();
                 $currImage.fadeOut(500,function(){
                     $(this).remove();
                     $newimg.fadeIn(500);
                 });
                });
                
            //}).attr('src',$image.attr('alt'));
                $('#main_img_url').attr('href', $newurl);
        }
        $image.css("opacity",1);
        $image.addClass("selected");
        var center = (img*this.itemMax  - (this.$clip.width() / 2) - 10 + (this.itemMax/2))-170 ;
        
        this.$clip.stop().animate({"scrollLeft" : center}, "fast");
        this.movement='halted';
    },
    resetPos: function() {
        if (!this.o.horizontal) {
            this.$clip[0].scrollTop = this.itemMax*this.addItems;
        } else {
            this.$clip[0].scrollLeft = this.itemMax*this.addItems;
        }
    },
    resetPosBack: function() {
        if (!this.o.horizontal) {
            this.$clip[0].scrollTop = this.itemTotal*this.itemMax;
        } else {
            this.$clip[0].scrollLeft = this.itemTotal*this.itemMax;
        }
    },
    showPrev: function() {
        //this.movement='animating';
        clearInterval(this.interval);
        this.$clip.find("img").removeClass("selected");
        this.$clip.find("img").css("opacity", 0.6);
        this.oldfocus = this.current;
        this.current--;
        $e_next = this.$clip.find('li:nth-child('+parseInt(this.current+this.addItems)+')');
        if(this.current == 0){
            this.current = this.itemTotal;
            $e_next = this.$clip.find('li:nth-child('+parseInt(this.current+this.addItems)+')');
            this.$clip[0].scrollLeft += this.itemTotal*this.itemMax;
        }
        var $elem   = $e_next.find('img');
        $($elem[0]).css("opacity", "1");
        $($elem[0]).addClass("selected");
        
        this.$loader.show();
        var center = ((this.current-1)+this.addItems)*this.itemMax - (this.$clip.width() / 2) - 10 + (this.itemMax/2);
        this.$clip.stop().animate({"scrollLeft" : center}, "fast");
        that = this;
        var $image = $($elem[0]);
        var alt = $image.attr('alt');
        var $newurl = $image.attr('longdesc');
        if(alt == "vimeo"){
            var $iframe = this.$clip.find('li:nth-child('+parseInt(that.current+that.addItems)+')').children("iframe");
            var $previousPayload = $('img.fp_preview');
            if($previousPayload == null) {
                $previousPayload = $('iframe.fp_preview');
            }
            var $newimg         = $iframe.clone();
            var $currImage  = $previousPayload;
            $currImage.stop(false,true);
            $newimg.insertAfter($currImage);
            $newimg.fadeOut(0);
            $newimg.addClass('fp_preview');
            that.$loader.hide();
            $currImage.fadeOut(500,function(){
                $(this).remove();
                $newimg.fadeIn(500);
            });
        }
        else {
            //$('<img class="fp_preview"/>').load(function(){
                var $previousPayload = $('img.fp_preview');
                if($previousPayload.length == 0) {
                    $previousPayload = $('iframe.fp_preview');
                }
                var $newimg         =$("<img class=\"fp_preview\" src=\""+$image.attr('alt')+"\" />"); //$(this);
                var $currImage  = $previousPayload;
                $currImage.stop(false,true);
                $newimg.insertAfter($currImage);
                $newimg.fadeOut(0);
                that.$loader.hide();
                $currImage.fadeOut(500,function(){
                    $(this).remove();
                    $newimg.fadeIn(500);
                });
                $('#main_img_url').attr('href', $newurl);
            //}).attr('src',$image.attr('alt'));
        }
    },
    showNext: function() {
        this.movement='animating';
        clearInterval(this.interval);
        this.$clip.find("img").removeClass("selected");
        this.$clip.find("img").css("opacity", 0.6);
        this.current++;
        
        $e_next = this.$clip.find('li:nth-child('+parseInt(this.current+this.addItems)+')');
        if(this.current == this.itemTotal+1){
            this.current = 1;
            $e_next = this.$clip.find('li:nth-child('+parseInt(this.current+this.addItems)+')');
            this.$clip[0].scrollLeft -= this.itemTotal*this.itemMax;
        }
        var $elem   = $e_next.find('img');
        $($elem[0]).css("opacity", "1");
        $($elem[0]).addClass("selected");
        this.$loader.show();
        var center = ((this.current-1)+this.addItems)*this.itemMax - (this.$clip.width() / 2) - 10 + (this.itemMax/2);
        this.$clip.stop().animate({"scrollLeft" : center}, "fast");
        that = this;
        var $image = $($elem[0]);
        var alt = $image.attr('alt');
        var $newurl = $image.attr('title');
        if(alt == "vimeo"){
            var $iframe = this.$clip.find('li:nth-child('+parseInt(that.current+that.addItems)+')').children("iframe");
            var $previousPayload = $('img.fp_preview');
            if($previousPayload == null) {
                $previousPayload = $('iframe.fp_preview');
            }
            var $newimg         = $iframe.clone();
            var $currImage  = $previousPayload;
            $currImage.stop();
            $newimg.insertAfter($currImage);
            $newimg.fadeOut(0);
            $newimg.addClass('fp_preview');
            that.$loader.hide();
            $currImage.fadeOut(500,function(){
                $(this).remove();
                $newimg.fadeIn(500);
            });
        }
        else {
            //$('<img class="fp_preview"/>').load(function(){
                //console.log(this);
                var $previousPayload = $('img.fp_preview');
                if($previousPayload.length == 0) {
                    $previousPayload = $('iframe.fp_preview');
                }
                var $newimg         = $("<img class=\"fp_preview\" src=\""+$image.attr('alt')+"\" />"); //$(this);
                var $currImage  = $previousPayload;
                $currImage.stop(false,true);
                $newimg.insertAfter($currImage);
                $newimg.fadeOut(0);
                that.$loader.hide();
                $currImage.fadeOut(500,function(){
                    $(this).remove();
                    $newimg.fadeIn(500);
                });
                $('#main_img_url').attr('href', $newurl);
            //}).attr('src',$image.attr('alt'));
        }
    },

    renderData: function(json) {
        if (json.length>0) { //render json data
            var self = this;
            $.each(json, function(i,item) {
                $("<img/>").attr({
                    src: item.src,
                    title: item.title,
                    alt: item.title,
                    width: self.o.jsonImgWidth,
                    height: self.o.jsonImgHeight
                }).appendTo(self.$list);
            });
            this.init();
        }
    }
});
          
})(jQuery);

