(function($){
    $.fn.flexslider = function() {
        return this.each(function() {
            flexslider(this);
        });
    };

    function flexslider(target) {
        var current_position = 0;
        var slide_width = $(target).width();
        var slides = $(target).find('.slider');
        var image_count = $(target).find('.slider li').length;
        var image_width = $(target).find('.slider li').outerWidth(true);

        // Wrap all .slides with #slide_inner div
        slides.wrapAll('<div class="slide_inner"></div>');
        // Float left to display horizontally, readjust .slides width
        slides.css({
            'float' : 'left',
            'width' : image_width*image_count+'px'
        });

        // Insert left and right arrow controls in the DOM
        $(target).find('.slideshow')
        .prepend('<span class="arrow_container"><span class="control left_control"></span></span>')
        .append('<span class="arrow_container"><span class="control right_control"></span></span>');

        var arrow_width = $(target).find('.arrow_container').outerWidth(true)*2;
        // Set #slide_inner width equal to total width of all slides
        $(target).find('.slide_inner').css('width', (slide_width-arrow_width)+'px');

        // Hide left arrow control on first load
        manage_controls(current_position);

        // Create event listeners for .controls clicks
        $(target).find('.control').click(function(){
            // Determine new position
            current_position = ($(this).hasClass('right_control'))
            ? current_position+1 : current_position-1;

            // Hide / show controls
            manage_controls(current_position);
            // Move slide_inner using margin-left
            var gap = arrow_width - $(target).find('.arrow_container').css('marginLeft').replace('px','');
            var max_fit = Math.floor((slide_width)/image_width);
            $(target).find('.slider').animate({'opacity': 0.6}, 100).animate({
                'marginLeft' : (max_fit*image_width)*(-current_position)
            }).animate({'opacity': 1.0});
        });

        // manage_controls: Hides and shows controls depending on current_position
        function manage_controls(position){
            // Hide left arrow if position is first slide
            if(position==0){
                $(target).find('.left_control').hide()
            }else{
                $(target).find('.left_control').show()
            }

            // Hide right arrow if position is last slide
            var image_max = image_count/(slide_width/image_width);

            if(position>=image_max-1){
                $(target).find('.right_control').hide()
            }else{
                $(target).find('.right_control').show()
            }
        }
    };
})(jQuery);

