(function ($) {
    $.fn.instagramstream = function (options) {
        var defaults = {
            username: '', // Instagram username
            limit: 10, // how many photos to show
            overlay: true, // add overlay div
            textContainer: '.is-text', // selector or jQuery object of div with text
            textPosition: '4', // position of text in grid of photos
            textSize: '1', // size of text e.g. 1 - has size like one image; 2 - has size of two images etc.
            imageQuality: 'standard', // ** not applicable anymore with new API **
            accessToken: ''
        };
        var options = $.extend(defaults, options);

        return this.each(function () {
            var object = $(this);

            object.append("<ul class=\"instagram-list\"></ul>")

            // check if access token is set
            if ((typeof (options.accessToken) != "undefined") && options.accessToken != "") {
                var access_token = options.accessToken;
            } else {
                console.warn("Instagram Access Token is not set. Please enter it in plugin init call.");
                return;
            }

            var url = "https://graph.instagram.com/me/media?fields=id,caption,media_url,permalink&limit=" + options.limit + "&access_token=" + access_token;
            
            $.getJSON(url, function (data) {
                
                $.each(data.data, function (i, shot) {

                    var photo_src = shot.media_url;
                    var photo_url = shot.permalink;

                    var photo_title = "";
                    if (shot.caption != null) {
                        photo_title = shot.caption.text;
                    }

                    var photo_container = $('<img/>').attr({
                        src: photo_src,
                        alt: photo_title
                    });
                    var url_container = $('<a/>').attr({
                        href: photo_url,
                        target: '_blank',
                        title: photo_title
                    });
                    
                    if (options.overlay) {
                        var overlay_div = $('<div/>').addClass('img-overlay');
                        $(url_container).append(overlay_div);
                    }

                    // reduce by one because array stars from 0
                    var textPos = parseInt(options.textPosition) - 1;

                    var $container = $('.instagram-list');

                    // image size
                    var textSizeWidth = ($container.width() / 8) * options.textSize;
                    var textSizeHeight = ($container.width() / 8);

                    // add text to stream
                    // if we are on desired position, add text
                    if (i == textPos) {

                        // check if text is jQuery object
                        if (jQuery.type(options.textContainer) == 'object') {

                            var text_li = $('<li/>')
                                    .attr({
                                        class: 'is-text'
                                    })
                                    .append(options.textContainer.html());

                            $("ul", object).append(text_li);

                            // remove original element
                            options.textContainer.remove();

                            // otherwise check if user passed selector
                        } else if (jQuery.type(options.textContainer) == 'string') {

                            // find element in DOM
                            var textHtml = jQuery(options.textContainer);

                            // append HTML if it exists
                            if (typeof (textHtml) != 'undefined') {
                                var text_li = $('<li/>')
                                        .attr({
                                            class: 'is-text'
                                        })
                                        .append(textHtml.html());

                                $("ul", object).append(text_li);

                                // remove original element
                                textHtml.remove();
                            }
                        }
                    }

                    var li = $('<li/>').css('background-image', 'url(' + photo_src + ')').append(url_container);
                    $("ul", object).append(li);

                    // calculate image and text size
                    onResize();

                });

            });

            /**
             * Resize event
             */
            $(window).resize(function () {
                onResize();
            });

            /**
             * Change image size on screen resize
             * 
             * @returns void
             */
            function onResize() {

                var windowWidth = $(window).width();

                // container
                var $container = $('.instagram-list');

                // loop through each gallery
                $container.each(function () {

                    var $this = $(this);

                    // image size
                    if (windowWidth < 320) {

                        var imageSizeWidth = 100;
                        var imageSizeHeight = $this.outerWidth();

                        if (options.textSize > 1) {
                            var textSizeWidth = (imageSizeWidth);
                            var textSizeHeight = (imageSizeHeight);
                        }

                        // smartphones
                    } else if (windowWidth > 320 && windowWidth < 479) {

                        var imageSizeWidth = 100;
                        var imageSizeHeight = $this.outerWidth();
                        var imageSize = imageSizeHeight;

                        if (options.textSize > 1) {
                            var textSizeWidth = (imageSizeWidth);
                            var textSizeHeight = (imageSizeHeight);
                        }

                        // smartphones and tables
                    } else if (windowWidth > 480 && windowWidth < 767) {

                        var imageSizeWidth = (100 / 2);
                        var imageSizeHeight = $this.outerWidth() / 2;
                        var imageSize = imageSizeHeight;

                        if (options.textSize >= 2) {
                            var textSizeWidth = imageSizeWidth;
                            var textSizeHeight = imageSizeHeight;
                        }

                        // tablets
                    } else if (windowWidth > 768 && windowWidth < 991) {

                        var imageSizeWidth = (100 / 4);
                        var imageSizeHeight = $this.outerWidth() / 4;
                        var imageSize = imageSizeHeight;

                        if (options.textSize >= 2) {
                            var textSizeWidth = imageSizeWidth * 2;
                            var textSizeHeight = imageSizeHeight;
                        }

                        // smaller screen desktops
                    } else if (windowWidth > 992 && windowWidth < 1199) {

                        var imageSizeWidth = (100 / 6);
                        var imageSizeHeight = $this.outerWidth() / 6;
                        var imageSize = imageSizeHeight;

                        if (options.textSize >= 3) {
                            var textSizeWidth = imageSizeWidth * 3;
                            var textSizeHeight = imageSizeHeight;
                        } else if (options.textSize == 2) {
                            var textSizeWidth = imageSizeWidth * 2;
                            var textSizeHeight = imageSizeHeight;
                        }

                        // large screen desktops
                    } else if (windowWidth > 1200) {

                        var imageSizeWidth = (100 / 8);
                        var imageSizeHeight = $this.outerWidth() / 8;
                        var imageSize = imageSizeHeight;

                        var textSizeWidth = imageSizeWidth * options.textSize;
                        var textSizeHeight = imageSizeHeight;
                    }

                    // change image width and height
                    object.find('li:not(.is-text)').width(imageSizeWidth + "%").height(imageSizeHeight);

                    // change text width and height
                    object.find('li.is-text').outerWidth(textSizeWidth + "%").outerHeight(textSizeHeight);
                });

            }

        });
    };
})(jQuery);