/* <resourceSettings>
    <resourceLocation name="Javascript" type="Chipotle.ResourceProvider.Resources.Javascript, Chipotle.ResourceProvider" />
</resourceSettings> */

// Create an isIE6 && isIE7 identifier in the Mootools Browser class
if((Browser.Engine.name=='trident' && Browser.Engine.version==4)) window.Browser.IE6 = true; else window.Browser.IE6 = false;
if((Browser.Engine.name=='trident' && Browser.Engine.version==5)) window.Browser.IE7 = true; else window.Browser.IE7 = false;

// Create the scroll effects on load
window.addEvent('domready', function() {
    // This Timeout is used to remove the immediate jumpiness often witnessed when the pages load
    // quickly and the pointer is still hovering over the nav
    setTimeout(function() { new PrimaryNavigation('chipotle_navigation', 'M_nav_primary_link', 'M_nav_secondary'); }, 500);

    // The sectionId is used to determine what page specific code needs to be executed
    var id = document.body.id.toString();
    switch (id) {
        case 'page-home':
            new MiniSlideshow('pork_slideshow', 'M_interactive_slide');
            ChipotlePresenter.Base.Init(true);
            new ChipotlePresenter($('pig_big_slideshow'), $('pig_big_slideshow_images'), function() { new MiniSlideshow('pig_big_slideshow_images', 'M_interactive_slide'); });
            if (window.Browser.IE6 == true) new IE6UTFShowHide('.M_gb_quiz_good,.M_gb_quiz_bad');
            new UnderTheFoil('switch');
            break;
        case 'page-fwi-animals':
            new DynamicTabs();
            new MiniSlideshow('pork_slideshow', 'M_interactive_slide');
            ChipotlePresenter.Base.Init(true);
            new ChipotlePresenter($('pig_big_slideshow'), $('pig_big_slideshow_images'), function() { new MiniSlideshow('pig_big_slideshow_images', 'M_interactive_slide'); });
            new ImageExpander('nat_raised_expanded');
            new ImageExpander('rbgh_expanded');
            break;
        case 'page-find':
            new FindSlideshowGet();
            new BtnHoverAttach('.M_input_button.M_btn_search input');
            break;
        case 'page-fanantics':
            new FananticsSlideshow();
            new TopFAQSlideshow();
            new FananticsQuiz();
            new UnderTheFoil('switch');
            new BtnHoverAttach('#quiz .M_submit_quiz img, #quiz_try_again');
            break;
        case 'page-fanantics-chipotle_fans':
            ChipotlePresenter.Base.Init();
            break;
        case 'page-fanantics-faq':
            new FAQAccordian('.Module.accordian_group');
            ChipotlePresenter.Base.Init();
            new ChipotlePresenter($('iaq_question'), $('iaq_answer'));
            break;
        case 'page-fanantics-talk_to_us':
            new TopFAQSlideshow();
            new BtnHoverAttach('.M_submit_cancel input');
            break;
        case 'page-fanantics-send_us_a_picture':
            new TopFAQSlideshow();
            break;
        case 'page-chipotle_story-whats_going_on':
            new FullSlideshow('slideshow-whats_going_on');
            break;
        case 'page-restaurants-the_chipotle_experience':
            new MiniSlideshow('design_slideshow', 'M_interactive_slide');
            break;
        case 'page-menu':
            new DynamicTabs();
            new MenuSlider();
            break;
        case 'page-menu-fresh_cooking':
            new DynamicTabs();
            break;
        case 'page-menu-ingredients':
            if (window.Browser.IE6 == true) new IE6UTFShowHide('.M_jal_bell_a,.M_jal_bell_b,.M_hab_chip_a,M_hab_chip_b');
            ChipotlePresenter.Base.Init(true);
            new ChipotlePresenter($('family_album'), $('family_album_images'), function() { new MiniSlideshow('family_album_images', 'M_interactive_slide'); });
            new UnderTheFoil('switch');
            new BtnHoverAttach('#chi_lib_submit, #chi_lib_try_again');
            break;
        case 'page-video':
            ChipotlePresenter.Base.Init(true);
            new ChipotlePresenter($('play-video'), $('video-div'));
            break;
        case 'page-search_results':
            new BtnHoverAttach('.search_results .M_submit_button input');
            break;
        case 'page-where-did-we-come-from':
            new UnderTheFoil('switch');
            break;
        case 'page-environment':
            new DynamicTabs();
            break;
        case 'page-search':
            new BtnHoverAttach('.M_submit input');
            break;
        case 'page-careers':
            new FAQAccordian('.Module.accordian_group');
            break;
        case 'page-account-gift-card':
            new FAQAccordian('.Module.accordian_group');
            break;
        case 'page-account-forgot-password':
            new BtnHoverAttach('.M_submit input');
            break;
        case 'page-fanantics-stories':
            new TopFAQSlideshow();
            break;
    }

    // Applies hover effect to tabs.. this gets around IE6's lack of hover anywhere
    new TabHover();
    new BtnHoverAttach('.M_search_form .M_submit input, .M_find_restaurant .M_submit input, .M_submit_cancel input, .M_giftcard_input input, .check_gift_card input');
});

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

// A global constructor that finds any tabs on the page and adds a hover state
var TabHover = new Class({
	initialize:function()
	{
		this.tabs = $$('.Module.tab_nav > ul > li');
		if(!this.tabs) return;
		
		this.tabs.each(function(el,index){
			el.addEvents({
				'mouseenter':this.Callbacks.enter.bind(this,index),
				'mouseleave':this.Callbacks.leave.bind(this,index)
			});
		},this);
	},
	Callbacks:{
		enter:function(index)
		{
			var el = this.tabs[index];
			if(el.hasClass('M_tabbed_current')) return;
			el.addClass('M_hovered');
		},
		leave:function(index)
		{
			this.tabs[index].removeClass('M_hovered');
		}
	}
});

