var richlite = window.richlite || {};

$(window).load(function($){
    richlite.main.init();
});

(function(){
    var main = {

        init: function() {
            this._setupNavMenu();
            this._setupNivoSlider();
            this._setupSearchForm();
            this._setupCollapsibleContainer();
            this._setupQuickNav();
            this._setupColorSwatchPopup();
            this._setupCustomScrollBar();
            this._autoScrollToThumbnail();
            this._setupThumbnailClickEvent();
            this._setupGalleryImageScrollButton();
            this._setupGalleryDownloadButton();
        },

        resetScrollArea: function() {
            var $scrollableTextArea = $('#articleNoteText, #productNoteText');
            $scrollableTextArea.mCustomScrollbar('vertical',0,'linear',1.05,"auto","yes","yes",20);
        },

        _setupNavMenu: function() {
            // setup the pull up menu list
            $('ul.navMenu').jMenu({
                    ulWidth: 200,
                    direction: 'down',
                    absoluteBottom: 30,
                    effects:{
                        effectSpeedOpen: 300,
                        effectSpeedClose: 200,
                        effectTypeOpen: 'slide',
                        effectTypeClose: 'fade',
                        effectOpen: 'linear',
                        effectClose: 'linear'
                    },
                    TimeBeforeOpening: 200,
                    TimeBeforeClosing: 200,
                    animatedText: true,
                    paddingLeft: 5
            });

            // setup the social links
            $('.social-ui').hover( function() {
                var $this = $(this),
                    type = $this.attr('socialType');
                    $this.addClass( type + '_over' );
            }, function() {
                var $this = $(this),
                    type = $this.attr('socialType');
                    $this.removeClass( type + '_over' );
            });
        },

        _setupNivoSlider: function() {
            // setup the slider on the home page
            if( $('.animateImageSlider').length > 0 ){
                $('#slider').nivoSlider({
                    effect                  : 'fold', // Specify sets like: 'fold,fade,sliceDown'
                    slices                  : 15, // For slice animations
                    boxCols                 : 8, // For box animations
                    boxRows                 : 4, // For box animations
                    animSpeed               : 700, // Slide transition speed
                    pauseTime               : 8000, // How long each slide will show
                    startSlide              : 0, // Set starting Slide (0 index)
                    directionNav            : true, // Next & Prev navigation
                    directionNavHide        : false, // Only show on hover
                    controlNav              : true, // 1,2,3... navigation
                    controlNavThumbs        : false, // Use thumbnails for Control Nav
                    controlNavThumbsFromRel : false, // Use image rel for thumbs
                    controlNavThumbsSearch  : '.jpg', // Replace this with...
                    controlNavThumbsReplace : '_thumb.jpg', // ...this in thumb Image src
                    keyboardNav             : true, // Use left & right arrows
                    pauseOnHover            : true, // Stop animation while hovering
                    manualAdvance           : false, // Force manual transitions
                    captionOpacity          : 0.95, // Universal caption opacity
                    prevText                : 'Prev', // Prev directionNav text
                    nextText                : 'Next', // Next directionNav text
                    beforeChange            : function(){}, // Triggers before a slide transition
                    afterChange             : function(){}, // Triggers after a slide transition
                    slideshowEnd            : function(){}, // Triggers after all slides have been shown
                    lastSlide               : function(){}, // Triggers when last slide is shown
                    afterLoad               : function(){} // Triggers when slider has loaded
                });

                // adjust the arrow location
                var nextArrowLeftPosition = 40 + $('.nivo-controlNav', '#slider').width() + 'px';
                $('a.nivo-nextNav', '#slider').css('left', nextArrowLeftPosition );
            }
        },

        _setupSearchForm: function() {
            if( $('#searchField').length > 0 ){
                $('#searchField').bind( 'focus blur', function( event ){
                    var et = event.type;

                    switch( et ){
                    case 'focus':
                        if( $(this).val() === 'Search' ){
                            $(this).val( '' ).removeClass('tips');
                        }
                        break;

                    case 'blur':
                        if( $(this).val() === '' ){
                            $(this).val( 'Search' ).addClass('tips');

                        }
                        break;

                    default:
                        break;
                }
                });
            }
        },

        _setupCollapsibleContainer: function() {
            // use this for the home page
            var targetContainer = '.nivo-caption, #productNotes, #articleNotes';
            $( targetContainer ).addClass('open').delegate( '.itemNotesTab', 'click', function() {
                //toggle the open / close class
                var $this = $(this);
                var $parent = $this.parents( targetContainer );
                $parent.toggleClass( function() {
                    if( $parent.is( '.close' ) ){ $parent.removeClass('close').animate( { right: 0
                        }, 800, 'easeOutQuad' );
                        return 'open';
                    } else {
                        $parent.removeClass('open').animate( {
                            right: -1 * $parent.width()
                        },  800, 'easeInQuad' );
                        return 'close';
                    }
                });
            });
        },

        _setupQuickNav: function() {
            var $qNavArea = $('#quickLink');
            if( $qNavArea.length > 0 ){
                var $headerList = $('h4', '.articleText'),
                    qNavString = '<h5>QUICK LINKS</h5>',
                    $additionalLinks = $('.moreLinks');
                qNavString += '<ul>';
                var $cHeaderData, cHeaderLabel;
                for (var i = 0; i < $headerList.length; i++) {
                    $cHeaderData = $( $headerList[i] );
                    cHeaderLabel = $cHeaderData.attr('label');
                    $cHeaderData.wrap('<a class="name" id="header_'+ i +'">');
                    qNavString += '<li>';
                    if( cHeaderLabel !== undefined ){
                        qNavString += '<a href="#header_'+ i +'">'+ cHeaderLabel.toUpperCase() + '</a>';
                    }else{
                        qNavString += '<a href="#header_'+ i +'">'+ $cHeaderData.text().toUpperCase() + '</a>';
                    }
                    qNavString += '</li>';
                }
                qNavString += '</ul>';
                $qNavArea.html( qNavString );
                if( $additionalLinks.length > 0 ){
                    $additionalLinks.remove();
                    $qNavArea.find('ul').append( $additionalLinks.html() );
                }

                // setup quick nav events
                $($qNavArea).delegate('a', 'click', function(event) {
                    if( !$( event.currentTarget ).hasClass('external') ){
                        event.preventDefault();
                        var $target = $( event.currentTarget ),
                        bookmarkName = $target.attr('href'),
                        $container = $('.container', '#articleNotes'),
                        parentContainerPosition = $container.parents('.customScrollBox').position().top,
                        containerMaxHeight = 25 + $container.height() - $('#articleNotes').height(),
                        newLocationY = -25 + (  -1 * Math.min( containerMaxHeight, $('a#' + bookmarkName ).position().top )),
                        scrollPercentage = ( newLocationY / containerMaxHeight ),
                        $scrollbar = $('.dragger', '#articleNotes'),
                        $scrollbarContainer = $('.dragger_container', '#articleNotes'),
                        newScrollLocation = -1 * scrollPercentage * ( $scrollbarContainer.height() - $scrollbar.height() );

                        // use animate to move the container
                        $container.animate({
                                top: newLocationY
                        }, 800);
                        // animate the scroll bar too
                        $scrollbar.animate({
                                top: newScrollLocation
                        }, 800);
                    }

                });
            }
        },

        _setupColorSwatchPopup: function() {
            var $colorSwatchArea = $('.colorList');
            if( $colorSwatchArea.length > 0 ){
                $colorSwatchArea.delegate( '.colorSwatchItem', 'click hover', $.proxy( function(event) {
                        event.stopPropagation();
                        var et = event.type,
                            $target = $( event.currentTarget );
                        switch( et ){
                        case 'click':
                            this._displayColorSwatchPopup( $target );
                            break;

                        case 'mouseenter':
                        case 'mouseover':
                            $target.addClass('hover');
                            break;

                        case 'mouseleave':
                        case 'mouseout':
                            $target.removeClass('hover');
                            break;

                        default:
                            break;
                        }
                }, this));
            }

            // setup the pop up close button
            $('#slider .itemImage').delegate( '.closeButton', 'click', $.proxy( function(event) {
                $( '.colorSwatchPopup' ).remove();
            }, this ));

        },

        _displayColorSwatchPopup: function( colorSwatchItem ) {
            // find previous color swatch and remove it from the screen
            var $previousPopup = $('.colorSwatchPopup'),
                cDescription = colorSwatchItem.find('.colorDescription').html(),
                cProductName = colorSwatchItem.parent().attr('productName'),
                cName = colorSwatchItem.find( '.colorName' ).text(),
                cImageUrl = colorSwatchItem.find( '.colorSwatch' ).attr('src');

            $previousPopup.parent().removeClass('hover').end().remove();
            if( $previousPopup.find('.colorPopupName').text() !== cName ){
                var swatchData = {
                    productName: cProductName,
                    name: cName,
                    description: cDescription,
                    imageUrl: cImageUrl
                };

                // create the pop up and place it on the color watch
                var popupHtml = $('#colorPopupPanel').tmpl( swatchData );
                popupHtml.appendTo( '#slider .itemImage' ).fadeOut( 0 ).fadeIn( 500 );
            }
        },

        _setupCustomScrollBar: function() {
            var $scrollableTextArea = $('#articleNoteText, #productNoteText');
            if( $scrollableTextArea.length > 0 ){
                $scrollableTextArea.mCustomScrollbar('vertical',0,'linear',1.05,"auto","yes","yes",20);

                // add the hover event on the arrow buttons
                $('.dragger_container').delegate('.scrollUpBtn, .scrollDownBtn', 'hover', function(event){
                    var target = event.currentTarget;
                    var et = event.type;

                    switch( et ){

                    case 'mouseenter':
                    case 'mouseover':
                        $(target).addClass('hover');
                        break;

                    case 'mouseleave':
                    case 'mouseout':
                        $(target).removeClass('hover');
                        break;

                    default:
                        break;
                    }
                });
            }
        },

        _autoScrollToThumbnail: function( scrollTime ) {
            if($('.galleryImage').length > 0){
                // get the current image id
                var imageID = $( '.galleryImage' ).attr( 'imageid' ),
                $thumbList = $( '.galleryThumbList' ),
                targetIndex = 0;

                // remove the previous selected item
                $( 'li.galleryThumbnailItem.selected' ).removeClass( 'selected' );
                // select the thumbnail with the same image id
                var selectedThumb = $thumbList.find( 'li[imageid="' + imageID + '"]' ).addClass( 'selected' );

                // set scroll time default
                if( scrollTime === undefined ){
                    scrollTime = 0;
                }


                targetIndex = Math.max( 0, $( selectedThumb ).index() - 3 );
                //$( '.galleryThumbnails' ).scrollTo( $( '.selected' ).prev().prev().prev(), scrollTime );
                $( '.galleryThumbnails' ).scrollTo( $( 'li', $thumbList )[ targetIndex ], scrollTime );
            }
        },

        _setupThumbnailClickEvent: function() {
            $('#slider .galleryThumbnails').delegate( 'li.galleryThumbnailItem>a', 'click', { scope: this }, function( event ) {
                event.preventDefault();
                var scope = event.data.scope;
                var $container = $(this).parent();
                var imageUrl = $container.find('img').attr( 'src' );
                var imageTitle = $container.attr( 'title' );
                var imageDescription = $container.attr( 'description' );
                imageUrl = imageUrl.split( '&w=120&h=90&' ).join( '&w=960&h=590&' );
                var imageID = $container.attr( 'imageid' );
                // update image
                $( '#slider .galleryImage' ).css( {
                    'background-image' : 'url(' + imageUrl + ')'
                }).attr( 'imageid', imageID );
                // update image title, description and download link
                $( '#imageNotes .imageTitle' ).html( imageTitle );
                $( '#imageNotes .imageDescription' ).html( imageDescription );
                var linkUrl = imageUrl.split( '&w=960&h=590&' ).join('&');
                $( 'a.downloadButton' ).attr( 'href', linkUrl );

                // scroll to the center
                scope._autoScrollToThumbnail( 700 );

                return false;
            });
        },

        _setupGalleryImageScrollButton: function() {
            if($('.galleryImage').length > 0){
                $('.galleryThumbnails').disableSelection();

                // check for image next and previous button
                if ( $('.galleryThumbList>ul').find('li.selected').prev( '.galleryThumbnailItem' ).length === 0 ){
                    $( '.scrollLeftBtn', '.galleryImage' ).hide();
                }
                if ( $('.galleryThumbList>ul').find('li.selected').next( '.galleryThumbnailItem' ).length  === 0  ){
                    $( '.scrollRightBtn', '.galleryImage' ).hide();
                }

                // check for scrolling thumbnail button
                if( true ){
                    $( '.scrollLeftBtn', '.galleryThumbnails' ).hide();
                    $( '.scrollRightBtn', '.galleryThumbnails' ).hide();
                }


                $('#content').delegate( '.scrollLeftBtn, .scrollRightBtn', 'hover click', $.proxy( function(event) {
                    var et = event.type,
                    $target = $( event.currentTarget ),
                    $targetParent = $target.parent(),
                    checkScrollButton = function() {
                    };

                    switch( et ){
                    case 'click':
                        if( $targetParent.hasClass( 'galleryImage' ) ){
                            var imageUrl = '';
                            if( $target.hasClass('scrollLeftBtn') ){
                                // find the previous image in the list
                                imageUrl = $('.galleryThumbList>ul').find('li.selected').prev( '.galleryThumbnailItem' ).find('a').attr('href');
                            } else if (  $target.hasClass('scrollRightBtn') ){
                                // find the next image in the list
                                imageUrl = $('.galleryThumbList>ul').find('li.selected').next( '.galleryThumbnailItem' ).find('a').attr('href');
                            }

                            window.location = imageUrl;
                        } else if(  $targetParent.hasClass( 'galleryThumbList' ) ){
                            if( $target.hasClass('scrollLeftBtn') ){
                                $targetParent.scrollTo( { left: '-=150' } );
                            } else if (  $target.hasClass('scrollLeftBtn') ){
                                $targetParent.parent().scrollTo( { left: '+=150' } );
                            }

                            checkScrollButton();
                        }
                        break;

                    case 'mouseenter':
                    case 'mouseover':
                        $target.addClass('hover');
                        break;

                    case 'mouseleave':
                    case 'mouseout':
                        $target.removeClass('hover');
                        break;

                    default:
                        break;
                    }
                }, this ));
            }
        },

        _setupGalleryDownloadButton: function() {
            if( $( 'a.downloadButton' ).length > 0  ){
                var $downloadButton = $( 'a.downloadButton' );
                var linkUrl = $downloadButton.attr( 'href' );
                linkUrl = linkUrl.split( '&w=960&h=590&' ).join( '&' );
                $downloadButton.attr( 'href', linkUrl );
            }
        },

        destroy: function() {

        }
    };

    richlite.main = main;
})();

