var lightwindow, refreshData;

var Site = {
    init: function() {        
    	lightwindow = new Iwindow({ overlay: 'myOverlay', wrap: 'frameWrap', iframe: 'myFrame' });
    	
    	Site.TextSize.init({ selector: '#textSize a', cookieName: 'citextsize', targeted: 'mainContent' });
        Site.Facts.init();
        Site.toggles();
        Site.exits();
        Site.backTo();
        Site.recipes.init();
        Site.buildTips();
		Site.transcripts();
    },

    Facts: {
        init: function() {
        	Site.FastFacts = new FastFacts("prevFact", "nextFact", "fastFactHeadline", "fastFactNum", "factContent", window.root + "js/fastFacts.js");
            refreshData = function(facts, sets, map) {            	
            	Site.FastFacts.dataReady(facts, sets, map);
            }

        }
    },

    toggles: function() {
        var sendToggle = $('sendFriend') || false
        if (sendToggle) {
            sendToggle = sendToggle.getElement('a')
		    .setProperties({ 'href': 'javascript:void(0);', 'id': 'friendToggle' })
		    .addEvent("click", function() { lightwindow.open((window.root || "") + "layer/sendToFriend.aspx") });
        }

    },

    exits: function() {
        var exitLinks = $$('.exitlink');
        var exp = /dest=(\S*)/

        if (exitLinks.length > 0) {
            exitLinks.each(function(el, i) {
                var _href = el.get('href')
                var _tmpUrl = _href.match(exp)[1]

                el.set("href", "javascript:void(0);")
                if (!el.hasClass('branded')) el.addEvent("click", function() { lightwindow.open((window.root || "") + "layer/exitSite.aspx?dest=" + _tmpUrl) });
                else if (el.hasClass('branded')) el.addEvent("click", function() { lightwindow.open((window.root || "") + "layer/interstitial.aspx?dest=" + _tmpUrl) });
            });
        }

    },

    backTo: function() {
        var scrollFx;

        var backTos = $$(".returnTop a");
        backTos.each(function(el, i) {
            el.addEvent("click", function(e) {
                e.stop();
                if (scrollFx) scrollFx.toTop();
                else scrollFx = new Fx.Scroll($(document.body)).toTop();
            })
        })
    },
	
	transcripts: function() {
		var togs = $$(".transcriptToggle a");
		var togd = $$(".transcriptCopy")
		
		if (togs.length == 0) return;
		
		togs.each(function(el, i) {
			el.addEvent("click", function() {
				var display = togd[i].getStyle("display");
				var span = this.getElement("span");
				if (span) span.set("html", (display == "none") ? "[Click to collapse]" : "[Click to expand]");
				togd[i].setStyle("display", (display == "none") ? "block" : "none");
			});
		})
		
	},
	
    buildTips: function() {
			//store titles and text
			$$('a.myTip').each(function(element,index) {
				var content = element.get('title').split('::');
				element.store('tip:title', '<span>'+content[0]+'</span>');
				element.store('tip:text', '<p>' + content[1] + '</p>');
			});
			
			//create the tooltips
			var tipz = new Tips('.myTip',{
				className: 'tipWrap',
				fixed: false,
				hideDelay: 100,
				showDelay: 100,
				offsets: {'x': 16, 'y': 16}
			});
			
			var superTips = $$('#superColon a.superColonTip')
			if (superTips.length > 0) {
				superTips.each(function(element,index) {
					var content = element.get('title')
					var exp = /Prevent Cancer Foundation Super Colon/
					var newstr = content.replace(exp, '<span class="supColon">Prevent Cancer Foundation Super Colon&trade;</span>')
					
					element.store('tip:title', '');
					element.store('tip:text', '<p>' + newstr + '</p>');
				});
			
				
				var superTip = new Tips('.superColonTip',{
					className: 'tipWrap',
					fixed: false,
					hideDelay: 100,
					showDelay: 100,
					offsets: {'x': 16, 'y': 16}
				});				
				
			}
							
		},
    recipes: {
        curr: null,
        firstTime: true,
        init: function() {
            this.parents = $$('.recipeToggle');
            this.togs = $$('.expandBtn');
            this.contents = $$('.recipeToggled');

            if (this.parents.length == 0) return;

            this.scroller = new Fx.Scroll($(document.body));

            this.contents.each(function(el, i) {
                el.setStyle('display', 'none')
            });

            this.togs.each(function(tog, i) {
                tog.setStyle('display', 'block')
            }, this);

            this.parents.each(function(par, i) {
                par.removeClass('active')
                par.addEvent('click', function() {
                    this.toggleItem(i)
                } .bind(this));

            }, this)

            if (this.togs.length > 0) this.toggleItem(0)

        },
        toggleItem: function(i) {
            if ($chk(this.curr)) {
                this.togs[this.curr].set('html', 'Click to expand')
                this.parents[this.curr].removeClass('recipeOpen')
                this.contents[this.curr].setStyle('display', 'none')
            }

            if (this.curr != i) {
                this.togs[i].set('html', 'Click to close')
                this.parents[i].addClass('recipeOpen')
                this.contents[i].setStyle('display', '')

                if (!this.firstTime) {
                    if ($(window).getScroll().y > this.parents[i].getPosition($(document.body)).y) {
                        var gotoElement = function() {
                            this.scroller.toElement(this.parents[i]);
                        } .delay(500, this);
                    }
                }

            }

            this.firstTime = false;
            this.curr = (this.curr == i) ? null : i
        }
    },

    TextSize: {
        cName: null,
        opts: { duration: 60, path: "/", domain: "intouch-dev.com"},
        scale: ['1.0em', '1.2em', '1.3em', '1.4em'],
        myScale: null,
        els: null,
        curr: 0,
        init: function(obj) {
            this.els = $$(obj.selector)

            if (this.els.length == 0) return
			
					
            this.cName = obj.cookieName
            if (!$chk(Cookie.read(this.cName))) Cookie.write(this.cName, 0, this.opts) //if doesnt exist, set cookie to 0					
            this.myScale = parseInt(Cookie.read(this.cName)) || 0 //in case cookies are disabled use 0								

            this.els.each(function(el, i) {
                el.set('href', 'javascript:void(0);')
                el.addEvent('click', function() {
                    this.processScale(el, i)
                } .bind(this))
            }, this)
            this.targetEl = $(obj.targeted) || $(document.body)
            this.targetEl.setStyles({ 'font-size': this.scale[this.myScale] })
        },
        setCookie: function() {
            Cookie.write(this.cName, this.myScale.toString(), this.opts)
        },
        processScale: function(el, index) {
            switch (index) {
                case 0:
                    this.myScale = (this.myScale + 1 > this.scale.length - 1) ? this.scale.length - 1 : this.myScale + 1
                    break;
                case 1:
                    this.myScale = (this.myScale - 1 < 0) ? 0 : this.myScale - 1
                    break;
            }
            this.setCookie();
            this.targetEl.setStyle('font-size', this.scale[this.myScale]);
        }
    },
	
	SiteMap: {
		options: {
			inputId: "siteMapState",
			toggleSelector: "#siteMap .ribbon",
			toggledSelector: "#siteMap .typePages"
		},
		
		map: {
			"breast": 	0,
			"colon": 	1,
			"gastric": 	2,
			"headneck": 3,
			"lung": 	4,
			"prostate": 5,
			"other": 	6
		},
		
		init: function() {
			this.section = $(this.options.inputId);
			if (!this.section) return;
			
			this.togs = $$(this.options.toggleSelector);
			this.togd = $$(this.options.toggledSelector);
			
			var where = this.section.get("value").toLowerCase();
			where = ($chk(this.map[where])) ? this.map[where] : null;
			
			this.togs.each(function(el, i) {				
				if ($chk(where)) {
					if (i == where) el.addClass("active");
				}
				else el.addClass("active");
				
				var span = el.getElement("span");
				span.addEvent("click", function(e) {
					this.toggle(i);
				}.bind(this))
				
			}, this);
			
			this.togd.each(function(el, i) {
				if ($chk(where)) {
					if (i == where) el.show();
					else el.hide();
				}
				else el.show();
			});			
			
			this.curr = where;
		},
		
		toggle: function(index) {
			var display = (this.togd[index].getStyle("display") == "none") ? false : true;
			this.togs[index][(display) ? "removeClass" : "addClass"]("active");
			this.togd[index][(display) ? "hide" : "show"]();
		}
	}
};