// User for collecting a series of images or <input type="image" and adds a JS hover state automatically
var BtnHoverAttach = new Class({
	initialize:function(css)
	{
		
		var els = $$(css);
		els.each(function(el){ new BtnHover(el); });
	}
});

// Adds a hover state to an <img or <input type="image"
// Please note that you must have an identically named asset with _hover for the hover state to work properly
var BtnHover = new Class({
    initialize: function(el) {
        // Get the elements required
        this.el = $(el);
        this.def_string = el.getProperty('src');
        if (!this.el || !this.def_string) return; // The element doesn't exist... kill the constructor

        // Generate the string for the hover state
        var t_string = this.def_string.split('.gif');
        t_string.splice(t_string.length - 1, 0, '_hover');

        this.hov_string = '';
        t_string.each(function(str, index) { this.hov_string += str; }, this);
        this.hov_string += '.gif';

        // Preload the hover image
        this.image = new Image();
        this.image.src = this.hov_string;

        // Attach the events to trigger the hover
        this.el.addEvents({
            'mouseenter': this.Callbacks.enter.bind(this),
            'mouseleave': this.Callbacks.leave.bind(this)
        });
    },
    Callbacks: {
        enter: function() { this.el.setProperty('src', this.hov_string); },
        leave: function() { this.el.setProperty('src', this.def_string); }
    }
});

// This finds any slideshows on a page, and adds the slideshow functionality to them
var FindSlideshowGet = new Class({
	initialize:function()
	{
		var els = $$('.M_media.M_interactive');
		els.each(function(el){
			new MiniSlideshow(el,'M_interactive_slide');
		});
	}
});

// A major constructor used to create a lightbox effect
var ChipotlePresenter = new Class({
    options: {
        type: null
    },

    initialize: function(el, to_display, onShow) {
        this.el = $(el);

        if (!this.el || !to_display) return;

        this.options.type = $type(to_display);

        if (to_display.id == 'family_album_images' || to_display.id == 'pig_big_slideshow_images') {
            if (this.options.type == 'element') this.content = $(to_display).dispose();
        }
        else {
            if (this.options.type == 'element') this.content = $(to_display);
        }

        if (onShow) this.Callbacks.onShow = onShow;

        this.el.addEvent('click', this.Callbacks.displayMask.bindWithEvent(this));
    },

    Callbacks: {
        displayMask: function(e) {
            e.preventDefault();

            if (this.content) ChipotlePresenter.Base.showContent(this.content.clone(true, true), this.Callbacks.onShow);
            else this.Callbacks.ajaxContent();
        },
        ajaxContent: function() {
            //ajax call needs to take place here to get the content,
            //then populate the dom element into this.content,
            //and execute ChipotlePresenter.Base.showContent as above
        },
        onShow: null
    }
});

ChipotlePresenter.extend({
    Base:
	{
	    Options: {
	        opacity: .9
	    },
	    // Must be called before creating Chipotle Presentor instances
	    Init: function(bool) {
	        this.Mask =
			{
			    Fx: new Fx.Morph(new Element('div', {
			        'class': 'M_lightbox_shade',
			        'styles': {
			            'opacity': 0,
			            'z-index': 9999,
			            'position': 'absolute',
			            'top': 0,
			            'display': 'none'
			        }

			    }).inject($(document.body)), {
			        duration: 500,
			        fps: 1000,
			        onComplete: this.maskAnimComplete.bind(this)
			    }),
			    show: function() {
			        this.showMask.apply(this);
			    },
			    hide: function() {
			        this.Mask.Fx.set({ 'display': 'none' });
			        this.Mask.Shim.hide();
			    }
			};

	        this.Mask.Shim = new IframeShim(this.Mask.Fx.element);

	        this.windowContainer = new Element('div', {
	            'styles':
				{
				    'position': 'absolute',
				    'z-index': 9999,
				    'top': 0,
				    'left': 0
				},
	            'events': { 'click': this.hideMask.bind(this) }
	        });

	        this.contentContainer = new Element('div', {
	            'class': 'M_lightbox_content',
	            'events': {
	                'click': function(e) { e.stopPropagation(); }
	            }
	        }).inject(this.windowContainer);

	        var LightboxClose = new Element('div',
			{
			    'class': 'M_lightbox_close',
			    'text': 'Close',
			    'events': {
			        'click': this.hideMask.bind(this)
			    }
			}).inject(this.contentContainer);

	        this.content = new Element('div').inject(this.contentContainer);
	    },
	    showMask: function() {
	        this.Mask.Fx.set({
	            'top': $(window).getScroll().y,
	            'height': $(window).getSize().y,
	            'width': $$('.Template')[0].getSize().x,
	            'display': 'block'
	        });

	        this.Mask.Shim.show();
	        this.Mask.Shim.position();

	        this.Mask.Fx.start({ 'opacity': this.Options.opacity });
	    },
	    hideMask: function() {
	        this.windowContainer.dispose();
	        this.content.empty();
	        this.Mask.Fx.start({ 'opacity': 0 });
	    },

	    injectContent: function() {
	        var winfo = null;
	        if ($(document.body).getFirst('.Template') == null) {
	            winfo = document.getElementById('div-template').getSize();
	        }
	        else {
	            winfo = $(document.body).getFirst('.Template').getSize();
	        }
	        this.windowContainer.setStyles({
	            'height': $(document.body).getSize().y,
	            'width': winfo.x,
	            'top': $(window).getScroll().y
	        });

	        this.windowContainer.inject(document.body);

	        this.tempContent.inject(this.content).setStyle('display', 'block');
	        if ($type(this.tempOnShow) == 'function') {
	            this.tempOnShow();
	            this.tempOnShow = null;
	        }
	    },

	    showContent: function(content, onShow) {
	        this.tempContent = content;
	        this.tempOnShow = onShow;
	        this.Mask.show.apply(this);
	    },

	    maskAnimComplete: function() {
	        var op = this.Mask.Fx.element.getStyle('opacity');
	        if (op == this.Options.opacity) this.injectContent();
	        else this.Mask.hide.apply(this);
	    }
	}
});

