// Scrolling Controller
var Scrolling = {
	divids : new Array(),
	divloc : new Array(),
	imgarray: new Array(),
	hrefarray: new Array(),
	collectionnavarray: new Array(),
    scrollContainer : '#scrollcontent',
    scrollInterval : false,
    controls : {
        'back' : $('<div class="scroll_wrap" id="scroll_right"><a class="horz_scroll_arrow replace"></a></div>').hide(),
        'forward' : $('<div class="scroll_wrap" id="scroll_left"><a class="horz_scroll_arrow replace" id="back"></a></div>')
    },
    init : function(container) {
        var that = this;
        this.scrollContainer = container || '#scrollcontent';
		Scrolling.setCollectionIds();
		Scrolling.setScrollContentItems();
        Scrolling.controls.forward.bind('mouseover', this.forward).
                bind('mouseout', {'direction' : 'forward'},
                function() {
                    if (!that.doingAutoscroll) {
                        clearInterval(Scrolling.scrollInterval);
                        $(Scrolling.scrollContainer).stop();
                    }
                }).
                bind('click', function() {
            clearInterval(Scrolling.scrollInterval);
            $(Scrolling.scrollContainer).stop();
            Scrolling.doScrollClick(1);
        });
        Scrolling.controls.back.bind('mouseover', this.back).
                bind('mouseout', {'direction' : 'back'},
                function() {
                    if (that.doingAutoscroll) return false;
                    clearInterval(Scrolling.scrollInterval);
                    $(Scrolling.scrollContainer).stop();
                }).
                bind('click', function() {
            clearInterval(Scrolling.scrollInterval);
            $(Scrolling.scrollContainer).stop();
            Scrolling.doScrollClick(-1);
        });
		$( 'nav.collectionNavigation' ).find( 'a' ).each( function ( i ) {
			Scrolling.collectionnavarray.push( $( this ) );
			Scrolling.hrefarray.push( $( this ).attr( 'href' ) );
		    $( this ).click( function ( event ) {
		        event.preventDefault();
		        $( '#scrollcontent' ).scrollLeft( Scrolling.divloc[i] );
		        Scrolling.turnon( i );
		    });
		});
        setTimeout(function() {
			var singleCWidth = $( Scrolling.imgarray[0] ).width(),
				bWidth = Utils.getBrowserDims( 'width' ),
				altLeft = 0;
			if ( $( 'nav.collectionNavigation a' ).size() === 1 ) {
				$( 'nav.collectionNavigation' ).css( 'visibility','hidden' );
				if ( singleCWidth > bWidth ) {
					$('body').append(Scrolling.controls.forward, Scrolling.controls.back);
				} else {
					altLeft = bWidth - singleCWidth;
					$( '.scrollMe' ).css( 'left', altLeft + 'px' );
				}
			} else {
				$('body').append(Scrolling.controls.forward, Scrolling.controls.back);
			}
			PDP.init();
			DLS.init();
        }, 500);
        var _this = this;
    },
    stop : function(e) {
        $('.' + containers['scrollArea']).stop();
    },
    forward : function() {
        Scrolling.controls.back.fadeIn();
        Scrolling.doScroll(1);
    },
    back : function() {
        Scrolling.controls.forward.fadeIn();
        Scrolling.doScroll(-1);
    },
    autoScroll: function(direction) {
        return true;
        direction = direction || 1;
        var amount = direction ? 1000 : 0;
        var time = 1000;
        var scrollMe = $(Scrolling.scrollContainer);
        var that = this;
        that.doingAutoscroll = true;
        scrollMe.stop().animate({scrollLeft :  amount}, time, 'swing', function() {
            that.doingAutoscroll = false;
        });
    },
    doScrollClick : function(where) {
        var time = 800;
        var amount = 400 * where;
        var scrollMe = $(Scrolling.scrollContainer);
		var slide = scrollMe;
        var current = scrollMe.scrollLeft();
		var newPosition = slide.scrollLeft();
        scrollMe.animate({scrollLeft :  current += amount}, time, 'swing', function() {
            if (scrollMe.scrollLeft() <= 0) {
                Scrolling.controls.back.hide();
            }
        });
		Scrolling.notify(newPosition, amount);
    },
    doScroll : function(where) {
        var time = 800;
        var amount = 400 * where;
        var scrollMe = $(Scrolling.scrollContainer);
        var current = scrollMe.scrollLeft();
        scrollMe.animate({scrollLeft :  current += amount}, time, 'linear', function() {
            if ($(this).scrollLeft() == 0) {
                Scrolling.controls.back.hide();
            }
        });
        var _this = this;
        Scrolling.scrollInterval = setInterval(function() {
            var slide = scrollMe;
            var current = slide.scrollLeft();
            slide.animate({scrollLeft :  current += amount}, time, 'linear', function() {
                var newPosition = slide.scrollLeft();
                if (newPosition == 0) {
                    Scrolling.controls.back.fadeOut();
                }
                Scrolling.notify(newPosition, amount);
            })
        }, time);
    },
	turnon : function( i, hasHash ) {
		log( '-->Scrolling.turnon()' );
		for(j=0;j<Scrolling.divids.length;j++) {
			if (j==i) {
				$( '#' + Scrolling.divids[j]).show();
				log( 'Testing for hasHash: ' + hasHash );
				if ( hasHash !== true ) {
					DLS.prepHashAdd( Scrolling.hrefarray[j], 1 );
				}
				DLS.collectionOnState( Scrolling.collectionnavarray[j] );
			}  else {
				$( '#' + Scrolling.divids[j]).hide();
			}
		}
	},
    notify : function(position, dir) {
		var winWidth = Utils.getBrowserDims( 'width' );
		var bOffsetMidLeft = parseInt( Utils.getBrowserDims( 'width', 'true' )[0] ) - 200;
		var bOffsetMidRight = bOffsetMidLeft + 400;
        for( i = Scrolling.divids.length - 1; i >= 0; i-- ) {
			if ( position > Scrolling.divloc[i] - parseInt( Utils.getBrowserDims( 'width', 'true' )[0] ) ) {
				Scrolling.turnon(i);
				return;
			}
			
        }
    },
	setCollectionIds: function () {
		$( '.CollectionContainer' ).find( 'article.Collection' ).each( function ( i ) {
		    $( this ).attr( 'id', 'prod' + i );
			Scrolling.divids.push( 'prod' + i );
			if ( i !== 0 ) { $( this ).hide() };
		});
	},
	setScrollContentItems: function () {
		var setWidth = 0;
		$( '#scrollcontent' ).find( 'img' ).each( function() {
		    setWidth = setWidth + $( this ).width();
		});
		$( '.scrollMe' ).css( 'width', setWidth + 'px' );
		$( '#scrollcontent' ).find( 'img' ).each( function() {
			Scrolling.imgarray.push( $( this ) );
			Scrolling.divloc.push( Math.round( Utils.itemOffset( $( this ), 'left' ) ) );
		});
	}
}; //-- Scrolling

