var lightwindow, refreshData;

var Site = {
    init: function() {        
    	lightwindow = new Iwindow({ overlay: 'myOverlay', wrap: 'frameWrap', iframe: 'myFrame' });
    	
    	Site.TextSize.init({ selector: '#textSize a', cookieName: 'textsize', targeted: 'mainContent' });
        Site.Facts.init();
        Site.toggles();
        Site.exits();
        Site.backTo();
        Site.recipes.init();
    },

    Facts: {
        init: function() {
        	Site.FastFacts = new FastFacts("prevFact", "nextFact", "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();
            })
        })
    },

    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 },
        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, 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]);
        }
    }
};

var FastFacts = new Class({
	Implements: [Options, Events],
	
	options: {},
	
	facts: null,
	
	queued: $empty,
	
	initialize: function(prevId, nextId, 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.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.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)*/,
			frame: new Fx.Tween(this.myFrame, {property:"height",duration:500}),
			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()
			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(a) {			
		this.myFrame.set('src', a);
	},
	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: true,
        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)
		
		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))
        }

    }

});


window.addEvent("domready", function() {
	Site.init();
})