// Flying Pig for the Fan-Antics UTF secondary UTF
var FlyingPiggy = new Class({
    initialize: function() {
        this.container = $('flying_pig');
        this.Animator = new Fx.Morph(this.container, {
            duration: 3000,
            fps: 1000,
            link: 'cancel',
            transition: 'sine:out',
            cyclePos: 'top',
            onStart: this.Callbacks.animStart.bind(this),
            onComplete: this.Callbacks.animComplete.bind(this)
        });


        this.Callbacks.startCycle.apply(this);
    },

    Callbacks: {
        startCycle: function() {
            var bot = parseInt(this.container.getStyle('bottom'), 10);
            this.Animator.options.duration = 4000;
            this.Animator.options.transition = 'sine:out';
            if (this.Animator.options.cyclePos == 'top') this.Animator.start({ bottom: bot - 50 });
            else this.Animator.start({ bottom: bot + 50 });
        },
        animStart: function() {
            if (this.Animator.options.cyclePos == 'top') this.Animator.options.cyclePos = 'bottom';
            else if (this.Animator.options.cyclePos == 'bottom') this.Animator.options.cyclePos = 'top';
        },
        animComplete: function() {
            this.Callbacks.startCycle.apply(this);
        },
        interrupt: function(where_to) {
            if (where_to == 'top') {
                this.Animator.options.duration = 1600;
                this.Animator.options.transition = 'elastic:out';
                this.Animator.start({ bottom: 880 });
                this.Animator.options.cyclePos = 'top';
                this.subs[1].setStyle('visibility', 'hidden');
                this.subs[2].setStyle('visibility', 'visible');
            }
            else if (where_to == 'middle') {
                this.Animator.options.duration = 4000;
                this.Animator.options.transition = 'elastic:out';
                this.Animator.start({ bottom: 300 });
                this.Animator.options.cyclePos = 'top';
                this.subs[1].setStyle('visibility', 'hidden');
                this.subs[2].setStyle('visibility', 'visible');
            }
            else if (where_to == 'bottom') {
                this.Animator.options.duration = 2000;
                this.Animator.options.transition = 'quad:out';
                this.Animator.start({ bottom: 30 });
                this.Animator.options.cyclePos = 'top';
            }
            else {
                this.Animator.options.duration = 8000;
                this.Animator.options.transition = 'elastic:out';
                this.Animator.start({ bottom: 190 });
                this.Animator.options.cyclePos = 'top';
                this.subs[1].setStyle('visibility', 'visible');
                this.subs[2].setStyle('visibility', 'hidden');
            }
        }
    }
});

// Quiz logic for Fan-Antics UTF
// Will create 1 of three answers
var FananticsQuiz = new Class({
    Options: {
        strings: {
            quiz: 'quiz',
            submit: 'quiz_submit',
            quizContainer: 'quiz_container',
            answerContainer: 'answer_container',
            quizAnswerClass: '.M_quiz_answer_image',
            tryAgain: 'quiz_try_again'
        }
    },
    Elements: {
        form: null
    },
    initialize: function() {
        var els = this.Elements;
        var str = this.Options.strings;

        els.former = $(str.quiz);
        els.quizContainer = $(str.quizContainer);
        els.answerContainer = $(str.answerContainer);

        els.timeRadios = $('time_radios').getElements('input');
        els.strengthRadios = $('strength_radios').getElements('input');
        els.itemRadios = $('item_radios').getElements('input');

        els.answers = els.answerContainer.getElements('.M_quiz_answer_image');

        this.Callbacks.clearRadios.apply(this);

        els.submitButton = $(str.submit);
        els.tryAgain = $(str.tryAgain);

        els.submitButton.addEvent('click', this.Callbacks.submitQuiz.bind(this));
        els.tryAgain.addEvent('click', this.Callbacks.tryAgain.bind(this));
    },

    Callbacks: {
        submitQuiz: function() {
            var els = this.Elements;
            var opts = this.Options;
            var points = 0;
            var answered1 = false;
            var answered2 = false;
            var answered3 = false;

            for (var x = 0; x < 3; x++) {
                if (els.timeRadios[x].checked == true) {
                    answered1 = true;
                    points += parseInt(els.timeRadios[x].value, 10);
                }
                if (els.strengthRadios[x].checked == true) {
                    answered2 = true;
                    points += parseInt(els.strengthRadios[x].value, 10);
                }
                if (els.itemRadios[x].checked == true) {
                    answered3 = true;
                    points += parseInt(els.itemRadios[x].value, 10);
                }
            }

            if (!(answered1 && answered2 && answered3)) {
                alert('Please answer all of the quiz questions.');
                return;
            }

            var answer = 0;
            if (points <= 5) answer = 0; // Could last a long time
            if (points > 5 && points <= 8) answer = 1; // Could last medium time
            if (points >= 9) answer = 2; // Could last no time

            els.answers[answer].setStyle('visibility', 'visible');
            els.quizContainer.setStyle('display', 'none');
            els.answerContainer.setStyle('display', 'block');
            this.Callbacks.clearRadios.apply(this);
        },

        clearRadios: function() {
            var els = this.Elements;
            els.timeRadios.setProperty('checked', false);
            els.strengthRadios.setProperty('checked', false);
            els.itemRadios.setProperty('checked', false);
        },
        tryAgain: function() {
            var els = this.Elements;

            els.answerContainer.setStyle('display', 'none');
            els.answers.setStyle('visibility', 'hidden');
            els.quizContainer.setStyle('display', 'block');
        }
    }
});

