﻿
App = function () {

    /* Private */

    /* Properties */

    var cmp = {};


    /* Defaults */

    TVI.debug = false;


    /* Methods */

    var init = function () {

        

        var searchForm = new TVI.Form({

            ID: 'search',
            submit: function () {
                window.location = '/products/search/' + sanitised(searchForm.field('text').val());
            }

        });

        // CUFON
        Cufon.replace('#header A:not(.basket A, .topNav A)', {
            hover: true
        });
        Cufon.replace('.homepageFeatureGallery .panel h2, .blackBoxwHeading H2, .blogSidebar .title2, .blogSidebar .title, .whiteBorderwHeading H2, .searchResultsBox .searchResultsTop H2, .categoryItem .title, .imageBox H2, .ratingTitle, .headingBar H2, #header .customerService, #header .loginArea .text, .homepageFeatureGallery .panel H2, .homepageQuicklinks .promo .panel, .fancyList .title');

        // FANCYBOX
        $('.fancybox, .lightbox').fancybox({
            'overlayOpacity': 0.94,
            'overlayColor': '#aeaeae',
            'padding': 17
        });

        TVI.event('.logout', 'click', function () {
            var cookie_date = new Date();  // current date & time
            cookie_date.setTime(cookie_date.getTime() - 1);
            document.cookie = "TviEcom=;expires=" + cookie_date.toGMTString();
            TVI.ajax({
                url: TVI.handlers + 'app.account.aspx/logout',
                success: function (d) {
                    $('.loginArea').html(d.accountForm);
                    if (window.location.toString().indexOf('checkout') > 0 || window.location.toString().indexOf('account') > 0) {
                        window.location = '/';
                    }
                    if (window.location.toString().indexOf('plant/') > 0) {
                        window.location.reload(true);
                    }
                }
            });
        });

        TVI.event('.quickAddButton', 'click', function () {

            var productID = $(this).attr('data-productID');

            TVI.ajax({

                url: '/handlers/app.products.aspx/getQuickLook',
                data: { productID: productID },
                responseType: 'text',
                success: function (d) {
                    $.fancybox({
                        content: d,
                        onComplete: function () {

                        }
                    });
                }

            });

        });

        TVI.event('.saveBasketButton', 'click', function (e) {

            data = {};

            // Build the data

            TVI.ajax({

                url: '/handlers/app.account.aspx/newBasket',
                data: data,
                success: function (d) {
                    // We get the basket back
                    $('.basket').html(d.miniBasket);
                   
                    TVI.Components.initialize();
                    App.roundCorners();
                    $.fancybox({
                        content: '<h3>Your basket has been saved</h3><p>Thank you for saving your basket. You can view your saved baskets <a href="/account/mybaskets.aspx">here</a>',
                        onComplete: function () {

                        }
                    });

                }

            });



        });

        TVI.event('.informationIcon, .informationPopup', 'click', function () {

            var contentName = $(this).attr('href');

            contentName = contentName.substring(contentName.indexOf('content') + 8);

            TVI.ajax({

                url: '/handlers/app.general.aspx/getPopupContent',
                data: { content: contentName },
                responseType: 'text',
                success: function (d) {
                    $.fancybox({
                        content: d,
                        onComplete: function () {

                        }
                    });
                }

            });

        });

        // FIRST VISIT OVERLAY
        $(window).load(function () {

            if (document.cookie.length < 1 || document.cookie.indexOf('firstvisit') == -1) {
                setTimeout(function () {
                    $.fancybox({
                        'overlayOpacity': 0.94,
                        'overlayColor': '#aeaeae',
                        'padding': 0,
                        'href': '#firstVisitOverlay',
                        onComplete: function (d) {
                            var subscribeForm = new TVI.Form({
                                ID: 'firstVisitOverlay',
                                url: '/handlers/App.Account.aspx/firstVisit',
                                success: function (d) {
                                    _gaq.push(['_trackPageview', '/firstVisitOverlayCompleted']);
                                    $('#firstVisitOverlay h1, #firstVisitOverlay p, #firstVisitOverlay-email').hide();
                                    $('.TVI-form-submit').show();
                                    $('.TVI-form-complete').text(d.message).show();
                                    $('.TVI-form-loading').hide();
                                    $('.noThanks').hide();
                                }
                            });
                        }
                    });
                }, 5000);
            }

            var expiry = new Date();
            expiry.setMonth(expiry.getDate() + 30);
            document.cookie = 'firstvisit=false; expires=' + expiry.toGMTString() + '; path=/';

        });
        $('#firstVisitOverlay .noThanks').click(function () {
            $.fancybox.close();
            return false;
        });

        $('#firstVisitOverlay .close').live('click', function () {
            $.fancybox.close();
            return false;
        });




        /* Constructor */
        TVI.Components.initialize();


        //        // If we support border radius remove the tvi buttons markup
        //        if ($('.borderradius') != undefined) {
        //            $('.TVI-button').each(function () {
        //                $(this).html($(this).find('.TVI-button-text').text());
        //            });
        //        }


        /* Nice #link scrolling */

        $('a[href^=#]').click(function () {

            if ($(this).attr('href') == '#') {
                return true;
            }

            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
        && location.hostname == this.hostname) {

                var $target = $(this.hash);

                $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');

                if ($target.length) {

                    var targetOffset = $target.offset().top;

                    $('html,body').animate({ scrollTop: targetOffset }, 1000, 'easeOutQuint', function () {
                        return false;
                    });



                }
            }
        });


        // BLOG ICONS
        $('.blogIcons A').hover(
			function () {
			    $(this).find('.blogIcon').animate({ top: '-=4px' });
			    $(this).find('.blogIconShaddow').animate({ top: '-=3px' });
			},
			function () {
			    $(this).find('.blogIcon').animate({ top: '+=4px' });
			    $(this).find('.blogIconShaddow').animate({ top: '+=3px' });
			}
		);


        // Subscribe form
        var subscribeForm = new TVI.Form({
            ID: 'subscribeForm',
            url: '/handlers/App.Account.aspx/newsletter'

        });


        // CORK BOARD
        // hover
        $('.accountCorkboard MAP AREA').hover(
            function () {

                // Get area segment data
                var overlaySegment = $(this).attr('data-overlayArea');

                // Fade correct segment
                $('.accountCorkboard').find('.overlaySegments .segment[class*=' + overlaySegment + ']').fadeTo('fast', 0.75);

            },
            function () {

                // Get area segment data
                var overlaySegment = $(this).attr('data-overlayArea');

                // Fade correct segment
                $('.accountCorkboard').find('.overlaySegments .segment[class*=' + overlaySegment + ']').fadeTo('fast', 1);

            }
        );


        // MENU DROPDOWNS
        // Set widths
        function showDropdown(item) {

            item.slideDown(100);

            var contentWidth = item.find('.middle').outerWidth();
            var navItemWidth = item.parents('.navItem').outerWidth();
            var offSetWidth = item.position().left * -2;
            var topCornerWidth = item.find('.tl').width() * 2;
            var bottomCornerWidth = item.find('.bl').width() * 2;

            // Overall width either content width or nav item width
            if (contentWidth > navItemWidth) {
                var overallwidth = contentWidth;
            } else {
                var overallwidth = navItemWidth + offSetWidth;
            }

            // Overall width
            item.width(overallwidth);

            // Top Extra to width of nav item
            item.find('.te').width(navItemWidth);

            // Top middle to overall width minus corners
            item.find('.tm').width(overallwidth - topCornerWidth);

            // Bottom middle to overall width minus corners
            item.find('.bm').width(overallwidth - bottomCornerWidth);

            // Add hover class            
            item.parent().find('A:first').addClass('hover');
        }


        // Show/hide
        $('.navItem').bind('mouseenter', function () {
            //  $('.dropdown').hide();
            //$('.navItem A').removeClass('hover');
        });
        $('.navItem .dropdown').parent().find('A:first').bind('mouseenter', function () {
            showDropdown($(this).parent().find('.dropdown'));
            return false;
        });
        $('.navItem .dropdown').parent().mouseleave(function () {
            $(this).find('.dropdown').hide();
            $(this).parent().find('A').removeClass('hover');
        });


        // INFOBOX
        $('.infoBox .infoBox_top').click(function () {
            if (!$(this).parent().find('.infoBox_middle').is(":animated")) {
                $(this).parent().find('.infoBox_middle').slideToggle();
                $(this).parent().toggleClass('open');
            }

            return false;
        });





        // QUICK ADD
        // button
        $('.productItem img').live('mouseenter', function () {
            $(this).closest('.productItem').find('.quickAddButton').show();
        });
        $('.productItem').live('mouseleave', function () {
            $(this).find('.quickAddButton').hide();
        });


        // EQUAL HEIGHTS
        $(window).load(function () {
            // Heading bars
            $('.headingBar').each(function () {
                var light = $(this).find('.light').outerHeight();
                var dark = $(this).find('.dark').outerHeight();

                if (light > dark) {
                    $(this).find('.dark').height(light);
                }
            });

            // Category page panel
            // Set height of panel to height of image

            if ($('.categoryFeature IMG').length > 0) {
                $('.categoryFeature IMG').batchImageLoad({
                    loadingCompleteCallback: function () {

                        $('.categoryFeature .panel').height($('.categoryFeature IMG').height() - 15);
                        $('.categoryFeature').height($('.categoryFeature IMG').height() + 39);


                    }
                });
            }
            else {
                $('.categoryFeature .panel').height($('.categoryFeature .panel').height() + 15);
                $('.categoryFeature').height($('.categoryFeature .panel').height() + 54);
            }

            //            var height = $('.categoryFeature IMG').height() - 15;
            //            $('.categoryFeature .panel').height(height);

            // Category items
            var maxHeight = 0;
            $('.categoryItem').each(function () {
                // If height is bigger then increase max size
                if ($(this).height() > maxHeight) {
                    maxHeight = $(this).height();
                }
            });
            $('.categoryItem').each(function () {
                $(this).height(maxHeight);
            });

        });

        App.formatProducts(function () { });





        // HOMEPAGE FUNCTION GALLERY
        function changeFeature(navItem) {

            var newItemIndex = navItem.index('.homepageFeatureGallery .featureList LI');
            var currentItemIndex = $('.homepageFeatureGallery .featureList LI.selected').index('.homepageFeatureGallery .featureList LI');
            var moveTo = newItemIndex * 280;
            var moveAmount = (currentItemIndex - newItemIndex);
            if (moveAmount < 1) {
                moveAmount = moveAmount * -1;
            }
            var moveSpeed = 400 + (moveAmount * 50);

            // Clear selected from other nav items
            $('.featureList LI').removeClass('selected');

            // Add selected to next item
            navItem.addClass('selected');

            // Change image src

            $('.homepageFeatureGallery .images').animate({ top: '-' + moveTo + 'px' }, moveSpeed, 'easeOutQuint');


            // Change panel
            // Hide all panels
            $('.homepageFeatureGallery .panel').hide();
            // Show correct panel
            $('.homepageFeatureGallery .panel:eq(' + newItemIndex + ')').show();
        }

        // Loop
        function animateFeature() {
            // Get next nav item in list
            var navItem = $('.featureList LI.selected');

            // Set to loop through list items
            if (navItem.next().length == 0) {
                var navItem = $('.featureList LI').first();
            } else {
                var navItem = $('.featureList LI.selected').next();
            }

            changeFeature(navItem);
            animateTimer = setTimeout(animateFeature, 10000);
        };
        // Select first panel 
        changeFeature($('.homepageFeatureGallery .featureList LI:first'));

        // Start animating onLoad
        animateTimer = setTimeout(animateFeature, 10000);

        // Click
        $('.homepageFeatureGallery .featureList A').click(function () {
            // Stop animation
            clearTimeout(animateTimer);

            // Get NavItem
            navItem = $(this).parent();

            // Change Feature
            changeFeature(navItem);

            return false;
        });


        App.setProductBanners();


    };


    var sanitised = function (input) {
        return input.replace(/-/g, "_").replace(/ /g, "-").replace(/&/g, "[AND]").replace(/\?/g, "[QUES]");
    }


    /* Public */

    TVI.apply(cmp, {

        setProductBanners: function () {
            // Sale
            $('.sale').each(function () {
                $(this).find('A:first').append('<div class="saleOverlay" />');
            });
            // Pre Order
            $('.preOrder').each(function () {
                $(this).find('A:first').append('<div class="preOrderOverlay" />');
            });
            // inStock
            $('.inStock').each(function () {
                $(this).find('A:first').append('<div class="inStockOverlay" />');
            });
        },

        formatProducts: function (success) {

            // Product items
            var maxHeight = 0;
            $('.productItem:not(.fancyboxContent .productItem)').each(function () {
                // If height is bigger then increase max size
                if ($(this).height() > maxHeight) {
                    maxHeight = $(this).height();
                }
            });
            $('.productItem:not(.fancyboxContent .productItem)').each(function () {
                $(this).height(maxHeight);
            });

            // ROUNDED
            if ($('.borderradius') == undefined) {
                $('.rounded').append('<div class="tl"></div><div class="tr"></div><div class="br"></div><div class="bl"></div>');
            }
            $('.productItem img').batchImageLoad({
                loadingCompleteCallback: function () {
                    $('.productItem img').each(function () {
                        if ($(this).height() < 172) {
                            $(this).parent().css('height', $(this).height() + 'px');
                        }
                    });
                    success();
                }

            });

        },
        roundCorners: function () {
            // ROUNDED
            if ($('.borderradius') == undefined) {
                $('.rounded').append('<div class="tl"></div><div class="tr"></div><div class="br"></div><div class="bl"></div>');
            }
            $('.productItem img').batchImageLoad({
                loadingCompleteCallback: function () {
                    $('.productItem img').each(function () {
                        if ($(this).height() < 172) {
                            $(this).parent().css('height', $(this).height() + 'px');
                        }
                    });
                }

            });
        }


    });


    TVI.ready(init);


    return cmp;


} ();
