(function ($) {
    $.fn.shopItemsGallery = function (JSON_URL, JSON_PARAMS, GALLERY_TYPE, ITEMS_NUMBER, SHUFFLED, PRELOADED_IMAGES) {
        var _MAX_SHORT_NAME_LENGTH = 18;
        var _MAX_DESIGNER_LENGTH = 12;
        var _PRELOADED_IMAGES = 0;
        var _ITEMS_NUMBER = 0;
        var _JSON_URL = "";
        var _JSON_PARAMS = {};
        var _SHUFFLED = 0;
        var _GALLERY_TYPE = "shopitems";
        var _THIS = $(this);

        if (typeof (JSON_URL) != 'undefined' && JSON_URL != null) _JSON_URL = JSON_URL;
        if (typeof (JSON_PARAMS) != 'undefined' && JSON_PARAMS != null) _JSON_PARAMS = JSON_PARAMS;
        if (typeof (ITEMS_NUMBER) != 'undefined' && ITEMS_NUMBER != null) _ITEMS_NUMBER = ITEMS_NUMBER;
        if (typeof (SHUFFLED) != 'undefined' && SHUFFLED != null) _SHUFFLED = SHUFFLED;
        if (typeof (PRELOADED_IMAGES) != 'undefined' && PRELOADED_IMAGES != null) _PRELOADED_IMAGES = PRELOADED_IMAGES;
        if (typeof (GALLERY_TYPE) != 'undefined' && GALLERY_TYPE != null) _GALLERY_TYPE = GALLERY_TYPE;

        /*==========================================Shuffling Array================================================*/

        var _ShuffleArray = function (arr) {
            for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
            return arr;
        } // end of _ShuffleArray

        /*===================================Setting Blinking design for arrows=====================================*/

        var _SetNavBtnHovers = function (btnNav) {
            _THIS.find(btnNav).animate({ opacity: 0.3 }, 250);
            _THIS.find(btnNav).mouseleave(function () {
                $(this).animate({ opacity: 0.3 }, 250);
            });
            _THIS.find(btnNav).mouseenter(function () {
                $(this).animate({ opacity: 0.7 }, 250);
                $(this).clearQueue();
            });
        } // end of _SetNavBtnHovers

        /*===========================================Creating jscarusel==============================================*/

        var _InsertItemsToPage = function (html_result, items_length) {

            _THIS.find('ul').html(html_result);
            _THIS.find('ul').disableSelection();
				if(_GALLERY_TYPE == "flickr"){
				_THIS.find('ul').jcarousel({
					wrap: 'circular'
				});
				_SetNavBtnHovers('.jcarousel-prev');
				_SetNavBtnHovers('.jcarousel-next');
				if (items_length < 8 && (GALLERY_TYPE = "flickr")) {
					_THIS.find(".jcarousel-prev").hide();
					_THIS.find(".jcarousel-next").hide();
				}
			}
        } // end of _InsertItemsToPage

        /*=============================================Building ShopItems html=========================================*/

        var _BuildShopItemsList = function (data_list) {

            var items = data_list.items;
            if (_SHUFFLED == 1) items = _ShuffleArray(items);

            var items_length = _ITEMS_NUMBER;
            if (_ITEMS_NUMBER == 0 || $(items).length < _ITEMS_NUMBER) items_length = $(items).length;

            var bad_images_array = [];

            var _BuildHtml = function () {
                var html_result = "";
                var counter = 0;
                var i = 0;
                while (i < $(items).length && counter < items_length) {
                    var item = $(items)[i];
                    if (item.name.length > _MAX_SHORT_NAME_LENGTH) item.name=item.name.substr(0, _MAX_SHORT_NAME_LENGTH)+"...";
                    if (item.designerName.length > _MAX_DESIGNER_LENGTH) item.designerName=item.designerName.substr(0, _MAX_DESIGNER_LENGTH)+"...";
                    if ($.inArray(item.picture, bad_images_array) == -1) {
                        html_result += _getShopItemHtml(item.url, item.imageUrl, item.name, item.price, item.designerName, item.canBeOrdered);
                        counter++;
                    }
                    i++;
                }
                _InsertItemsToPage(html_result);
            }

            var _getShopItemHtml = function (itemUrl, imgUrl, itemName, itemPrice, itemDesigner, canBeOrdered) {
                var html_result = '<li>';
                html_result += '<a href="' + itemUrl + '">';
                html_result += '<span class="b-pictureShopItem"><img src="' + imgUrl + '"  alt=""/></span>';
                html_result += '<span class="txt-productTitle">' + itemName + '</span>';
                itemPrice = (canBeOrdered) ? itemPrice + ' &euro;' : '&nbsp;';
                html_result += '<span class="txt-productPrice">' + itemPrice + '</span>';
                html_result += '<span class="txt-productDescription">' + itemDesigner + '</span>';
                html_result += '<span class="b-helper"></span>';
                html_result += '</a>';
                html_result += '</li>';
                return html_result;
            }


            if (_PRELOADED_IMAGES == 1) {
                var img_loaded_counter = $(items).length;
                for (var i = 0; i < $(items).length; i++) {
                    var item = $(items)[i];
                    $(new Image()).bind("load error", function (event) {
                        if (event.type == 'error') bad_images_array.push($(this).attr('src'));
                        if (--img_loaded_counter < 1) {

                            _BuildHtml();
                        }
                    }).attr('src', item.picture);

                };
            } else {
                _BuildHtml();
            }


        } // end of _BuildShopItemsList

        /*=========================================Building flickr html===============================================*/


        _BuildFlickrList = function (data_list) {

            var items = data_list.photos.photo;
            if (_SHUFFLED == 1) items = _ShuffleArray(items);

            var items_length = _ITEMS_NUMBER;
            if (_ITEMS_NUMBER == 0 || $(items).length < _ITEMS_NUMBER) items_length = $(items).length;

            var bad_images_array = [];


            var _BuildHtml = function () {
                var html_result = "";
                var counter = 0;
                var i = 0;
                var page_url = "http://www.flickr.com/photos/imaterialise/";
                while (i < $(items).length && counter < items_length) {
                    var item = $(items)[i];
                    if ($.inArray(item.url_s, bad_images_array) == -1) {
                        var myURL_small = "http://farm" + item.farm + ".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s" + ".jpg";
                        html_result += _getFlickrItemHtml(page_url, item.id, myURL_small, item.title);
                        counter++;
                    }
                    i++;
                }

                _InsertItemsToPage(html_result, items_length);
            }

            var _getFlickrItemHtml = function (pageUrl, itemID, imgUrl, imgTitle) {
                var html_result = '<li>';
                html_result += '<a href="' + pageUrl + itemID + '/" target="_blank" title="' + imgTitle + '">';
                html_result += '<img src="' + imgUrl + '" alt="' + imgTitle + '"/>';
                html_result += '</a>';
                html_result += '</li>';
                return html_result;
            }

            if (_PRELOADED_IMAGES == 1) {
                var img_loaded_counter = $(items).length;
                for (var i = 0; i < $(items).length; i++) {
                    var item = $(items)[i];
                    $(new Image()).bind("load error", function (event) {
                        if (event.type == 'error') bad_images_array.push($(this).attr('src'));
                        if (--img_loaded_counter < 1) {

                            _BuildHtml();
                        }
                    }).attr('src', item.url_s);

                };
            } else {
                _BuildHtml();
            }



        } // end of _BuildFlickrList

        /*==========================================reading JSON data================================================*/

        $.getJSON(_JSON_URL, _JSON_PARAMS,
            function (data) {
                switch (_GALLERY_TYPE) {
                    case "shopitems":
                        _BuildShopItemsList(data);
                        break;
                    case "flickr":
                        _BuildFlickrList(data);
                        break;
                    default:
                        _BuildShopItemsList(data);
                }

            });


    } // end of shopItemsGallery plugin

})(jQuery);