// Menu slideshow interaction
var MenuSlider = new Class({
	Options:{
		strings:{
			container_id:'burritos_tacos_more'
		},
		position:0,
		slide_width:796,
		animating:true
	},
	Elements:{
		container:null
	},
	initialize:function()
	{
		var opts = this.Options;
		var els = this.Elements;
		els.container = $(opts.strings.container_id);
		els.nav = els.container.getElements('.M_slide_nav a');
		els.navParents = els.container.getElements('.M_slide_nav li');
		els.slides = els.container.getElements('.M_slide');
		// Just in case we don't have the elements to make the slideshow...
		if(!els.container || els.nav.length==0 || els.slides.length==0 || els.nav.length!=els.slides.length) return;
		
		els.container.getParent('.Template').setStyles({'overflow':'hidden','position':'relative'});
		els.slides.setStyles({
			'position':'absolute',
			'top':40,
			'left':0,
			'display':'none',
			'width':opts.slide_width
		});
		
		els.container.setStyles({
			'position':'relative',
			'height':440
		});
		
		els.slides[0].setStyle('display','block');
		els.slides[0].inject(els.container);
		els.navParents[0].addClass('M_current');
		
		els.nav.each(function(el,index){
			el.addEvent('click',this.Callbacks.direction.bindWithEvent(this,index));
		},this);
		opts.animating = false;
	},
	Callbacks:{
		direction:function(e,index)
		{
			e.preventDefault();
			if(index==this.Options.position || this.Options.animating==true) return;
			
			this.Options.animating = true;
			
			if(index>this.Options.position) var direction = 'next';
			else var direction = 'prev';
			
			this.Callbacks.setupAnim.run([index,direction],this);
		},
		setupAnim:function(index,dir)
		{
			var wInfo = $(window).getSize().x;
			var cInfo = this.Elements.container.getPosition().x;
			var opts = this.Options;
			var els = this.Elements;
			
			
			if(dir=='next')
			{
				var setObj = { 1:{ 'left': wInfo-cInfo+100, 'display':'block' } };
				var startObj = {
					0:{ 'left':-(cInfo+opts.slide_width+100) },
					1:{ 'left': 0 }
				};
			}
			else
			{
				var setObj = { 1:{ 'left': -(cInfo+opts.slide_width+100), 'display':'block' } };
				var startObj = {
					0:{ 'left':wInfo-cInfo+100 },
					1:{ 'left': 0 }
				};
			}
			var tAnim = new Fx.Elements([els.slides[opts.position],els.slides[index]],{
				duration:400,
				transition:'cubic:in:out',
				onComplete:this.Callbacks.animComplete.bind(this,index)
			}).set(setObj);
			
			if(window.Browser.IE6==true) $(document.body).setStyles({'overflow-x':'hidden','position':'relative'});
			els.slides[index].inject(this.Elements.container);
			
			els.navParents[opts.position].removeClass('M_current');
			els.navParents[index].addClass('M_current');
			
			
			tAnim.start(startObj);
		},
		animComplete:function(index)
		{
			var opts = this.Options;
			var els = this.Elements;
			
			els.slides[opts.position].setStyle('display','none');
			opts.position = index;
			
			if(window.Browser.IE6==true) $(document.body).setStyle('overflow-x','auto');
			
			opts.animating=false;
		}
	}
});

// A hover state to show larger images on the FWI > Animals page
var ImageExpander = new Class({
	initialize:function(el)
	{
		this.el = $(el);
		if(!this.el) return;
		
		this.image = this.el.getElements('img')[1];
		if(!this.image) return;
		
		new Element('div',{
			'class':'M_hotspot',
			'events':{
				'mouseenter':this.Callbacks.hotspotOver.bind(this),
				'mouseleave':this.Callbacks.hotspotOut.bind(this)
			}
		}).inject(this.el);
	},
	Callbacks:{
		hotspotOver:function(e){ this.image.setStyle('display','block'); },
		hotspotOut:function(){ this.image.setStyle('display','none'); }
	}
});

// A universal class to add mini slideshow functionality
// Bear in mind, this may, more than likely require CSS to make it actually look right in new contexts
var MiniSlideshow = new Class({
	options:{
		position:0,
		animating:true
	},
	
	initialize:function(el,slide_class)
	{
		this.container = $(el);
		if(!this.container || $type(slide_class)!='string') return; // If there is no container or the slide_class is not a string, kill the constructor
		
		if(slide_class[0]!='.') slide_class = '.'+slide_class;
		
		this.slides = this.container.getElements(slide_class).dispose();
		
		if(this.slides.length<=1) return; // If 1 or 0 slides exist, kill the constructor
		
		this.slides.setStyles({
			'position':'absolute',
			'left':0,
			'top':0,
			'opacity':0
		});
		this.slides[0].inject(this.container).setStyle('opacity',1);
		
		this.slides.addEvent('click',this.Callbacks.next.bind(this));
		
		var btn_next = new Element('div',{
			'text':'Next',
			'class':'M_next',
			'events':
			{
				'click':this.Callbacks.next.bind(this),
				'mousedown':this.Callbacks.mouseDown,
				'mouseup':this.Callbacks.mouseUp
			}
		}).inject(this.container);
		
		var btn_prev = new Element('div',{
			'text':'Prev',
			'class':'M_prev',
			'events':
			{
				'click':this.Callbacks.prev.bind(this),
				'mousedown':this.Callbacks.mouseDown,
				'mouseup':this.Callbacks.mouseUp
			}
		}).inject(this.container);
		this.options.animating=false;
	},
	
	Callbacks:
	{
		next:function()
		{
			if(this.options.animating==true) return;
			this.options.animating=true;
			var newPos = this.options.position+1;
			if(newPos>=this.slides.length) newPos = 0;
			this.Callbacks.transition.run([newPos,'next'],this);
			
		},
		
		prev:function()
		{
			if(this.options.animating==true) return;
			this.options.animating=true;
			var newPos = this.options.position-1;
			if(newPos<0) newPos = this.slides.length-1;
			this.Callbacks.transition.run([newPos,'prev'],this);
		},
		
		transition:function(newPos,direction)
		{
			this.slides[newPos].inject(this.container);
			
			var keyframes = { 0:{ 'opacity':[1,0] }, 1:{ 'opacity':[0,1] } };
			
			new Fx.Elements([this.slides[this.options.position],this.slides[newPos]],{
				duration:600,
				fps:1000,
				transition:'quad:out',
				onComplete:this.Callbacks.animComplete.bind(this,newPos)
			}).start(keyframes);
		},
		
		animComplete:function(newPos)
		{
			this.slides[this.options.position].dispose();
			this.options.position = newPos;
			this.options.animating=false;
		},
		mouseDown:function(e){ e.preventDefault(); this.setStyle('margin-top',1); },
		mouseUp:function(e){ e.preventDefault(); this.setStyle('margin-top',0); }
	}
});