var FastFacts = new Class({
	Implements: [Options, Events],
	
	options: {},
	
	facts: null,
	
	queued: $empty,
	
	initialize: function(prevId, nextId, headlineId, currId, contentId, data, opts) {
		if (opts) this.setOptions(opts);
		
		this.dataSrc = data;
		
		this.prevBtn = ($(prevId) || new Element("div")).addEvent("click", this.getPrev.bind(this));
		this.nextBtn = ($(nextId) || new Element("div")).addEvent("click", this.getNext.bind(this));	
				
		this.curr = ($(currId)) ? $(currId).get("html") : "1";
		this.factHeadline = $(headlineId) || new Element("h5");
		this.factHeadlineImg = this.factHeadline.getElement("img") || new Element("img");
		this.factContent = $(contentId) || new Element("div");
	},
	
	dataReady: function(facts, sets, map) {
		
		var g 		= map[this.curr.toInt()];
		var s	 	= sets[g.set];
		this.curr 	= g.start;
		
		this.facts = new Array();
		for (var i=0; i < s.length; i++) {
		 	this.facts.push(facts[s[i]]);
		 }; 
		
		this.factLength = this.facts.length;
		
		this.queued.call(this);	
	},
	
	getData: function() {		
		var asset = new Element("script", {
			"type": "text/javascript",
			"src": this.dataSrc + '?noCache=' + new Date()
		});
		(function() {
			asset.inject(document.body);
		}).delay(500, this)		
		

	},
	
	getPrev: function() {
		if (!this.facts) {
			this.queued = this.getPrev;
			this.getData();			
		}			
		else {
			var prev = (this.curr - 1 < 0) ? this.facts.length - 1 : this.curr - 1;
			
			this.loadContent(prev);			
		}

	},

	getNext: function() {
		if (!this.facts) {
			this.queued = this.getNext;
			this.getData();			
		}
		else {
			var next = (this.curr + 1 > this.facts.length - 1) ? 0 : this.curr + 1;
			
			this.loadContent(next);			
		}			
	},
	
	loadContent: function(index) {		
		this.factHeadline.set("class", "fact_" + (index + 1));
		this.factHeadlineImg.set("alt", "Fast Fact #" + (index + 1));
					
		this.factContent.set("html", this.facts[index]);
		this.curr = index;		
	}
});


