var slider = Class.create();
Object.extend(slider.prototype, Event.Listener);
Object.extend(Object.extend(slider.prototype, AC.Slider.prototype), {

	createArrows: function() {
		// previous arrow
		this.prevArrow = Builder.node('a', { 'class':'ACSliderPreviousArrow' }, '&lt;');
		Event.observe(this.prevArrow, 'click', function(evt) {
			Event.stop(evt);
			if (this.currentPage!=1) this.getPrevious();
		}.bind(this));
		this.container.appendChild(this.prevArrow);

		// next arrow
		this.nextArrow = Builder.node('a', { 'class':'ACSliderNextArrow' }, '&gt;');
		Event.observe(this.nextArrow, 'click', function(evt) {
			Event.stop(evt);
			if (this.currentPage!=this.totalPages) this.getNext();
		}.bind(this));
		this.container.appendChild(this.nextArrow);
	},

	// get's called in initialize upon construction
	populate: function() {
		var items = $$('.slideritem');
		for (var i=0; i<items.length; i++) {
			var html = items[i].down();
			var sliderItem = new AC.SliderItem(html);
			this.items.push(sliderItem);
			items[i].remove();
		}

		this.render(7);

	},

	scrolltoPageNumber: function(toPageNumber, direction) {
		// if we're not going to the current page & we're not already doing something ...
		if (this.currentPage != toPageNumber && !this.isAnimating) {

			// if we don't know the direction, figure it out (-1 is next, 1 is previous)
			if (!direction) var direction = this.currentPage-toPageNumber;

			var prop3 = (direction==1) ? 'Left Arrow' : 'Right Arrow';
			AC.Tracking.trackClick({
				prop3: document.title+' - Slider Button - '+prop3
			}, this, 'o', document.title);

			this.isAnimating = true;

			// set the current page to the one we're going to
			this.currentPage = toPageNumber;
			// and fix the number if we're going to before the first page or page after the last page
			this.resetPages();

			// remove the 'active' class on the page nav items
			var pageNavAnchors = this.pageNav.getElementsByTagName('a');
			for (var i=0, anchor; anchor=pageNavAnchors[i]; i++) {
				if (Element.hasClassName(anchor, 'active')) Element.removeClassName(anchor, 'active');
				if (anchor.innerHTML==this.currentPage) Element.addClassName(anchor, 'active');
			}

			// do the scroll
			var options = {
				duration: 0.5,
				queue: { position:'end', scope:'sliderQueue', limit:1 },
				afterFinish: this.afterScroll.bind(this)
			};

			// TODO slider needs to be reworked, pretty inflexible
			//may not always have the mask dimensions prior to this point.
			//probably need to maintain a reference to the mask itself to 
			//recalculate the dimendions if necessary. Only recalculating 
			//if it's 0 right now but could do it more often to aid in
			//flexibile resizing
			if (!this.maskInnerDimension) {
				this.positionWithinMask(this.container);
			}

			if (this.orientation == 'horizontal') {
				new Effect.MoveBy(this.list, 0, this.maskInnerDimension*direction, options);
			} else {
				new Effect.MoveBy(this.list, this.maskInnerDimension*direction, 0, options);
			}
		} else {
			this.resetArrows();
		}
	},

	resetArrows: function() {
		if (this.prevArrow) this.prevArrow.removeClassName('inactive');
		if (this.nextArrow) this.nextArrow.removeClassName('inactive');

		if (this.currentPage == 1 && this.prevArrow) {
			this.prevArrow.addClassName('inactive');
		} else if (this.currentPage == this.totalPages && this.nextArrow) {
			this.nextArrow.addClassName('inactive');
		}
	},

	resetPages: function() {
		this.resetArrows();

		if (this.currentPage == 0) {
			this.currentPage = this.totalPages;
			this.positionOffset = -this.maskInnerDimension*this.totalPages + 'px';
			this.prevArrow.addClassName('inactive');
		} else if (this.currentPage == 1) {
			this.currentPage = 1;
			this.positionOffset = -this.maskInnerDimension + 'px';
		} else if (this.currentPage == this.totalPages+1) {
			this.currentPage = 1;
			this.positionOffset = -this.maskInnerDimension+'px';
			this.nextArrow.addClassName('inactive');
		} else {
			this.positionOffset = false;
		}
	}

});