// Slideshow Slider for Chipotle Story > What's Going On
// Can take any number of elements and create a slideshow out of them, it relies on the content
var FullSlideshow = new Class({
	options:{
		animating:true,
		location:0
	},
	
	initialize:function(el)
	{
		// Get container, and main sub elements, create animation slider, inject slides into this
		this.container = $(el);
		if(!this.container) return;
		
		var slides = this.container.getElements('.M_slide').dispose();
		this.options.length = slides.length;
		
		this.slider = new Element('div',{
			'styles':{
				'position':'absolute',
				'width':796*slides.length,
				'top':55,
				'left':0,
				'height':280
			}
		}).inject(this.container);
		
		this.slider.adopt(slides);
		
		this.Animator = new Fx.Tween(this.slider,{
			duration:800,
			fps:1000,
			link:'cancel',
			transition:'cubic:in:out'
		});
		
		slides.setStyles({
			'position':'absolute',
			'margin':'0 0 0 10px'
		});
		
		slides.each(function(el,i){ el.setStyle('left',(i*796)); });
		
		this.container.setStyles({
			'height':325,
			'overflow':'hidden'
		});
		
		
		// Create HTML controls
		var controls = new Element('ul',{ 'class':'M_slide_controls' });
		
		controls.adopt(new Element('li',{
			'text':'previous',
			'class':'M_previous',
			'events':{
				'click':this.Callbacks.queueSlide.bind(this,'prev'),
				'mousedown':this.Callbacks.btnDown,
				'mouseup':this.Callbacks.btnUp
			}
		}));
		
		this.locations = [];
		
		for(var x=0,y=slides.length;x<y;x++) {
			this.locations[x] = new Element('li',{
				'text':x+1,
				'events':{
					'click':this.Callbacks.queueSlide.bind(this,x),
					'mousedown':this.Callbacks.btnDown,
					'mouseup':this.Callbacks.btnUp
				}
			});
			
			if(x==0) this.locations[x].addClass('M_current');
			
			controls.adopt(this.locations[x]);
		}
		
		this.locations = $$(this.locations);
		
		controls.adopt(new Element('li',{
			'text':'next',
			'class':'M_next',
			'events':{
				'click':this.Callbacks.queueSlide.bind(this,'next'),
				'mousedown':this.Callbacks.btnDown,
				'mouseup':this.Callbacks.btnUp
			}
		}));
		
		controls.inject(this.container.getFirst('div'));
	},
	
	Callbacks:{
		queueSlide:function(where_to)
		{
			if(where_to==this.options.location) return;
			
			if(where_to=='next')
			{
				where_to = this.options.location+1;
				if(where_to>=this.options.length) where_to=0;
			}
			if(where_to=='prev')
			{
				where_to = this.options.location-1;
				if(where_to<0) where_to=this.options.length-1;
			}
			
			this.locations.removeClass('M_current');
			
			this.locations[where_to].addClass('M_current');
			
			this.Callbacks.animateTo.run(where_to,this);
		},
		
		animateTo:function(loc)
		{
			var left = loc*796;
			this.options.location = loc;
			this.Animator.start('left',-left);
		},
		
		btnDown:function()
		{
			var el = $(this);
			if(!el.hasClass('M_current')) el.setStyle('margin-top',1);
		},
		btnUp:function()
		{
			var el = $(this);
			el.setStyle('margin-top',0);
		}
	}
});

// Accordian interaction for Fan-Antics > FAQ
var FAQAccordian = new Class({
	initialize:function(string)
	{
		this.container = $$(string)[0];
		if(!this.container) return;
		
		this.togglers = this.container.getElements('.M_accordian_toggle');
		this.elements = this.container.getElements('.M_accordian_content_container');
		
		this.headers = this.container.getElements('.M_accordian_toggle h3');
		
		this.headers.each(function(el){
			el.adopt(new Element('span'));
		});
		
		this.Accordion = new Fx.Accordion(this.container,this.togglers,this.elements,{
			duration:200,
			display:-1,
			returnHeightToAuto:false,
			opacity:true,
			transition:'sine:in:out',
			alwaysHide:true,
			initialDisplayFx:false,
			onBackground:function(tog)
			{
				tog.removeClass('M_expanded');
			},
			onActive:function(tog){
				tog.addClass('M_expanded');
			}
		});
	}
});