var Iwindow = new Class({
	overlay: null,
	frameWrap: null,
	myFrame: null,
	myFx: null,
	myUrl: null,
	_tWin: null,
	
	initialize: function(obj) {
		// set static dimensions for HTTPS pages
		this.fixed = {
			sendtofriend_popup: 300
		};		
		this.build(obj);	
	},
	build: function(obj) {
		[
			this.overlay = new Element('div',{id: obj.overlay}), 
			this.frameWrap = new Element('div',{id: obj.wrap}),
			this.loader = new Element('div', {id: 'frameLoader', html: '<p>Loading</p>'})
		].each(function(el) {
			el.hide().inject(document.body, 'bottom')			
		});
		
		this.overlay.addEvent('click',function() { this.closeWin()}.bind(this));
		/*
		this.myFrame = new Element("iframe", {
			"id": "myFrame",
			"class": "myFrameClass",
			scrolling: "no",
			frameborder: 0,
			src: window.root + "blank.htm"
		}).hide().inject(this.frameWrap).addEvent('load', function() {this.frameLoaded()}.bind(this));
		*/
		this.closeBtn = new Element("div", {"class":"frameCloseWrap"});
		
		this.closeBtn.adopt(new Element("iframe", {
			"class": "closeFrame",
			scrolling: "no",
			frameborder: 0,
			src: window.root + "blank.htm"
		})).adopt(new Element("div", {"class":"frameBtn"}));		
		

		this.closeBtn.addEvent("click", function() {
			this.closeWin();			
		}.bind(this))
		
		this.frameWrap.adopt(this.closeBtn);
		

		this._tWin 	= $(document.body);
		
		this.myFx = {
			overlay: new Fx.Tween(this.overlay, {property:"opacity",duration:300, onComplete: function() {this._setDisplay}.bind(this)}).set(0),
			frameWrap: new Fx.Tween(this.frameWrap, {property:"opacity",duration:500})/*.set(0)*/,			
			win: new Fx.Scroll(this._tWin, {duration: 500})
		};	
	
		this.targeted = ($(document.body) || new Element("div")).getSize().x
								
	},
	open: function(url, mode) {		
		this.frameUrl = url;
		this.mode = (mode) ? mode : null;			
		
		this._resizeOverlay()
		this.overlay.show()
		this.myFx.overlay.start(0.5).chain(function() {
			this.loader.show()
			this.setFrame(url)
		}.bind(this))
						
		try {pauseVideo()} catch(e) {}
		//hideDDown();																		
		
		window.addEvent("scroll",this._resizeOverlay.bind(this)).addEvent("resize", this._resizeOverlay.bind(this));						
	},
	closeWin: function() {
		this.loader.hide()
		this.myFx.frame.start(1).chain(function() {
			this.myFrame.hide().destroy();
			this.frameWrap.hide()
			//this.myFrame.set('src','javascript:void(0)')
		}.bind(this))
		this.myFx.overlay.start(0);
		try { resumeVideo() } catch(e) {}
		//showDDown();
		window.removeEvents("scroll").removeEvents("resize");		
	},
	setHeight: function(y) {			
		if (y && this.myFrame.getStyle('visibility') != 'hidden') {
			this.myFrame.setStyle('height', y);
		}
		else {
		    try { this.myFrame.contentWindow.scaleWindow() } catch(e) {}
		}
	},
	scale: function(y) {		
		if (this.myFrame.isDisplayed() && this.mode) this.myFx.win.toTop();
		this.myFx.frame.start(y);
	},
	setFrame: function(url) {					
		this.myFrame = new Element("iframe", {
			"id": "myFrame",
			"class": "myFrameClass",
			scrolling: "no",
			frameborder: 0,
			src: url,
			events: {
				"load": function() {this.frameLoaded()}.bind(this)
			}
		}).hide();
		this.myFx.frame = new Fx.Tween(this.myFrame, {property:"height",duration:500});
		this.myFrame.inject(this.frameWrap);
	},
	frameLoaded: function() {		
		if (this.myFrame.get('src').test("blank.htm")) return;
		this.loader.hide();
		this.frameWrap.show()
		this.myFrame.show();
		try {this.myFrame.contentWindow.scaleWindow()} 
		catch(e) {
			var page = this.frameUrl.split("/").getLast().split(".")[0].toLowerCase();			
			if (this.fixed[page]) this.scale(this.fixed[page]);
		}	
	},
	_resizeOverlay: function() {
		wrapStyles = {left:(this.targeted / 2) - (this.frameWrap.getStyle('width').toInt() / 2)}
		loaderStyles = {left: (this.targeted / 2) - (this.loader.getStyle('width').toInt() / 2)}
		
		wrapStyles.top = loaderStyles.top = (this.mode) ? 25 : window.getScrollTop() + 25
		
		try{
			this.overlay.setStyles({top:window.getTop(), height:window.getScrollHeight()});
			this.loader.setStyles(loaderStyles)
		    this.frameWrap.setStyles(wrapStyles);		
		} catch (e) {}
	},	
	_setDisplay: function() {
		if (this.overlay.getStyle('visibility') == 'hidden') {
			$$([this.overlay, this.frameWrap]).setStyle('display','none')
		}
	}	
});