// Product Detail Page Controller
var PDP = {
	
	AjaxTemplateParam: '?Template=/v2/templates/master-ajax.jsp',
	ProductURL: '',
	CloseBtnWidth: 0,
	ContentHeight: 0,
	ContentHeightInit: 0,
	IsDisplayed: false,
	
	init: function () {
		log( '---->PDP.init()' );
		PDP.createContainer();
		$( '.CollectionContainer' ).find( 'area' ).each( function () {
			$( this ).click( function ( event ) {
				event.preventDefault();
				if ( PDP.IsDisplayed === true ) return;
				PDP.IsDisplayed = true;
				SS.setLoadingGraphic( 'FADEIN' );
				if ( $( 'section.Detail' ).hasClass( 'isSlid' ) !== false ) return; // keep from firing multiple times
				PDP.ProductURL = $( this ).attr( 'href' );
				DLS.prepHashAdd( PDP.ProductURL, 2 );
				SS.doAjax( $( this ).attr( 'href' ) + PDP.AjaxTemplateParam, 60000, true, PDP.preFetchData );
			});
		});
	}, //-- PDP.init()
	
	createContainer: function () {
		log( '---->PDP.createContainer()' )
		$( '<div id="PreFetch"></div>' ).appendTo( '#page' );
	}, //-- PDP.createContainer()
	
	preFetchData: function ( data ) {
		log( '---->PDP.preFetchData()' );
		$( '#PreFetch' ).append( innerShiv( data, false ) );
		PDP.buildPDP( $( '#PreFetch' ).find( 'section.Detail' ) );
		$( '#PreFetch' ).html( '' );
	}, //-- PDP.preFetchData()
	
	buildPDP: function ( page ) {
		log( '---->PDP.buildPDP()' );
		var initPDPLeft = Utils.getBrowserDims( 'width' ), initPDPTop = Utils.itemOffset( $( 'section.Category' ), 'top' );
		$( 'section.Detail' ).addClass( 'isSlid' );
		$( 'section.Detail.isSlid' ).css({
			'left': initPDPLeft + 'px',
			'top': initPDPTop + 'px'
		});
		$( 'section.Detail' ).attr( 'data-role', PDP.ProductURL );
		PDP.ProductURL = '';
		$( page ).appendTo( 'body' );
		SS.setRecoPosition(); // baselines reco images
		SS.headerImageReplace( true ); // hide header image if exists
		PDP.slidePage( 'left' );
	}, //-- PDP.buildPDP()
	
	setupCloseButton: function () {
		log( '---->PDP.setupCloseButton()' );
		$( 'section.Detail' ).append( '<div id="PDPClose"><span class="PDPCloseIcon">' + $( 'section.Detail' ).find( '#CloseButtonIcon' ).text() + "</span>" + $( 'section.Detail' ).find( '#CloseButtonText' ).text() + '</div>' );
		PDP.CloseBtnWidth = $( '#PDPClose' ).outerWidth() + 1;
		$( '#PDPClose' ).css( 'marginLeft', '-' + PDP.CloseBtnWidth + 'px' );
		$( '#PDPClose' ).fadeIn( 300 );
		$( '#PDPClose' ).click( function () {
			PDP.slidePage( 'right' );
			Utils.addHash( 'Collection', Utils.queryHash( 'Collection' ), '=' );
		});
	}, //-- PDP.setupCloseButton()
	
	slidePage: function ( direction ) {
		log( '---->PDP.slidePage()' );
		var sectionWidthBase = 883, setLeftPos = parseInt( Utils.itemOffset( $( 'header' ), 'left' ) ), bWidth = Utils.getBrowserDims( 'width' );
		switch ( direction.toLowerCase() ) {
			case 'left':
				PDP.setupCloseButton();
				setLeftPos = setLeftPos + PDP.CloseBtnWidth;
				var sectionWidth = $( 'body' ).width() - setLeftPos;
				if ( bWidth <= 1023 ) { sectionWidth = sectionWidthBase; }
				$( 'section.Detail' ).css( 'width', sectionWidth + 'px' );
				$( 'section.Detail' ).animate({
					left: setLeftPos + 'px'
				}, 1000, 'easeOutBack', function() {
					PDP.testHeightDiff();
					$( '.scroll_wrap' ).fadeOut();
					PDP.ContentHeightInit = $( '#scrollcontent' ).height();
					SS.setLoadingGraphic( 'OFF' );
				});
				break;
			case 'right':
				$( 'section.Detail' ).css( 'width','100%' );
				$( 'section.Detail' ).animate({
					left: ( bWidth - setLeftPos ) + 'px'
				}, 750, 'easeInBack', function () {
					$( 'section.Detail' ).remove();
					$( '.scroll_wrap' ).fadeIn();
					PDP.testHeightDiff( 'true' );
					PDP.IsDisplayed = false;
				});
				break;
			default: log( '-->ERROR: PDP.slidePage() - direction switch passed bad value: ' + direction + '\nShould be right or left' );
		}
	}, //-- PDP.slidePage()
	
	testHeightDiff: function ( reset ) {
		log( '---->PDP.testHeightDiff()' );
		var adjustmentStyles = ( parseInt( $( '#scrollcontent' ).css( 'top' ).replace( 'px','' ) ) * 2 ) + parseInt( $( '#scrollcontent' ).css( 'marginTop' ).replace( 'px','' ) );
		var calloutOffset = $( 'aside.calloutTabs' ).height() - parseInt( $( 'aside.calloutTabs' ).css( 'top' ) );
		if ( $('aside.calloutTabs').find( 'a' ).size() !== 0 ) {
			PDP.ContentHeight = $( '#scrollcontent' ).height() + adjustmentStyles + calloutOffset;
			log( 'hasAside: ' + PDP.ContentHeight );
		} else {
			PDP.ContentHeight = $( '#scrollcontent' ).height() + adjustmentStyles;
			log( 'no aside: ' + PDP.ContentHeight );
		}
		var detailHeight = $( 'section.Detail' ).height();
		var adjContentHeight = detailHeight - ( $( '#scrollcontent' ).height() + ( parseInt( $( '#scrollcontent' ).css( 'top' ).replace( 'px','' ) ) * 2 ) + parseInt( $( '#scrollcontent' ).css( 'marginTop' ).replace( 'px','' ) ) );
		if ( reset === 'true' ) {
			$( '#scrollcontent' ).animate({
				height: PDP.ContentHeightInit
			}, 100, 'linear' );
		} else {
			if ( PDP.ContentHeight > detailHeight ) {
				$( 'section.Detail' ).animate({
					height: PDP.ContentHeight
				}, 100, 'linear' );
			} else if ( detailHeight > PDP.ContentHeight ) {
				$( '#scrollcontent' ).animate({
					height: ( PDP.ContentHeight + adjContentHeight ) - adjustmentStyles
				}, 100, 'linear' );
			}
		}
	} //-- PDP.testHeightDiff()
	
}; //-- PDP