// Mini slideshow for brief FAQ
var TopFAQSlideshow = new Class({
	initialize:function()
	{
		this.element = $$('.M_faq_slideshow')[0];
		if(!this.element) return;
		
		this.buttons = $$('.M_faq_slideshow_button_prev, .M_faq_slideshow_button_next');
		
		this.questions = this.element.getElements('.M_faq_question').dispose();
		
		this.position = 0;
		this.current = this.questions[this.position].clone().inject(this.element);
		this.current.setStyles({'position':'absolute','top':0,'left':0});
		
		this.element.setStyle('overflow','visible');
		
		this.animating=true;
		this.buttons[0].addEvent('click',this.Callbacks.navigate.bind(this,false));
		this.buttons[0].addEvent('mousedown',this.Callbacks.mouseDown.bind(this,0));
		this.buttons[0].addEvent('mouseup',this.Callbacks.mouseUp.bind(this,0));
		
		this.buttons[1].addEvent('click',this.Callbacks.navigate.bind(this,true));
		this.buttons[1].addEvent('mousedown',this.Callbacks.mouseDown.bind(this,1));
		this.buttons[1].addEvent('mouseup',this.Callbacks.mouseUp.bind(this,1));
		
		this.animating=false;
	},
	
	Callbacks:{
		mouseDown:function(index){ this.buttons[index].setStyle('top',49); },
		mouseUp:function(index){ this.buttons[index].setStyle('top',48); },
		
		navigate:function(next){
			if(this.animating==true) return;
			this.animating=true;
			
			var setObj = { 0:{'position':'absolute','top':0,'opacity':0} };
			var startObj = {
				0:{ 'left':0, 'opacity':1 },
				1:{ 'opacity':0 }
			};
			
			if(next==true)
			{
				this.position++;
				if(this.position>=this.questions.length) this.position = 0;
				
				setObj[0]['left'] = 40;
				startObj[1]['left'] = -40;
			}
			else
			{
				this.position--;
				if(this.position<0) this.position = this.questions.length-1;
				
				setObj[0]['left'] = -40;
				startObj[1]['left'] = 40;
			}
			
			this.newQuestion = this.questions[this.position].clone();
			
			var tempFx = new Fx.Elements([this.newQuestion,this.current],{
				transition:'circ:out',
				duration:400,
				fps:1000,
				onComplete:this.Callbacks.animationComplete.bind(this)
			}).set(setObj);
			
			tempFx.elements[0].inject(this.element);
			tempFx.start(startObj);
		},
		
		animationComplete:function()
		{
			this.current.destroy();
			this.current = this.newQuestion;
			this.newQuestion=null;
			this.animating=false;
		}
	}
});

// A single use slideshow for Fan-Antics
var FananticsSlideshow = new Class({
	initialize:function()
	{
		// Get the image container
		this.container = $$('.M_fanantics_slide_show')[0];
		if(!this.container) return;
		
		// Get the images, and remove them from the dom
		this.images = this.container.getChildren('img').dispose();
		
		// Set slideshow position to the beginning (0)
		this.position = 0;
		
		// Inject a clone of first image, no animations needed
		this.images[this.position].clone().inject(this.container);
		
		// Start the slideshow timer
		setTimeout(this.Callbacks.timeout.bind(this),2000);
	},
	
	Callbacks:
	{
		timeout:function()
		{
			// Increment the slideshow position
			this.position++;
			// Error check the position (ensure it does not exceed the number of images, otherwise restart)
			if(this.position==this.images.length) this.position = 0;
			
			// Create a temporary animation object with a cloned image, set its opaicty to 0, bind the animation complete event
			var tempFx = new Fx.Tween(this.images[this.position].clone(),{
				duration:800,
				onComplete:this.Callbacks.animation.bind(this)
			}).set('opacity',0);
			
			// Inject the cloned image, and start the animation
			tempFx.element.inject(this.container);
			tempFx.start('opacity',1);
		},
		
		// Called when the slideshow animation is complete
		animation:function()
		{
			// Remove the old image, and start the the timer
			this.container.getFirst('img').destroy();
			setTimeout(this.Callbacks.timeout.bind(this),2000);
		}
	}
});

// Setups interaction for major tabs
var DynamicTabs = new Class({
    initialize: function() {
        this.Elements.tabs = $$('.tab_nav input');
        this.Elements.groups = $$('.Module.tab_section');

        if (this.Elements.tabs.length != this.Elements.groups.length) return;

        this.Elements.tabs.each(function(el, index) {
            el.addEvent('click', this.Callbacks.clickTab.bindWithEvent(this, index));
            if (index == 0) {
                this.Elements.groups[index].style.display = '';
                el.getParent().addClass('M_tabbed_current');
            }
            else {
                this.Elements.groups[index].style.display = 'none';
            }
        }, this);
    },

    Elements: {},
    Callbacks:
	{
	    clickTab: function(e, index) {
	        e.preventDefault();
	        this.Elements.tabs.each(function(el, i) {
	            el.getParent().removeClass('M_tabbed_current');
	            this.Elements.groups[i].style.display = 'none';
	        }, this);

	        this.Elements.tabs[index].getParent().addClass('M_tabbed_current');
	        this.Elements.groups[index].style.display = 'block';
	    }
	}
});

var aboveFoil = "true";
function foilQuery() {
    return aboveFoil;
}
function doAboveFoil() {
    aboveFoil = "true";
    reloadMute();
}
function doBelowFoil() {
    aboveFoil = "false";
    reloadMute();
}
function reloadMute() {
    var el = document.getElementById("MuteShell");
    if (el) {
        el.innerHTML = '<div id="MuteButton"><\/div>';
    }
    LoadMuteButton();
}