// movie functions
function thisMovie(movieName) {
	 if (navigator.appName.indexOf("Microsoft") != -1) {
		 return window[movieName];
	 } else {
		 return document[movieName];
	 }
}
function playVideo()
{
    thisMovie("videoSection").playVideo();
}
function pauseVideo()
{
    thisMovie("videoSection").pauseVideo();
}
function stopVideo()
{
    thisMovie("videoSection").stopVideo();
}
function seekVideo(offset)
{
    thisMovie("videoSection").seekVideo(offset);
}
function setVideoVolume(level)
{
    thisMovie("videoSection").setVideoVolume(level);
}
function fullScreenVideo(state)
{
    thisMovie("videoSection").fullScreenVideo(state);
}
function loadVideoById(id)
{
    thisMovie("videoSection").loadVideoById(id);
}
function resumeVideo()
{
    thisMovie("videoSection").resumeVideo();
}

var MooShow = new Class({
    Implements: [Options, Events],

    options: {
        wrapSelector: '.slidesIn',
        slideSelector: '.slide',

        navSelector: 'a',

        mode: 'fade', // options: fade OR scroll

        duration: 500,

        startRandom: false,
        autoRotate: true,
        rotateDuration: 5000,
        welcomeFrame: false
    },

    startIndex: 0,
    slideScale: null,
    curr: null,
    slideInterval: null,

    firstTime: true,

    initialize: function(scrollId, navId, opts) {
		if (opts) this.setOptions(opts);
		
		this.scroller 	= $(scrollId)
		this.controller = $(navId)
		
		// IDs dont exist, try again
		if (!this.scroller || !this.controller) return	
		this.scrollWrap = this.scroller.getElement(this.options.wrapSelector) || new Element("div");
		
		this.scrollSlides 	= this.scroller.getElements(this.options.slideSelector);			
							
		// change mode to default if they pass invalid mode
		if (!$A(['fade', 'scroll']).contains(this.options.mode.toLowerCase())) this.options.mode = 'fade';

		this.slideScale = {x: this.scrollSlides[0].getStyle('height').toInt(), y: this.scrollSlides[0].getStyle('width').toInt()};			
		
		// if scroll..
		if (this.options.mode == 'scroll') {
			this.scrollWrap.setStyle('width', (this.slideScale.y * this.scrollSlides.length).toInt() + 'px')			
			this.scrollFx = new Fx.Tween(this.scrollWrap, {property: 'left', duration: this.options.duration}).set((this.startIndex == 0) ? 0 : -(this.slideScale.y * this.startIndex))
		};
		
		// if fade..
		if (this.options.mode == 'fade') {
			this.scrollSlides.each(function(slide, i) {
				slide.setStyles({
					position: 'absolute',
					zIndex: this.scrollSlides.length - i
				})
				slide.set('tween', {property: 'opacity', duration: this.options.duration, link: 'cancel'}).set('opacity', (this.startIndex == i) ? 1 : 0)
			}, this)
									
		};
		
		// inital frame isn't related to show, so exclude it
		if (this.options.welcomeFrame) {
			this.startingSlide = this.scrollSlides[0];
			this.scrollSlides.splice(0,1)				
		};	
		
		this.navs = this.controller.getElements(this.options.navSelector);		
		if ($chk(this.startIndex)) {
			this.navs[this.startIndex].addClass('active')
			this.curr = this.startIndex
		};
		
		this.setNavBinds(true);
		
		// if its automated
		if (this.options.autoRotate) {
			$clear(this.slideInterval);
			
			var enterFunc = function() {
				$clear(this.slideInterval)			
			}.bind(this);
			
			var leaveFunc = function() {
				$clear(this.slideInterval)
				this.slideInterval = this.runShow.periodical(this.options.rotateDuration, this)				
			}.bind(this);
			
			this.slideInterval = this.runShow.periodical(this.options.rotateDuration, this);
			
			this.scroller.addEvent('mouseenter', enterFunc);
			this.scroller.addEvent('mouseleave', leaveFunc);
			this.controller.addEvent('mouseenter', enterFunc);
			this.controller.addEvent('mouseleave', leaveFunc);		
			
		};
    },

    runShow: function() {
        this.nextSlide();
    },

    nextSlide: function() {
        var next = (!$chk(this.curr)) ? 0 : (this.curr + 1 > this.scrollSlides.length - 1) ? 0 : this.curr + 1
        this.gotoSlide(next)
    },

    prevSlide: function() {
        var prev = (this.curr - 1 < 0) ? this.scrollSlides.length - 1 : this.curr - 1
        this.gotoSlide(prev)
    },

    gotoSlide: function(index) {
        var mode = this.options.mode

        if (this.options.welcomeFrame && this.firstTime) {
            this.startingSlide.tween(0)
        }

        if (mode == 'scroll') {
            this.scrollFx.start((index == 0) ? 0 : -(this.slideScale.y * index))
        }

        else if (mode == 'fade') {
            if ($chk(this.curr)) this.scrollSlides[this.curr].tween(0)
            this.scrollSlides[index].tween(1)
        }

        if (this.navs.length >= 2) {
            if ($chk(this.curr)) this.navs[this.curr].removeClass('active')
            this.navs[index].addClass('active')
        }

        this.curr = index
        this.firstTime = false

    },

    setNavBinds: function(state) {
        var fn = (state) ? 'addEvent' : 'removeEvent'

        // if nav items more than 2, assume clickable nav
        if (this.navs.length >= 2) {
            this.navs.each(function(el, i) {
                el[fn]('click', function() {
                    this.gotoSlide(i);
                } .bind(this))
            }, this)
        }
        else {
            //this.navs[0][fn]('click', this.prevSlide.bind(this))
            //this.navs[1][fn]('click', this.nextSlide.bind(this))
        }

    }

});

