var Site = {
    init: function() {
        Site.textSize.load('textSize');
        Site.overlay.init();
        Site.mainScroller = new MooShow('phoneSlides', 'siteNav', { mode: 'fade', duration: 700 });
    },

    textSize: {
        myCookie: null,
        opts: { duration: 60 },
        els: null,
        curr: 0,
        load: function(id) {
            this.els = $(id).getElements('a');

            if (this.els.length == 0) return;

            this.sizeMap = {
                0: "0.75em",
                1: "1.0em",
                2: "1.15em"
            }
            this.bdy = $pick($("siteContent"), $('siteBody'), new Element("div"));

            this.els.each(function(el, i) {
                el.addEvent('click', function() { this.loadCookie(i) } .bind(this))
            }, this);

            this.myCookie = (Cookie.read('text_size') || "0").toInt();

            if (!$chk(this.myCookie)) this.setCookie();

            this.loadCookie(this.myCookie);
        },
        setCookie: function() {
            //Writes default text-size
            this.myCookie = Cookie.write('text_size', 'small', this.opts);
        },
        loadCookie: function(num) {
            //Reset cookie with new value
            this.myCookie = Cookie.write('text_size', num, this.opts);

            //toggle on state if present
            if (this.els[this.curr].hasClass('active')) {
                this.els[this.curr].removeClass('active');
            }
            this.bdy.setStyle('font-size', this.sizeMap[num]);
            this.els[num].addClass('active');

            this.curr = num;
        }
    },

    overlay: {
        init: function() {
            this.centeredOver = $("siteWrap");
            this.scrolled = new Fx.Scroll($(document.body))

            this.build();

            this.pages = {
                "aaasa.html": {
                    targeted: this.wrap
                }
            };

            var toggles = [$("demo"), $$("#navitem2 a")[0]];


            toggles.each(function(el, i) {
                if ($type(el) != "element") return;

                var href = el.get("href");
                el.store("overhref", href);

                el.set({
                    href: "javascript:void(0);",
                    target: ""
                });

                el.addEvent("click", function(e) {
                    e.stop();
                    this.launch(href);
                } .bind(this))

            }, this)


            if (window.location.href.indexOf("overlay=true") != -1) {
                var item = null;
                toggles.each(function(el, i) {
                    if (el)
                     item = el; 
                })
                this.launch(item.retrieve("overhref"))
            }

        },

        build: function() {
            var targeted = $(document.body);

            this.overlay = new Element("div", { "id": "boxOverlay", opacity: 0.75, styles: { "display": "none"} }).addEvent("click", function() { this.collapse(); } .bind(this)).inject(targeted, "bottom");
            this.wrap = new Element("div", { "id": "boxWrap", styles: { "display": "none"} }).inject(targeted, "bottom");
            this.closeBtn = new Element("div", { "id": "boxClose" }).addEvent("click", function() { this.collapse(); } .bind(this)).inject(this.wrap);

        },

        launch: function(href) {
            this.page = ($A(href.split("/")).getLast()).toLowerCase();

            var req = new Request({ url: href })


            req.addEvents({
                success: function(txt, xml) {
                    this.setContent(txt);
                } .bind(this)
            });

            req.send();

            window.addEvent("resize", this.resizeOverlay.bind(this)).addEvent("scroll", this.resizeOverlay.bind(this))
        },


        collapse: function() {
            this.overlay.hide();
            this.wrap.hide();
            this.wrap.empty();
            window.removeEvents("resize").removeEvent("scroll")
        },

        setContent: function(els) {
            this.wrap.empty();
            this.closeBtn = new Element("div", { "id": "boxClose" }).addEvent("click", function() { this.collapse(); } .bind(this)).inject(this.wrap);

            var dummy = new Element("div", { "html": els, styles: { display: "none"} }).inject($(document.body))
            this.wrap.adopt(dummy.getElement("#overWrap"));
            dummy.destroy();

            this.setFlash();

            this.resizeOverlay();

            this.overlay.show();
            this.wrap.show();

            this.scrolled.toTop();
        },

        resizeOverlay: function() {
            this.overlay.setStyle("height", window.getScrollSize().y)

            var wrapStyle = {}
            wrapStyle.left = ($(document.body).getSize().x / 2).toInt() - (this.wrap.getStyle("width").toInt() / 2).toInt() + "px"
            wrapStyle.top = "100px"

            this.wrap.setStyles(wrapStyle);

        },

        setFlash: function() {
            var page = $A(window.location.href.split("/")).getLast();

            var flashvars = {
                xmlConfigUrl: "docs/swf/xml/videoPlayerConfig.xml",
                pageUrl: page
            };
            var params = {
                menu: "true",
                wmode: "opaque",
                bgcolor: "#ffffff",
                base: "",
                swliveconnect: "true",
                allowscriptaccess: "always",
                allowfullscreen: "true"
            };
            var attributes = {
                id: "videoSection",
                name: "videoSection"
            };
            swfobject.embedSWF(window.root + "docs/swf/videoSection.swf", "flashContent", "640", "386", "9.0.0", window.root + "docs/swf/expressInstall.swf", flashvars, params, attributes);
        }
    }
}
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: true		
	},
	
	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) 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)				
		}	
		
		if (this.controller) {
			this.navs = this.controller.getElements(this.options.navSelector)						
			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 && 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]('mouseenter', 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();
});