// UTF Transition Logic
// Can take any number of switches
var UnderTheFoil = new Class({
    Elements: {
        template: null,
        atf: null,
        utf: null,
        content: null,
        Switches: []
    },

    initialize: function(switches) {
        if ($type(switches) == 'string') switches = [switches];
        if (!$(switches[0])) return;


        this.Elements.atf = $$('.Template.atf')[0];
        this.Elements.anim_content = $$('.Region.content')[0];
        this.Elements.utf = $$('.Template.utf')[0];
        this.Elements.utfHidden = this.Elements.utf.getFirst('.hidden');
        this.Elements.content = new Element('div', { styles: { 'position': 'relative'} }).inject(this.Elements.anim_content, 'before');

        this.Elements.content.adopt(this.Elements.anim_content);

        this.Elements.return_message = new Element('div', {
            'class': 'Module pull_to_return',
            'styles': { 'opacity': 0 },
            'events': { 'click': this.Callbacks.switchClick.bind(this) }
        }).inject($$('.Region.utf_switch')[0]);

        this.Animator = new Fx.Elements(
		[
			this.Elements.content,
			this.Elements.utf,
			this.Elements.atf,
			this.Elements.utfHidden,
			this.Elements.return_message
		], {
		    duration: 700,
		    fps: 1000,
		    transition: 'quad:in:out',
		    open: false,
		    link: 'ignore',
		    contentHeight: this.Elements.content.getSize().y,
		    windowHeight: this.Utilities.getWindowSize.bind(this),
		    utfHeight: this.Elements.utf.getSize().y,
		    isIE6: window.Browser.IE6,
		    animating: false,
		    onStart: this.Callbacks.animatorStart.bind(this),
		    onComplete: this.Callbacks.animatorEnd.bind(this)
		});

        this.Animator.set({
            0: { position: 'relative', width: 960, height: this.Elements.content.getSize().y, margin: '0 auto' },
            1: { top: 130, height: this.Utilities.getWindowSize.bind(this), position: 'absolute' }, //height:this.Elements.content.getSize().y+110
            3: { opacity: 0 }
        });

        if (Browser.Engine.name == 'trident') this.Animator.set({ 3: { opacity: 1, height: 0, overflow: 'hidden'} });

        this.Scroller = new Fx.Scroll($(window), { duration: 600, transition: 'sine:out' });

        this.Elements.anim_content.style.position = 'absolute';
        this.Elements.anim_content.style.bottom = '0';

        switches.each(function(el, index) {
            this.Elements.Switches[index] = $(el);
            this.Elements.Switches[index].addEvent('click', this.Callbacks.switchClick.bind(this));
        }, this);

        $(window).addEvent('resize', this.Callbacks.windowResize.bind(this));
        this.Callbacks.windowResize.bind(this);       
    },

    Utilities: {
        getWindowSize: function() {
            var content_size = this.Animator.options.contentHeight + 110;
            var window_size = $(window).getSize().y - 130;

            if (content_size > window_size) return content_size;
            else return window_size;
        }
    },

    Callbacks: {
        windowResize: function() {
            var opts = this.Animator.options;
            opts.windowHeight = this.Utilities.getWindowSize.bind(this);


            if (opts.open == false) this.Animator.set({ 1: { height: this.Utilities.getWindowSize.bind(this)} });
            else {
                var width = $(window).getSize().x;
                this.Animator.set({ 1: { width: width }, 2: { width: width} });
            }
        },

        animatorStart: function() {
            this.Animator.options.animating = true;
            this.Scroller.toTop();
        },

        animatorEnd: function() {
            if (this.Animator.options.open == true) {
                if (navigator.userAgent.match('MSIE')) {
                    this.Animator.set({ 4: { opacity: '1'} });
                    //SwitchOnSoundBelowTheFoil();
                    doBelowFoil();
                    //setTimeout("doBelowFoil()", 900);
                }
                else {
                    //setTimeout("SwitchOnSoundBelowTheFoil()", 1000);
                    doBelowFoil();
                }
            }
            else {
                //SwitchOnSoundAboveTheFoil();
                doAboveFoil();
            }
            if (this.Animator.options.isIE6 == false) {
                if (this.Animator.options.open == true) {
                    this.Animator.options.unit = '%';
                    if (Browser.Engine.name == 'trident') this.Animator.set({ 2: { width: 100} });
                    this.Animator.set({ 2: { position: 'fixed'} });
                    this.Animator.options.unit = 'px';
                }
                else {
                    this.Animator.options.unit = '%';
                    this.Animator.set({ 1: { width: 100 }, 2: { width: 'auto', position: 'relative'} });
                    this.Animator.options.unit = 'px';
                    if (Browser.Engine.name != 'trident') $(document.body).style.overflowX = 'auto';
                }
            }
            this.Animator.options.animating = false;
        },

        switchClick: function() {
            if (this.Animator.options.open == false && this.Animator.options.animating == false) {
                this.Animator.options.open = true;
                var set_obj = { 0: { overflow: 'hidden'} };
                var anim_obj = { 0: { height: 0 }, 1: { height: this.Animator.options.utfHeight} };

                if (Browser.Engine.name != 'trident') {
                    var width = this.Elements.utf.getSize().x;
                    set_obj['1'] = { width: width };
                    set_obj['2'] = { width: width };
                    $(document.body).style.overflowX = 'hidden';

                    anim_obj['3'] = { opacity: 1 };
                    anim_obj['4'] = { opacity: 1 };
                }
                else anim_obj['3'] = { height: this.Animator.options.utfHeight };
                this.Animator.set(set_obj);
                this.Animator.start(anim_obj);
                setTimeout(this.Animator.set({ 4: { opacity: '1'} }), 1200);
            }
            else if (this.Animator.options.animating == false) {
                this.Animator.options.open = false;

                if (Browser.Engine.name != 'trident') {
                    this.Animator.start({
                        0: { height: this.Animator.options.contentHeight },
                        1: { height: this.Animator.options.windowHeight },
                        3: { opacity: 0 },
                        4: { opacity: [1, 0] }
                    });
                }
                else {
                    this.Animator.start({
                        0: { height: this.Animator.options.contentHeight },
                        1: { height: this.Animator.options.windowHeight },
                        3: { height: 0 },
                        4: { opacity: [1, 0] }
                    });
                }
            }
        }
    }
});