var SlideShow = new Class({
	Implements: [Events, Options],
	
	options: {
		slideSelector: ".slide",
		
		mediaParentSelector: ".slideMedia",
		mediaSelector: ".media",
		mediaRotateDelay: 3000,
		
		navSelector: ".nav a",		
		navActiveClass: "active",
		setNavActiveOnParent: true,
		navEventType: "click"
	},
	
	curr: null,
	slideOutBound: $empty,
	slideInBound: $empty,
	
	initialize: function(slideParentId, navParentId, opts) {
		this.setOptions(opts || {});
		this.slideParent 	= $(slideParentId) || new Element("div");
		this.navParent 		= $(navParentId) || new Element("div");
		
		this.medias 	= [];
		
		this.slideParent.setStyle("height", this.slideParent.offsetHeight);
		
		this.prepSlides();
		this.prepNav();
		
		//this.curr = 0;
		this.show(0);
	
	},
	
	prepSlides: function() {
		if (this.slides) return this.slides;
		
		this.slides 	= this.slideParent.getElements(this.options.slideSelector);		
		this.slides.each(function(slide, i) {			
			var media = slide.getElements(".media"), mediawrap;
			if (media.length > 1) {
				mediawrap = slide.getElement(this.options.mediaParentSelector) || new Element("div");
				mediawrap.setStyle("position", "relative");
				
				media.each(function(img, j) {
					media[j] = new Fx.Tween(media[j], {property: "opacity", link: "cancel"});
					if (j != 0) media[j].set(0);
					
					img.setStyles({
						position: "absolute",
						left: 0,
						top: 0,
						zIndex: media.length - j
					});					
				}, this);
				
			};
			this.medias.push(media);			
			
			if (this.slides.length > 1) {
				this.slides[i] = new Fx.Tween(this.slides[i], {
					property: "opacity",
					link: "cancel"
				});
				if (i != 0) this.slides[i].set(0);
				slide.setStyles({
					position: "absolute",
					left: 0,
					top: 0,
					zIndex: this.slides.length - i
				});								
			};
			
		}, this);

		return this;
	},
	
	prepNav: function() {
		if (this.navs) return this.navs;
		
		this.navs = this.navParent.getElements(this.options.navSelector);
		this.navs.each(function(nav, i) {
			if (nav.get("tag") == "a") nav.set("href", "javascript:void(0);");
			nav.addEvent(this.options.navEventType, function() {
				this.show(i);
			}.bind(this))
		}, this);
		
		return this;
	},
	
	show: function(index) {
		//if (index == this.curr) return;				
		var currParent = null;
		var showParent = (this.options.setNavActiveOnParent) ? this.navs[index].getParent() : this.navs[index];
		
		if ($chk(this.curr)) {
			//((this.options.setNavActiveOnParent) ? this.navs[this.curr].getParent() : this.navs[this.curr]).removeClass(this.options.navActiveClass);
			currParent = (this.options.setNavActiveOnParent) ? this.navs[this.curr].getParent() : this.navs[this.curr];
			currParent.removeClass(this.options.navActiveClass);			
			currParent.set("opacity", 1);
			
			this.slideOutBound = this.slideOut.bind(this, [this.curr]);
			
			this.slides[this.curr].removeEvents("complete").addEvent("complete", this.slideOutBound);
			
			this.slides[this.curr].start(0);
		};
		
		//((this.options.setNavActiveOnParent) ? this.navs[index].getParent() : this.navs[index]).addClass(this.options.navActiveClass);
		showParent.addClass(this.options.navActiveClass);		
		showParent.set("opacity", 0.5);
		
		this.slideInBound = this.slideIn.bind(this, [index]);
		this.slides[index].removeEvents("complete").addEvent("complete", this.slideInBound);
		this.slides[index].start(1);
		
		this.curr = index;
	},
	
	slideOut: function(index) {		
		if (this.medias[index].length > 1) {
			this.medias[index].each(function(media, i) {
				if (i == 0) media.set(1);
				else media.set(0);
			});
		};
		this.fireEvent("slideOut", [this.slides[index]]);
		
	},
	
	slideIn: function(index) {
		$clear(this.mediaInterval);
		
		if (this.medias[index].length > 1) {
			var slide = this.slides[index].element;
			slide.store("currMedia", "0");
			this.mediaInterval = this.rotateMedia.periodical(this.options.mediaRotateDelay, this, [index, slide]);		
		};
		
		this.fireEvent("slideIn", [this.slides[index]]);
	},
	
	rotateMedia: function(index, slide) {		
		var curr = slide.retrieve("currMedia").toInt();
		this.medias[index][curr].start(0);
		
		var next = (curr + 1 > this.medias[index].length - 1) ? 0 : curr + 1;
		slide.store("currMedia", next);
		this.medias[index][next].start(1);				
	},
	
	toElement: function() {
		if ($chk(this.curr)) return this.slides[this.curr];
		else return false;
	},
		
	detach: function() {
	}
	
});