Event.onDOMReady(function() {

	// tracker and delegate
	var trackerDelegate = {
		trackingNameForSection: function(tracker, name, section) {
			tracker.count++;
			if (name.match('design_overlay')) return false;
			if (name.match('Step')) return false;
			if (tracker.count > 1) return name;
			return false;
		},
		
		sectionDidChange: function(tracker, view, incoming, id, properties) {
			properties.prop25 = properties.pageName;
			return properties;
		},
		
		QTdidBegin: function(tracker, properties) {
			properties.prop25 = properties.pageName;
			return properties;
		}
	}
	var tracker = new AC.ViewMaster.Tracker('click');
	tracker.setDelegate(trackerDelegate);

	$$('a.slideshow-action').each(function(downloadLink) {
		downloadLink.observe('mousedown', function(evt) {
			AC.Tracking.trackClick({
				prop3: document.title.replace(/Apple - /,'') + ' - Play Sildeshow Button (US)'
			}, this, 'o', document.title.replace(/Apple - /,'')  + ' - Play Slideshow Button');
		});
	})
	
	// change the overlay background for each overlay
	var overlayBackground = function(evt) {
		var overlay = evt.event_data.data.sender;
		var incoming = evt.event_data.data.incomingView;

		if (overlay && typeof(overlay.setOverlayShadowImageSrc) == 'function' && incoming) {
			if (incoming.id == 'designvideo') {
				overlay.setOverlayShadowImageSrc('http://images.apple.com/euro/macbookpro/images/overlay-videobg20081014.png');
			} else {
				AC.Tracking.trackPage({
					pageName: document.title.toString().replace('Apple - ', '') +' - Overlay (US)'
				});
				overlay.setOverlayShadowImageSrc('http://images.apple.com/euro/macbookpro/images/overlay-batterybg20090106.png');
			}
		}
	}

	Event.Listener.listenForEvent(AC.ViewMaster, 'ViewMasterWillShowNotification', false, overlayBackground);

	// monsterlay...
	var gallerySections = $$('#design_overlay > ul > li > a.overlaythumb');

	var galleryViewMaster = new AC.ViewMaster.SlideshowViewer(gallerySections, 'designSwapView', 'overlaythumb', null, {
		parentSectionId: 'design_overlay',
		parentTriggerClassName: 'OverlayPanel',
		silentTriggers: true,
		delay: 6000,
        willEnd: true,
		triggerEvent: ['overlay:clicked', 'click']
	});

	var galleryViewMasterDelegate = {
		willShow: function(overlayPanel, outgoing, incoming) {
			if(incoming && incoming.id === 'space') {
				//alert('showing unibody');
			}
		}
	}
	galleryViewMaster.setDelegate(galleryViewMasterDelegate);
	var aSlider = new slider('slider');
	aSlider.direction = -1;

	var pageController = {
		isGalleryViewMasterSlideshowPlaying: false,
		isGalleryViewMasterSlideshowPaused: false,
		isMotionPicturePlaying:false,
		motionPicturePlaying:null,
		shouldStartGalleryViewMasterSlideshow:false,
        _stopSlideShow: function() {
            this.isGalleryViewMasterSlideshowPlaying = false;
            this.shouldStartGalleryViewMasterSlideshow = false;
            if (this.isMotionPicturePlaying) {
                //this.motionPicturePlaying.stop();
                this.motionPicturePlaying = null;
                this.isMotionPicturePlaying = false;
            }
            galleryViewMaster.slideshow.stop();
            this.slideShowTrigger.removeClassName('playing');
        },
        sliderClicked:  function(evt) {
            if(this.isGalleryViewMasterSlideshowPlaying === true) {
                this._stopSlideShow();
            }
        },
        _slideShowProgressionNavDisplay: null,
        startStopSlideShow:  function(evt) {
            if(!this.isGalleryViewMasterSlideshowPlaying == true) {
                this.isGalleryViewMasterSlideshowPlaying = true;
				if (this.isMotionPicturePlaying) {
					this.shouldStartGalleryViewMasterSlideshow = true;
                }
                else if(this.isGalleryViewMasterSlideshowPlaying === true) {
                    this.isGalleryViewMasterSlideshowPaused = true;
					galleryViewMaster.slideshow.start();
                }
                this.slideShowTrigger.addClassName('playing');
                this._slideShowProgressionNavDisplay = pageController.slideShowProgressionNav.style.display;
                pageController.slideShowProgressionNav.style.display = "none";
            }
            else {
				if (this.isMotionPicturePlaying) {
					this.shouldStartGalleryViewMasterSlideshow = false;
                }
                else {
					galleryViewMaster.slideshow.stop();
                }
                this.isGalleryViewMasterSlideshowPlaying = false;
                this.slideShowTrigger.removeClassName('playing');
                pageController.slideShowProgressionNav.style.display = this._slideShowProgressionNavDisplay;
            }
        
        
        },
        slideShowNextAction: function(evt) {
            evt.stop();
            
            AC.Tracking.trackClick({
                    prop3: document.title+' - Next Button'
                }, this, 'o', document.title);
                
            this.prepareForManualNavigationWhilePlaying();
            galleryViewMaster.next();
        },
        prepareForManualNavigationWhilePlaying: function() {
            if(this.isGalleryViewMasterSlideshowPlaying == true) {
                galleryViewMaster.slideshow.stop();
                if (this.isMotionPicturePlaying) {
                    //this.motionPicturePlaying.stop();
                    this.motionPicturePlaying = null;
                    this.isMotionPicturePlaying = false;
                }
                galleryViewMaster.slideshow.start();
            
            }
        },
        slideShowPreviousAction: function(evt) {
            evt.stop();
            
            AC.Tracking.trackClick({
                    prop3: document.title+' - Back Button'
                }, this, 'o', document.title);
                
            aSlider.direction = 1;
            this.prepareForManualNavigationWhilePlaying();
            galleryViewMaster.previous();
        },
		motionPictureDidStart:  function(evt) {
			var data = evt.event_data.data;

			if (data === galleryViewMaster.slideshow) {
				this.isGalleryViewMasterSlideshowPaused = true;
				if (this.isMotionPicturePlaying) {
					this.shouldStartGalleryViewMasterSlideshow = true;
					galleryViewMaster.slideshow.stop();
				}
			} else {
				this.isMotionPicturePlaying = true;
				this.motionPicturePlaying = data;
				if (this.isGalleryViewMasterSlideshowPaused) {
					this.shouldStartGalleryViewMasterSlideshow = true;
					galleryViewMaster.slideshow.stop();
				}
			}

		},

		motionPictureDidEnd: function(evt) {
			var data = evt.event_data.data;

			if (data === galleryViewMaster.slideshow) {
				 if(galleryViewMaster.getNextSection() == galleryViewMaster.getFirstSection()) {
					this.isGalleryViewMasterSlideshowPaused = false;
					this._stopSlideShow();
					galleryViewMaster.reset();
				 }
			} else {
				if (this.motionPicturePlaying === data) {
					this.isMotionPicturePlaying = false;
                    this.motionPicturePlaying = null;
					if (this.isGalleryViewMasterSlideshowPlaying && this.shouldStartGalleryViewMasterSlideshow) {
						this.shouldStartGalleryViewMasterSlideshow = false;
						if (evt.event_data.event_name === 'didFinishMovie') {
							galleryViewMaster.slideshow.setProgress(galleryViewMaster.slideshow.delay()*2/3);
						} else {
							galleryViewMaster.slideshow.setProgress(galleryViewMaster.slideshow.delay());
						}
						galleryViewMaster.slideshow.start();
					}
				}
			}

		}
	}; //pageController
	Object.extend(pageController, Event.Listener);
	window.pageController = pageController;

	pageController.listenForEvent(AC.ViewMaster, 'ViewMasterDidShowNotification', false, function(evt) {
		var data = evt.event_data.data,
		indexOfIncomingView;
		if (galleryViewMaster === data.sender) {
			indexOfIncomingView = data.sender.indexOfSection(data.incomingView);
			aSlider.scrolltoPageNumber(Math.floor((indexOfIncomingView/7)+1), aSlider.direction);
			if (aSlider.direction === 1) aSlider.direction = -1;
		}
	});

	pageController.listenForEvent(document.event, 'didStart', false, pageController.motionPictureDidStart.bind(pageController));
	pageController.listenForEvent(document.event, 'didEnd', false, pageController.motionPictureDidEnd.bind(pageController));
	pageController.listenForEvent(document.event, 'didFinishMovie', false, pageController.motionPictureDidEnd.bind(pageController));
    pageController.slideShowTrigger = $('play_slideshow');
    pageController.slideShowProgressionNav = $('progression_nav');
    
    if(pageController.slideShowTrigger) {
        Event.observe(pageController.slideShowTrigger, 'click', pageController.startStopSlideShow.bindAsEventListener(pageController));
    }
    if($('slideshow-previous')) {
        Event.observe($('slideshow-previous'), 'click', pageController.slideShowPreviousAction.bindAsEventListener(pageController));
    }
    if($('slideshow-next')) {
        Event.observe($('slideshow-next'), 'click', pageController.slideShowNextAction.bindAsEventListener(pageController));
    }
    
    Event.observe($('slider'), 'click', pageController.sliderClicked.bindAsEventListener(pageController));

	var hashId = window.location.hash.split('#')[1];

	var triggerLinks = document.getElementsByClassName('overlaythumb'),
		trigger;
	for (i = 0, trigger; (trigger = triggerLinks[i]); i++) {
		if (trigger.getAttribute('href').match(new RegExp("#" +hashId+ "(?![\_\w\-])"))) {
			window.setTimeout(function() { trigger.fire('overlay:clicked'); }, 300);
			return;
		}
	}


});