// Top nav interaction
var PrimaryNavigation = new Class({
    options: {
        timer: null
    },
    initialize: function(el, class_string, secondary_class) {
        var opts = this.options;

        opts.container = $(el);
        opts.anchor_class = '.' + class_string;
        opts.secondary_class = '.' + secondary_class;
        opts.anim_els = [opts.container.getFirst('ul')];
        opts.anchors = [];

        opts.container.getElements(opts.anchor_class).each(function(el) {
            if (el.getNext(this.options.secondary_class)) {
                this.options.anchors.push(el);
                this.options.anim_els.push(el.getNext('ul'));
                el.addEvent('mouseenter', this.Callbacks.mouseOver.bind(this, [this.options.anim_els.length - 1]));
            }
            else {
                el.addEvent('mouseenter', this.Callbacks.storeOver.bind(this, [this.options.anim_els.length - 1]));
                el.addEvent('mouseleave', this.Callbacks.storeOut.bind(this));
            }
        }, this);

        this.options.anchorsSet = opts.container.getElements('.M_nav_primary_link');

        this.Animator = new Fx.Elements(opts.anim_els, {
            duration: 200,
            fps: 1000,
            link: 'cancel',
            transition: 'sine:out',
            state: 'closed'
        });

        this.Animator.set({
            1: { opacity: 0, display: 'block' },
            2: { opacity: 0, display: 'block' },
            3: { opacity: 0, display: 'block' },
            4: { opacity: 0, display: 'block' },
            5: { opacity: 0, display: 'block' }
        });

        opts.container.addEvent('mouseleave', this.Callbacks.outDelay.bind(this));
        opts.container.addEvent('mousemove', this.Callbacks.stopOut.bind(this));
    },

    Callbacks: {
        mouseOver: function(index) {
            if (this.Animator.options.state == 'closed') {
                this.Animator.options.state = 'open';

                var t_obj = { 0: { 'margin-top': 15} };
                t_obj[index] = { 'opacity': 1 };
                this.options.anchorsSet[index - 1].addClass('hovered');
                this.options.anchorsSet.setStyle('opacity', .35);
                this.options.anchorsSet[index - 1].setStyle('opacity', 1);

                if (document.getElementById('divToHideWhenHoverMenu') != null) {
                    document.getElementById('divToHideWhenHoverMenu').style.display = 'none';
                    document.getElementById('divToShowWhenHoverMenu').style.display = '';
                }

                this.Animator.start(t_obj);
            }
            else if (this.Animator.options.state == 'open') {
                var t_obj = { 0: { 'margin-top': 15 }, 1: { 'opacity': 0 }, 2: { 'opacity': 0 }, 3: { 'opacity': 0 }, 4: { 'opacity': 0 }, 5: { 'opacity': 0} };

                this.options.anchors.each(function(el) { if (el) el.removeClass('hovered'); });
                this.options.anchorsSet[index - 1].addClass('hovered');
                this.options.anchorsSet.setStyle('opacity', .35);
                this.options.anchorsSet[index - 1].setStyle('opacity', 1);
                t_obj[index] = { 'opacity': 1 };

                this.Animator.start(t_obj);
            }
        },

        storeOver: function(index) {
            this.options.anchorsSet.setStyle('opacity', .35);
            this.options.anchorsSet[index].setStyle('opacity', 1);
            this.Callbacks.mouseOut.run([true], this);
        },

        storeOut: function(index) {
            this.options.anchorsSet.setStyle('opacity', 1);
        },

        stopOut: function() { clearTimeout(this.options.timer); },

        outDelay: function() {
            clearTimeout(this.options.timer);
            this.options.timer = setTimeout(this.Callbacks.mouseOut.bind(this, false), 1000);
        },

        mouseOut: function(bool) {
            this.options.anchors.each(function(el) { if (el) el.removeClass('hovered'); });
            this.Animator.options.state = 'closed';
            if (bool == true) {
                this.Animator.start({ 1: { opacity: 0 }, 2: { opacity: 0 }, 3: { opacity: 0 }, 4: { opacity: 0 }, 5: { opacity: 0} });
            }
            else {
                this.options.anchorsSet.setStyle('opacity', 1);
                this.Animator.start({ 0: { 'margin-top': 15 }, 1: { 'opacity': 0 }, 2: { 'opacity': 0 }, 3: { 'opacity': 0 }, 4: { 'opacity': 0 }, 5: { 'opacity': 0} });
            }
            if (document.getElementById('divToHideWhenHoverMenu') != null) {
                setTimeout("document.getElementById('divToHideWhenHoverMenu').style.display = ''", 100);
                setTimeout("document.getElementById('divToShowWhenHoverMenu').style.display = 'none'", 100);
            }
        }
    }
});


// This is for IE6 only on the Homepage UTF section for the quiz hovers
// This is needed because IE6 does not support the css selector :hover on elements besides <a tags
var IE6UTFShowHide = new Class({
	initialize:function(classes)
	{
		var els = $(document.body).getElements(classes);
		els.addEvents({
			'mouseenter':this.mouseEnter,
			'mouseleave':this.mouseLeave
		});
	},
	mouseEnter:function(){
		$(this).getFirst('img').setStyle('visibility','visible');
	},
	mouseLeave:function()
	{
		$(this).getFirst('img').setStyle('visibility','hidden');
	}
});