var VideoControl = new Class({
	Implements: [Events, Options],
	
	options: {
		navId: "videoNav",
		
		categorySelector: ".videoCategory",
		pageSelector: ".videoPage",
		thumbSelector: ".thumb a",
		
		wrapperSelector: ".boxedIn",
		
		subNavSelect: ".videoSubNav",
		
		prevTabActiveClass: "videoTab leftTab",
		prevTabInactiveClass: "videoTab leftTabInactive",
		nextTabActiveClass: "videoTab rightTab",
		nextTabInactiveClass: "videoTab rightTabInactive",

		paginatorClass: "paginator",
		paginatorLinkType: "a",
				
		manyClass: "manyVideos",
		
		autoDetectPage: true
	},
	
	curr: [null, null],
	
	initialize: function(opts) {
		this.setOptions(opts || {});
		
		this.base = $(this.options.navId) || new Element("div");
		this.wrap = this.base.getElement(this.options.wrapperSelector);
				
		var loc = [0,0];
		var pagename = window.location.href.split("/").getLast().toLowerCase();		
		
		this.categories = this.base.getElements(this.options.categorySelector);
		this.categories.each(function(el, i) {
			this.categories[i] = new VideoCategory(el);
			this.categories[i].hide();
			if (this.options.autoDetectPage) {
				var has = this.categories[i].hasLinkTo(pagename);
				if ($chk(has)) loc = [i, has];				
			}
		}, this);
		
		this.subnav = this.base.getElement(this.options.subNavSelect);
		
		this.build();
		this.goTo.apply(this, loc);
	},
	
	build: function() {
		this.nextTab = new Element("div");
		this.prevTab = new Element("div");		

		// there's only 1 category with 1 page
		if (this.categories.length == 1 && this.categories[0].length == 1) {
			["next", "prev"].each(function(dir, i) {
				this[dir + "Tab"].set("class", this.options[dir + "TabInactiveClass"]);
			}, this);							
		}
		// there's possibly several categories, and thus possibly several pages
		else {
			var pager = new Element("div", {"class": this.options.paginatorClass}).inject(this.wrap);
			this.paginator = new VideoPaginator(pager);
			
			this.paginator.addEvent("select", function(index) {					
				this.showPage(index);
			}.bind(this));
			
			this.categories.each(function(cat, i) {
				cat.addEvent("show", function(len) {						
					this.paginator.populate(len);
				}.bind(this));
				cat.addEvent("showPage", function(index) {
					this.paginator.select(index);
				}.bind(this));
			}, this);
			
			["next", "prev"].each(function(dir, i) {
				this[dir + "Tab"].set("class", this.options[dir + "TabActiveClass"]);
				this[dir + "Tab"].addEvent("click", function() {
					this[dir + "Page"]();
				}.bind(this));
			}, this);
			
			if (this.subnav && this.categories.length > 1) {
				this.wrap.addClass(this.options.manyClass);
				this.subs = this.subnav.getElements("li a");
				this.subs.each(function(el, i) {
					el.addEvent("click", function() {
						this.goTo(i);
					}.bind(this));
				}, this);
				this.subnav.show();
			}			

		}
		
		this.nextTab.inject(this.wrap);
		this.prevTab.inject(this.wrap);		
		
		return this;
	},
	
	nextPage: function() {		
		this.categories[this.curr[0]].nextPage();
	},
	
	prevPage: function() {		
		this.categories[this.curr[0]].prevPage();
	},
	
	showPage: function(page) {
		var p = this.categories[this.curr[0]].showPage(page);
		
		this.curr[1] = (!p) ? this.curr[1] : page;
	},
	
	showCategory: function(cat) {
		if (this.curr[0] == cat) return;
		
		if ($chk(this.curr[0])) {
			this.categories[this.curr[0]].hide().reset();
		};
		this.categories[cat].show();
		if (this.categories[cat].length == 1) $$(this.nextTab, this.prevTab).hide();
		else $$(this.nextTab, this.prevTab).show();
		
		this.curr[0] = cat;			
	},
	
	selectSub: function(index) {
		if (!this.subnav) return;
		
		var curr = this.subnav.retrieve("currSub");
		if ($chk(curr)) this.subs[curr.toInt()].removeClass("active");
		
		this.subs[index].addClass("active");
		this.subnav.store("currSub", index);
		return this;
	},
	
	goTo: function(cat, page) {
		if (cat == this.curr[0]) return;
		
		page = ($chk(page)) ? page : 0;
		
		this.showCategory(cat);
		this.categories[this.curr[0]].showPage(page);
		//this.showPage(page);
		
		this.selectSub(cat);
		
		return this;
	}
	
});
var VideoPaginator = new Class({
	Implements: [Events, Options],
	options: {},	
	curr: null,
	
	initialize: function(element, opts) {
		this.setOptions(opts);
		this.element = $(element) || new Element("div");
		this.pages = [];
	},
	
	toElement: function() {
		return this.element;
	},
	
	populate: function(num) {		
		this.element.empty();
		this.element.hide();
		this.curr = null;
		this.pages = [];
		for (var i = 0; i < num; i++) {
			var bound = function(j) {				
				this.fireEvent("select", [j]);
				this.select(j);
			}.bind(this, i);
			
			var p = new Element("a", {
				events: {
					click: bound
				},
				href: "javascript:void(0);",
				html: i + 1 + ""
			});
			
			this.pages.push(p);
			this.element.adopt(p);
		};
		
		if (num != 1) this.element.show();
	},
	
	select: function(index) {		
		if (this.curr == index) return;		
		
		if ($chk(this.curr)) {
			this.pages[this.curr].removeClass("active");
		};		
		
		this.pages[index].addClass("active");
		
		this.curr = index;		
	}
	
});