// Deep Linking Controller
var DLS = {
	
	HashArray: {
		Collection: Utils.queryHash( 'Collection' ),
		Variant: Utils.queryHash( 'Variant' )
	},
	
	init: function () {
		log( '---->DLS.init()' );
		DLS.checkForHash();
	}, //-- DLS.init()
	
	checkForHash: function () {
		log( '---->DLS.checkForHash()' );
		if ( Utils.queryHash( 'Collection' ) === false ) {
			DLS.collectionOnState( $( 'nav.collectionNavigation a:first' ) );
			DLS.prepHashAdd( $( 'nav.collectionNavigation a:first' ).attr( 'href' ), 1 );
		} else {
			$( 'nav.collectionNavigation a ' ).each( function () {
				if ( DLS.parseDataURL( $( this ).attr( 'href' ), 1 ).toString() === DLS.HashArray.Collection ) {
					DLS.collectionOnState( $( this ) );
				}
			});
			for ( cItem in Scrolling.collectionnavarray ) {
				if ( Scrolling.collectionnavarray[cItem].hasClass( 'ON' ) ) {
					$( '#scrollcontent' ).scrollLeft( Scrolling.divloc[cItem] );
					if ( Utils.queryHash( 'Variant' ) !== false ) {
						Scrolling.turnon( cItem, true );
					} else {
						Scrolling.turnon( cItem );
					}
				}
			}
			if ( Utils.queryHash( 'Variant' ) !== false ) {
				var matchCombo = DLS.HashArray.Collection + '/' + DLS.HashArray.Variant;
				$( '.CollectionContainer map' ).find( 'area' ).each( function () {
					try {
						if ( $( this ).attr( 'href' ).indexOf( matchCombo ) !== -1 ) {
							SS.doAjax( $( this ).attr( 'href' ) + PDP.AjaxTemplateParam, 60000, true, PDP.preFetchData );
						}
					} catch ( e ) {
						log( 'No such Collection/Variant Exists: ' + matchCombo + '\nError: ' + e );
					}
				});
			}
		}
	}, //-- DLS.checkForHash()
	
	parseDataURL: function ( item, hashLevel ) {
		try {
			var itemURL = item,
			itemArray = itemURL.split( '/' ),
			extensionArray = itemURL.split( '/' ),
			getExtension = extensionArray.pop().split( '.' ),
			fullExtension = '.' + getExtension[getExtension.length - 1],
			hashArray = [];
			if ( hashLevel === 2 ) {
				hashArray.push( itemArray[itemArray.length - 2] );
				hashArray.push( itemArray[itemArray.length - 1].replace( fullExtension, '' ) );
				return hashArray;
			} else if ( hashLevel === 1 ) {
				hashArray.push( itemArray[itemArray.length - 1].replace( fullExtension, '' ) );
				return hashArray;
			}
		} catch ( e ) {
			log( '-->ERROR: DLS.parseDataURL(): ' + e );
		}
	}, //-- DLS.parseDataURL()
	
	collectionOnState: function ( item ) {
		$( 'nav.collectionNavigation a' ).each( function () {
			$( this ).removeClass( 'ON' ).removeClass( 'isPage' );
		});
		$( item ).addClass( 'ON' ).addClass( 'isPage' );
		SS.collectionNavHover();
	}, //-- DLS.collectionOnState()
	
	prepHashAdd: function ( url, level ) {
		log( '---->DLS.prepHashAdd()' );
		switch ( level ) {
			case 1:
				Utils.addHash( 'Collection', DLS.parseDataURL( url, level ).toString(), '=' );
				break;
			case 2:
				var sectionData = DLS.parseDataURL( url, level ), hashArray = ['Collection','Variant'], falsyArray = [false, true];
				for ( section in sectionData ) {
					Utils.addHash( hashArray[section], sectionData[section], '=', falsyArray[section] );
				}
				break;
			default: log( '-->ERROR: DLS.prepHashAdd() - switch passed bad value: ' + level + '\nShould be 1 or 2' );
		}
	} //-- DLS.prepHashAdd()
	
}; //-- DLS

$(document).ready( function () {
	SS.setLoadingGraphic( 'ON' );
	Scrolling.init("#scrollcontent");
	$('#scrollcontent').scrollLeft(0);
});

$(window).load( function () {
	SS.setLoadingGraphic( 'OFF' );
});
