﻿//Formats a number with commas
var formatNumber = function(number) {
    number += "";
    var parts = number.split('.');
    var integer = parts[0];
    var decimal = parts.length > 1 ? '.' + parts[1] : '';
    var regex = /(\d+)(\d{3})/;
    while (regex.test(integer)) {
        integer = integer.replace(regex, '$1' + ',' + '$2');
    }
    return integer + decimal;
};

Lamco.Carousel = (function() {
    // Contains data for each listing that the banner is cycling through
    var testcarousel_itemList = [];

    // Will be used to reset highlighting to the middle index once
    // user is no longer manipulating the carousel
    var currentFocusedItemIndex = 1;

    //The preferred number of items to display in the carousel
    var preferredCarouselSize = 7;

    //The number of listings needed to lean the tool tip within the viewport
    var itemsForToolTipLean = 3;

    // PreferredCarouselSize represents the amount of visible items we wish to see in the
    // carousel at any one time
    var carouselMiddleItemViewIndex = Math.floor(preferredCarouselSize / 2) + 1;

    var listingDetailPage = false;

    return {
        Carousel_initCallback: function(carousel, state) {

            currentFocusedItemIndex = carouselMiddleItemViewIndex;

            // Get container width for a standard carousel item
            var carouselClippingWith = carousel.options.visible * 110;

            // Calculate left margin to center the carousel items
            var carouselContainerHorizontalMargin = (parseFloat($('.jcarousel-container-horizontal').css("width"), 10) - carouselClippingWith) / 2;

            // Set up the clipping width according to the number of items
            // that will be visible at any one time
            $('.jcarousel-clip-horizontal').css({ width: carousel.options.visible * 110, marginLeft: carouselContainerHorizontalMargin, marginRight: carouselContainerHorizontalMargin });

            // Highlight middle item
            $('.jcarousel-item-' + currentFocusedItemIndex + ' .BannerImageContainer').fadeTo("fast", 1);

            // Stops and starts the auto scrolling of the carousel
            // depending upon whether the user is interacting with the control
            if (testcarousel_itemList.length > 1) {
                $('#testcarousel').hover(function() {

                    carousel.stopAuto();
                },
				function() {
				    // Highlight the previous middle item the was selected before user interrupted auto-scroll
				    $('.jcarousel-item-' + currentFocusedItemIndex + ' .BannerImageContainer').fadeTo("fast", 1);

				    carousel.startAuto();
				});
            }
        }
		,
        Carousel_ItemLastInCallback: function(carousel, listObject, i, state) {
            // Temporarily we are not doing anything here because it doesn't fire each time
            // an element appears in the tail end of the carousel
        }
	    ,
        Carousel_ItemVisibleOutCallback: function(carousel, item, i, state, evt) {
            // Used if the rotating mode is circular
            if (evt != 'init') {
                //Remove the tool tip
                Lamco.Carousel.Carousel_RemoveToolTip(i);
                carousel.remove(i);
            }
        }
	    ,
        Carousel_ItemVisibleInCallback: function(carousel, item, i, state, evt) {
            if (evt != 'init' && !listingDetailPage) {
                // Used if the the rotating mode is circular
                var idx = carousel.index(i, testcarousel_itemList.length);
                carousel.add(i, Lamco.Carousel.Carousel_GetItemHTML(testcarousel_itemList[idx - 1]));

                // Ensure middle item is selected
                $('.jcarousel-item-' + currentFocusedItemIndex + ' .BannerImageContainer').fadeTo("fast", 1);

                if (testcarousel_itemList.length > 1) {
                    // Set up hovering functionality for newly added banner item
                    $('.jcarousel-item-' + i + ' .BannerImageContainer').hoverIntent(function() {

                        // Reduce opacity of all listings
                        $('.BannerImageContainer').each(function() {
                            $(this).fadeTo("fast", .4);
                        });

                        $(this).fadeTo("fast", 1);
                    },
					function() {
					    $(this).fadeTo("fast", .4);
					});
                }

                $('.jcarousel-item-' + i + ' .BannerImageContainer').click(function() {
                    var itemsCarouselIndex = $(this).parent().attr("jcarouselindex");
                    var translatedIndex = carousel.index(itemsCarouselIndex, testcarousel_itemList.length);
                    var listingItem = testcarousel_itemList[translatedIndex - 1];

                    return Lamco.Mapping.DisplayListingDetails(listingItem.ListingID);
                });
            }

            //ToolTip
            if (state == 'next' && testcarousel_itemList.length > itemsForToolTipLean) {
                //Add the tool tip for the new item.
                Lamco.Carousel.Carousel_SetToolTip(carousel, i, 'topMiddle', 'bottomRight');

                //Remove the tool tip for the second item to the right and add it with a different position
                var secondToRight = i - 1;
                Lamco.Carousel.Carousel_UpdateToolTip(carousel, secondToRight, 'topMiddle', 'bottomMiddle');

                //Get the left item, replace toolbar with different position
                var firstIndex = carousel.first;
                Lamco.Carousel.Carousel_UpdateToolTip(carousel, firstIndex, 'topMiddle', 'bottomLeft');
            }
            else if (state == 'prev' && testcarousel_itemList.length > itemsForToolTipLean) {
                Lamco.Carousel.Carousel_SetToolTip(carousel, i, 'topMiddle', 'bottomLeft');

                //Remove the tool tip for the second item to the left and add it with a different position
                var secondToLeft = i + 1;
                Lamco.Carousel.Carousel_UpdateToolTip(carousel, secondToLeft, 'topMiddle', 'bottomMiddle');

                //Get the right item, replace toolbar with different position
                var lastIndex = carousel.last;
                Lamco.Carousel.Carousel_UpdateToolTip(carousel, lastIndex, 'topMiddle', 'bottomRight');
            }
            else if (state == 'init' && testcarousel_itemList.length > itemsForToolTipLean) {
                if (i == carousel.first && testcarousel_itemList.length > itemsForToolTipLean) {
                    //Tool tip leaning right
                    Lamco.Carousel.Carousel_SetToolTip(carousel, i, 'topMiddle', 'bottomLeft');
                }
                else if (i == carousel.last && testcarousel_itemList.length > itemsForToolTipLean) {
                    //Tool tip leaning left
                    Lamco.Carousel.Carousel_SetToolTip(carousel, i, 'topMiddle', 'bottomRight');
                }
                else {
                    //Tool tip middle
                    Lamco.Carousel.Carousel_SetToolTip(carousel, i, 'topMiddle', 'bottomMiddle');
                }
            }
            else {
                //Not enough items to lean the tool tip inside
                Lamco.Carousel.Carousel_SetToolTip(carousel, i, 'topMiddle', 'bottomMiddle');
            }
        }
	    ,
        Carousel_ItemLoadCallBack: function(carousel, state) {
            if (state == 'init') {
                for (var i = carousel.first; i <= carousel.last; i++) {
                    if (carousel.has(i)) {
                        continue;
                    }

                    if (i > testcarousel_itemList.length) {
                        break;
                    }

                    carousel.add(i, Lamco.Carousel.Carousel_GetItemHTML(testcarousel_itemList[i - 1]));
                }

                if (testcarousel_itemList.length > 1) {
                    $('.BannerImageContainer').each(function() {
                        $(this).hoverIntent(function() {
                            if (!listingDetailPage) {
                                // Remove all highlighting
                                $('.BannerImageContainer').each(function() {
                                    $(this).fadeTo("fast", .4);
                                });

                                $(this).fadeTo("fast", 1);
                            }
                        },
						function() {
						    if (!listingDetailPage) {
						        $(this).fadeTo("fast", .4);
						    }
						});

                        if (!listingDetailPage) {
                            $(this).click(function() {
                                var itemsCarouselIndex = $(this).parent().attr("jcarouselindex");
                                var translatedIndex = carousel.index(itemsCarouselIndex, testcarousel_itemList.length);
                                var listingItem = testcarousel_itemList[translatedIndex - 1];

                                return Lamco.Mapping.DisplayListingDetails(listingItem.ListingID);
                            });
                        }
                    });
                }

                // Highlight the middle starting point
                $('.jcarousel-item-' + currentFocusedItemIndex + ' .BannerImageContainer').css({ backgroundColor: '#ffffff' });
                //Lamco.Carousel.Carousel_SetDescriptionArea(carousel, currentFocusedItemIndex);
            }
            else {
                // Highlight middle
                // Determine middle item index from last in index
                if (state == 'next') {
                    currentFocusedItemIndex++;
                }
                else if (state == 'prev') {

                    currentFocusedItemIndex--;
                }

                if (testcarousel_itemList.length > 1) {
                    // Reduce opacity of all listings
                    $('.BannerImageContainer').each(function() {
                        $(this).fadeTo("fast", .4);
                    });

                    // Increase opacity of middle item to highlight it
                    $('.jcarousel-item-' + currentFocusedItemIndex + ' .BannerImageContainer').fadeTo("fast", 1);
                }

            }
        },
        Carousel_SetToolTip: function(carousel, cItemIndex, positionTarget, positionToolTip) {
            // Since carousel is circular translate the passed in index to it's position in
            // the testcarousel_itemList array
            var idx = carousel.index(cItemIndex, testcarousel_itemList.length);

            if (idx > 0) {
                var carouselItem = testcarousel_itemList[idx - 1];
                var amount = formatNumber(carouselItem.Price);
                var title = '<p > ' + carouselItem.Address + '</p>'

                //Create the popup html, note: You need to use inline css or qtip styling.
                var container = $('<div style="font-size:10px; text-align:center;" >'
                        + '<table style="width:100%;" cellpadding="0" cellspacing="0" border="0">'
                        + ' <tr style="text-align:left;">'
                        + '     <td style="padding-right:5px;">Price: $' + amount + ' </td>'
                        + '     <td style="padding-right:5px;">Bathrooms: ' + carouselItem.NumberOfBathrooms + ' </td>'
                        + '     <td style="padding-right:5px;">Bedrooms: ' + carouselItem.NumberOfBedrooms + ' </td>'
                        + ' </tr>'
                        + ' <tr style="text-align:left;">'
                        + '     <td>Area Inside: ' + carouselItem.SizeOfHouse + ' sqft.</td>'
                        + '     <td>Year Built: ' + carouselItem.YearBuilt + ' </td>'
                        + '     <td>Lot Size: ' + carouselItem.LotSize + ' acres</td>'
                        + ' </tr>'
                        + '</table>'
                        + '</div>');

                //Creates the tooltip
                //Note position works like "Tooltip's specified position is touching the targets specified position"
                $('.jcarousel-item-' + cItemIndex + ' .BannerImageContainer').qtip(
                    {
                        content: {
                            text: container,
                            title: { text: title }
                        },
                        position: {
                            corner: {
                                target: positionTarget,
                                tooltip: positionToolTip
                            }
                        },
                        style: {
                            width: {
                                min: 450
                            },
                            padding: 5,
                            background: '#FBFBFB',
                            color: 'black',
                            textAlign: 'center',
                            border: {
                                width: 1,
                                radius: 4,
                                color: '#687819'
                            },
                            title: {
                                background: '#687819',
                                color: 'white',
                                textAlign: 'center',
                                fontWeight: 'bold',
                                fontSize: 11
                            },
                            tip: positionToolTip
                        }

                    });
            }
        }
        ,
        Carousel_UpdateToolTip: function(carousel, itemIndex, newPositionTarget, oldPositionToolTip) {
            //Remove the old tool tip and add the new one
            Lamco.Carousel.Carousel_RemoveToolTip(itemIndex);
            Lamco.Carousel.Carousel_SetToolTip(carousel, itemIndex, newPositionTarget, oldPositionToolTip);
        }
        ,
        Carousel_RemoveToolTip: function(index) {
            //Removed the tool tip given the index
            $('.jcarousel-item-' + index + ' .BannerImageContainer').qtip("destroy");
        }
		,
        Carousel_GetItemHTML: function(item) {
            return '<div class="BannerImageContainer" ><a href="#"><img src="' + item.PropertyImageUrl + '" width="110" height="100" style="border:none; background-color:white;" alt="' + item.PropertyImageUrl + '" /></a></div>';
        }
		,
        Initialize: function(items) {
            testcarousel_itemList = items;
            if (testcarousel_itemList.length < preferredCarouselSize) {
                carouselMiddleItemViewIndex = Math.floor(testcarousel_itemList.length / 2) + 1;
            }
            $('#testcarousel').jcarousel({
                vertical: false,
                size: testcarousel_itemList.length,
                scroll: 1,
                visible: (testcarousel_itemList.length < preferredCarouselSize ? testcarousel_itemList.length : preferredCarouselSize),
                animation: 'fast',
                auto: 5,
                wrap: (testcarousel_itemList.length == 1 ? null : 'circular'),
                initCallback: Lamco.Carousel.Carousel_initCallback,
                itemLoadCallback: { onBeforeAnimation: Lamco.Carousel.Carousel_ItemLoadCallBack },
                itemVisibleInCallback: { onBeforeAnimation: Lamco.Carousel.Carousel_ItemVisibleInCallback },
                itemVisibleOutCallback: { onAfterAnimation: Lamco.Carousel.Carousel_ItemVisibleOutCallback },
                itemLastInCallback: { onBeforeAnimation: Lamco.Carousel.Carousel_ItemLastInCallback }
            });
        }
        ,
        InitializeForListingDetail: function(items) {
            preferredCarouselSize = 5;
            listingDetailPage = true;
            testcarousel_itemList = items;
            if (testcarousel_itemList.length < preferredCarouselSize) {
                carouselMiddleItemViewIndex = Math.floor(testcarousel_itemList.length / 2) + 1;
            }
            else {
                carouselMiddleItemViewIndex = Math.floor(preferredCarouselSize / 2) + 1;
            }
            $('#testcarousel').jcarousel({
                vertical: false,
                size: testcarousel_itemList.length,
                visible: (testcarousel_itemList.length < preferredCarouselSize ? testcarousel_itemList.length : preferredCarouselSize),
                scroll: 0,
                auto: 5,
                wrap: (testcarousel_itemList.length == 1 ? null : 'circular'),
                initCallback: Lamco.Carousel.Carousel_initCallback,
                itemLoadCallback: { onBeforeAnimation: Lamco.Carousel.Carousel_ItemLoadCallBack },
                itemVisibleInCallback: { onBeforeAnimation: Lamco.Carousel.Carousel_ItemVisibleInCallback },
                itemVisibleOutCallback: { onAfterAnimation: Lamco.Carousel.Carousel_ItemVisibleOutCallback },
                itemLastInCallback: { onBeforeAnimation: Lamco.Carousel.Carousel_ItemLastInCallback }
            });
        }
    }
})();