var VideoCategory = new Class({
	Implements: [Events, Options],
	options: {
		pageSelector: ".videoPage",
		thumbSelector: ".thumb a"
	},
	curr: null,
	isVisible: false,
	
	initialize: function(element, opts) {
		this.setOptions(opts);
		
		this.element = $(element) || new Element("div");
		this.pages = this.element.getElements(this.options.pageSelector);
		this.pages.hide();
		this["length"] = this.pages.length;
	},
	
	toElement: function() {
		return this.element;
	},
	
	show: function() {
		this.element.show();
		this.isVisible = true;
		
		this.fireEvent("show", [this.pages.length]);
		
		return this;
	},
	
	hide: function() {
		this.element.hide();
		this.isVisible = false;
		return this;
	},
	
	reset: function() {
		this.pages.each(function(el, i) {
			el[(i == 0) ? "show" : "hide"]();
		});
	},
	
	showPage: function(index) {
		//if (this.curr == index) return false;
		
		if ($chk(this.curr) && this.curr != index) {
			this.pages[this.curr].hide();
		};
		
		this.pages[index].show();
		this.fireEvent("showPage", [index]);
		
		this.curr = index;
		return this;
	},
	
	hasLinkTo: function(pagename) {
		var has = false, which;		
		this.pages.each(function(page, i) {
			var thumbs = page.getElements(this.options.thumbSelector);
			thumbs.each(function(thumb) {
				var thumbpagename = thumb.get("href").split("/").getLast().toLowerCase();
				if (thumbpagename == pagename) {
					has = true;
					which = i;
				};
			});
		}, this);
		
		return (!has) ? false : which;		
	},
	
	nextPage: function() {
		var next = (this.curr + 1 > this.pages.length - 1) ? 0 : this.curr + 1;
		this.showPage(next);
	},
	
	prevPage: function() {
		var prev = (this.curr - 1 < 0) ? this.pages.length - 1 : this.curr - 1;
		this.showPage(prev);	
	}
	
})

window.addEvent("domready", function() {
	Site.init();
})



