/**
 * @fileoverview frozThumbSlider plugin
 * @author Lawrence Natividad
 * @copyright Copyright ( c ) 2010 Frozynart Designs
 * @license Licensed under MIT ( http://www.frozynart.com/license/mit )
 * @version: 1.0 2010-09-27
 */
 
( function( $ ) {
    /**
     * all parameters
     * <ul> passes must have ID
     * all content banners must have the same dimensions
     * When thumbnails are clicked, contents slide over accordingly
     * @namespace frozThumbSlider Plugin Namespace
     * @requires jQuery 1.2.6 and above / jQuery Easing / jquery.color
     * @example jQuery( "#id-of-list-that-contains-contents" ).frozThumbSlider
     * @return {jQuery Object}
     */
    jQuery.fn.frozThumbSlider = function( options ) {
        var opts                            = jQuery.extend( {}, jQuery.fn.frozThumbSlider.defaults, options );
        jQuery.fn.frozThumbSlider.opts      = opts;
        var $this                           = jQuery( this );
        
        opts.wrapperId = opts.wrapperId + '-' + $this.attr('id');
        var mainContent = '#' + $this.attr('id');
        var wrapperId = '#' + opts.wrapperId;
        var contentCount = jQuery($this).children().length;
        
        jQuery( $this ).data( "activeSlide", 0 );
        
        var measureWidth = function( obj ){
            return obj.width();
        };
        
        var measureHeight = function( obj ){
            return obj.height();
        };
        
        var slideBack = function( diff, dimension, content ){
            jQuery( content ).animate( {"left": "+=" + ( diff * dimension ) + "px"}, opts.slideEasing );
        };

        var slideForward = function( diff, dimension, content ){
            jQuery( content ).animate( {"left": "-=" + ( diff * dimension ) + "px"}, opts.slideEasing );
        };

        var slideUp = function( diff, dimension, content ){
            jQuery( content ).animate( {"top": "+=" + ( diff * dimension ) + "px"}, opts.slideEasing );
        };

        var slideDown = function( diff, dimension, content ){
            jQuery( content ).animate( {"top": "-=" + ( diff * dimension ) + "px"}, opts.slideEasing );
        };
        
        var slideContent = function( count ){
            
            if (count > jQuery( $this ).data( "activeSlide")){
                difference = count - jQuery( $this ).data( "activeSlide");
                if (opts.slideVertical === false){
                    slideForward(difference, xDim, mainContent);
                } else {
                    slideDown(difference, yDim, mainContent);
                }
            } else {
                difference = jQuery( $this ).data( "activeSlide") - count;
                if (opts.slideVertical === false){
                    slideBack(difference, xDim, mainContent);
                } else {
                    slideUp(difference, yDim, mainContent);
                }
            };
        };
        
        var setHoverBoxOffset = function( box, start ){
            var pos = jQuery(opts.thumbList).position();
            var offsetTop = (jQuery(opts.thumbList + ' > li:eq(' + start + ')').outerHeight()
                           - jQuery(box).height())/2;
            var offsetLeft = (jQuery(opts.thumbList + ' > li:eq(' + start + ')').outerWidth()
                            - jQuery(box).width ())/2;
            var posLeft = pos.left + offsetLeft + opts.boxOffsetLeft;
            var posTop = pos.top + offsetTop + opts.boxOffsetTop;
            jQuery(box).css({ left: posLeft, top: posTop })
        }
        
        var slideTab = function( count ){
            
            if (count > jQuery( $this ).data( "activeSlide")){
                difference = count - jQuery( $this ).data( "activeSlide");
                if (opts.thumbsVertical === false){
                    slideBack(difference, thumbsX, opts.hoverBox);
                } else {
                    slideUp(difference, thumbsY, opts.hoverBox);
                }
            } else {
                difference = jQuery( $this ).data( "activeSlide") - count;
                if (opts.thumbsVertical === false){
                    slideForward(difference, thumbsX, opts.hoverBox);
                } else {
                    slideDown(difference, thumbsY, opts.hoverBox);
                }
            };
        };
        
        var selectTab = function( obj ){
            jQuery(opts.thumbList + ' > li').each( function(){
               jQuery(this).removeClass('selected'); 
            });
            jQuery(obj).addClass('selected');
        };
        
        var detectDefaultBoxColor = function(){
            if ( jQuery(opts.hoverBox).css('background-color') == 'transparent' ){
                return opts.defaultColor;
            }
            return jQuery(opts.hoverBox).css('background-color');
        }
        
        var blockAnimate = function( obj, defColor ){


            if (jQuery(obj).attr('rel') !== undefined){
                var newColor = '#' + jQuery(obj).attr('rel').substring(1).toUpperCase();
            } else {
                var newColor = defColor;
            }

//            if ( newColor.indexOf('rgba(') !== -1 ){
//                var colorArray = defColor.substring(5).split(',');
//                newColor = '#' + (colorArray[0] + 256 * colorArray[1] + 65536 * colorArray[2]).toString(16);
//            }
            
//            alert(newColor)
            jQuery(opts.hoverBox).animate({backgroundColor: newColor}, { queue: false, duration: opts.colorChangeTime });
            
        };
        
        xDim = measureWidth( jQuery('li:first', $this) );
        yDim = measureHeight( jQuery('li:first', $this) );
        
        $this.wrap( "<div id=" + opts.wrapperId + " />" );
        jQuery( wrapperId ).css( {position: "relative",
                                  width:xDim,
                                  height:yDim,
                                  overflow: 'hidden'} );
        
//        if ( navigator.appVersion.match('MSIE 7.0') !== null){
//            jQuery( wrapperId ).css( { top: '-29px'} );
//        } else {
//            jQuery( wrapperId ).css( { top: '-4px'} );
//        }
        
        if ( true === opts.slideVertical ){
            jQuery( mainContent ).css( {height: (yDim * contentCount)} )
            jQuery( mainContent + " > li" ).each( function(){
//                jQuery( this ).css( {float:"top"} );
                jQuery(this)[0].style.cssFloat = jQuery(this)[0].style.styleFloat = 'left';
            } );
        }
        else{
            jQuery( mainContent ).css( {width: (xDim * contentCount)} )
            jQuery( mainContent + " > li" ).each( function(){
//                jQuery( this ).css( {float:"left"} );
                jQuery(this)[0].style.cssFloat = jQuery(this)[0].style.styleFloat = 'top';
            } );
        }
        
        if (jQuery( opts.thumbList + ' > li:eq(1)').length === 0){
            jQuery(opts.thumbList).remove();
            if (opts.hoverOption === true){
                jQuery(opts.hoverBox).remove();
            }
            return false;
        }
        
        offset1 = jQuery( opts.thumbList + ' > li:first > a:first').offset();
        offset2 = jQuery( opts.thumbList + ' > li:eq(1) > a:first').offset();
        thumbsX = offset2.left - offset1.left;
        thumbsY = offset2.top - offset1.top;
        
        if ( opts.starterSlide !== 0){
            slideContent( opts.starterSlide );
        }
        
        if (opts.hoverOption === true){
            setHoverBoxOffset( opts.hoverBox, opts.starterSlide );
            var defColor = detectDefaultBoxColor();
            blockAnimate( jQuery( opts.thumbList + ' > li:eq(' + opts.starterSlide + ')'), defColor );
            slideTab( opts.starterSlide );
        }
        
        
        var setAutoSlide = function(head){
            head.data('btnList', jQuery(document).find('ul' + opts.thumbList));
        
            var mainTimer = jQuery.timer( head.data('autoSlide'), function( timer ) { 
                var activeCount = head.data('btnList').find('li.selected').prevAll().length;
                var listLength = head.data('btnList').children('li').length;

                if ( activeCount >= (listLength - 1) ){
                    activeCount = 0;
                } else {
                    activeCount += 1;
                }

                head.data('btnList').children('li:eq(' + activeCount + ')').click();
            });
            
            head.data('carouselTimer', mainTimer);
            return head;
        }
        
        var setHoverHold = function(head){
            head.hover( function(){
                head.data('carouselTimer').stop();
            }, function(){
                head.data('carouselTimer').reset(head.data('autoSlide'));
            });
            
            head.data('btnList').hover( function(){
                head.data('carouselTimer').stop();
            }, function(){
                head.data('carouselTimer').reset(head.data('autoSlide'));
            });
        }
        
        selectTab( opts.thumbList + ' > li:eq(' + opts.starterSlide + ')');
        jQuery( $this ).data( "activeSlide", opts.starterSlide );

        jQuery( opts.thumbList + ' > li').each( function(){
            jQuery(this).click( function(){
                nthCount = jQuery(this).prevAll().length;
                if( nthCount !== jQuery( $this ).data( "activeSlide")){
                    if (opts.queueEffects === false){
                        jQuery( mainContent ).stop( false, true );
                        if (opts.hoverOption === true){
                            jQuery( opts.hoverBox ).stop( false, true );
                        }
                    }
                    slideContent( nthCount );
                    if (opts.hoverOption === true){
                        blockAnimate( jQuery(this), defColor );
                        slideTab( nthCount );
                    }
                    selectTab( this );
                    jQuery( $this ).data( "activeSlide", nthCount )
                }
                return false;
            });
        });     
        
        if ( opts.autoSlide !== false ){
            jQuery($this).data('autoSlide', opts.autoSlide);
            var head = setAutoSlide($this);
            
            if (opts.hoverHold === true){
                setHoverHold(head);
            }
        }

        return $this;
    };

    /** 
     * Sends a message to the console
     * @private
     */
    var _debug = function( message ) {
        if ( true === jQuery.fn.frozThumbSlider.opts.debug ) {
            console.log( message );
        }
    };
    
    jQuery.fn.frozThumbSlider.defaults =   {
        thumbList: null,
        hoverOption: false,
        hoverBox: null,
        wrapperId: 'froz-thumb-slider-wrapper',
        slideVertical: false,
        thumbsVertical: false,
		slideEasing: "easeInOutExpo",
		defaultColor: '#00AA00',
		boxOffsetLeft: 0,
		boxOffsetTop: 0,
		colorChangeTime: 700, //amount of time that is color effect is delayed
		queueEffects: false,
        starterSlide: 0,
        
        autoSlide: false,
        hoverHold: true
    };
} )(jQuery);

