var SupportFormHandler = Class.create({
    initialize: function() {
        this.form = $('supportform');
        this.supportCode = $('code');
        this.agree = $('agree');
        this.submit = $('supportsubmit');
        this.submit.observe('click', this.handleClick.bind(this));
    },
    handleClick: function(e) {
        $$('div.error').each( function(d) {
            d.remove();
        });
        if ($F(this.agree) != "agreed") {
            e.stop();
            var errormsg = new Element('div', {'class': 'error'}).insert("You must agree to the Terms of Service.");
            this.agree.up().insert(errormsg);
        }
        if ($F(this.supportCode).length != 6) {
            e.stop();
            var errormsg = new Element('div', {'class': 'error'}).insert("Your code must be 6-digits long.");
            this.supportCode.up().insert(errormsg);
        }
    }
});

var Gallery = Class.create({
    initialize: function() {
        this.container = $('gallery');
        this.buildFader();
        this.container.insert(this.fader);
        this.buildHolder();
        this.container.insert(this.holder);
        this.image = null;
        this.anchor = null;
        this.initLinks();
    },
    initLinks: function() {
        this.links = $$('div#gallery a');
        this.links.each((function(l) {
            l.observe("click", this.handleClick.bind(this, l));
        }).bind(this));
    },
    handleClick: function() {
        arguments = $A(arguments);
        this.anchor = arguments.shift();
        var event = arguments.shift();
        event.stop();
        this.showImage();
    },
    buildFader: function() {
        this.fader = new Element('div', {'id': 'gallery-fader'});
        this.fader.visStatus = "hidden";
        this.fader.hide();
        
    },
    buildHolder: function() {
        this.holder = new Element('div', {'id': 'gallery-holder'});
        var caption = new Element('p', {'id': 'gallery-caption', 'class': 'center bold large'});
        caption.insert("Click anywhere to return.");
        this.holder.insert(caption);
        this.holder.handle = null;
        this.holder.visStatus = "hidden"
        this.holder.hide();
    },
    buildHandle: function() {
        this.holder.handle = new Element('div').setStyle({height: this.image.height + 'px'});
        this.holder.prev = new Element('div', {'id': 'gallery-prev'});
        this.holder.next = new Element('div', {'id': 'gallery-next'});
                
        this.holder.prev.observe('click', this.showPrevImage.bind(this));
        this.holder.next.observe('click', this.showNextImage.bind(this));
        
        this.holder.imgholder = new Element('div', {'id': 'gallery-imgholder'});
        this.holder.handle.insert(this.holder.prev);
        this.holder.handle.insert(this.holder.imgholder);
        this.holder.handle.insert(this.holder.next);
        this._adjustPagers();
    },
    _adjustPagers: function() {
        var viewport = $H(document.viewport.getDimensions());
        var imgheight = this.image.height;
        if (imgheight > viewport.get('height')) {
            imgheight = (viewport.get('height') * 0.80).round();
        }
        var imgwidth = this.image.width;
        if (imgwidth > viewport.get('width')) {
            imgwidth = (viewport.get('width') * 0.80).round();
        }
        
        var pagerStyle = {height: imgheight + 'px'};
        this.holder.prev.setStyle(pagerStyle);
        this.holder.next.setStyle(pagerStyle);
        this.holder.handle.setStyle({height: (imgheight + 10 + 2) + 'px'});
        this.holder.imgholder.setStyle({height: imgheight + 'px', width: imgwidth + 'px'});
        if (this.anchor == this.links.first()) {
            this.holder.prev.addClassName('disable');
        } else {
            this.holder.prev.removeClassName('disable');
        }
        if (this.anchor == this.links.last()) {
            this.holder.next.addClassName('disable');
        } else {
            this.holder.next.removeClassName('disable');
        }
    },
    showImage: function() {
        this.fader.setStyle({opacity: 0.0, background: "#fff url('images/ajax-loader.gif') center center no-repeat"});
        this.fader.show();
        this.fader.visStatus = "vis";
        this.fader.observe("click", this._hideAll.bind(this));
        new Effect.Fade(this.fader, {from: 0.0, to: 0.75, duration: .5, afterFinish: this._loadImage.bind(this, this._showHolder.bind(this))});
    },
    showPrevImage: function(e) {
        //stub
        e.stop();
        if (this.anchor == this.links.first()) {
            return;
        }
        this.anchor = this.links[this.links.indexOf(this.anchor) - 1];
        this.image.src = this.anchor.href;
        this._loadImage(this._afterImageChange.bind(this));
    },
    showNextImage: function(e) {
        //stub
        e.stop();
        if (this.anchor == this.links.last()) {
            return;
        }
        this.anchor = this.links[this.links.indexOf(this.anchor) + 1];
        this.image.src = this.anchor.href;
        this._loadImage(this._afterImageChange.bind(this));
    },
    _afterImageChange: function() {
        this.holder.imgholder.insert(this.image);
        this._adjustPagers();
        this._centerHolder();
    },
    //this needs to be split off into hide each item separately... I'll use an effect.queue
    _hideAll: function() {
        $A(arguments).shift().stop();
        if(this.holder && this.holder.visStatus != "hidden") {
            this._hideHolder();
        }
        if(this.fader && this.fader.visStatus != "hidden") {
            this._hideFader();
        }
    },
    _hideHolder: function() {
        this.holder.stopObserving('click');
        this.holder.next.stopObserving('click');
        this.holder.prev.stopObserving('click');
        this.holder.visStatus = "hidden";
        new Effect.Fade(this.holder, {from: 1.0, to: 0.0, duration: .25, queue: {position: 'end', scope: 'galleryscope'},
            afterFinish: this._hideHolder2.bind(this)});
    },
    _hideHolder2: function() {
        this.image.remove();
        this.holder.handle.remove();
        this.holder.hide();
    },
    _hideFader: function() {
        this.fader.stopObserving('click');
        this.fader.visStatus = "hidden";
        this.fader.setStyle({background: '#fff'});
        new Effect.Fade(this.fader, {from: 0.75, to: 0.0, duration: .25, queue: {position: 'end', scope: 'galleryscope'}, 
            afterFinish: this._hideFader2.bind(this)});
    },
    _hideFader2: function() {
        this.fader.hide();
    },
    _loadImage: function(callback) {
        if (this.image && this.image.up()) { this.image.remove();}
        
        this.image = new Element('img', {alt: 'Image View'});
        this.image.src = this.anchor.href;
        var self = this;
        setTimeout(function() {
            self._checkImage(callback);
        }, 100);
    },
    _checkImage: function(callback) {
        var self = this;
        if(this.image.complete) {
            callback();
        } else {
            setTimeout(function() {
                self._checkImage(callback);
            }, 100);
        }
    },
    _showHolder: function() {
        //abort if the fader isn't visable
        if (this.fader.visStatus == "hidden") { return; }
        
        this.holder.visStatus = "vis";
        this.holder.observe("click", this._hideAll.bind(this));
        this.holder.setOpacity(0.0);
        this.holder.show();
        this.buildHandle();
        this.holder.insert(this.holder.handle);
        this._afterImageChange();
        new Effect.Fade(this.holder, {from: 0.0, to: 1, duration: .5});
        
    },
    _centerHolder: function() {
        var halfWidth = (this.holder.clientWidth / 2).round();
        var halfHeight = (this.holder.clientHeight / 2).round();
        var centerX = (document.viewport.getWidth() / 2).round();
        var centerY = (document.viewport.getHeight() / 2).round();
        var newtop = centerY - halfHeight;
        if (newtop < 0) { newtop = 0};
        var newleft = centerX - halfWidth;
        if (newleft < 0) { newleft = 0};
        this.holder.setStyle({top: newtop + 'px',
        left: newleft + 'px'});
    }
});

var Navigation = Class.create({
	initialize: function() {
		//select li tags that only have a nested ul tag.
		this.navs = $$('#navbox > li').map( function(n) { if (n.down('ul')) { return n;} }).compact();
		this.subnavs = $$('#navbox > li > ul');
		var self = this;
		this.navs.each(function(n,i) {
			var anchor = n.down('a');
			anchor.nav = i;
			anchor.observe('click', function(e) { e.stop(); window.location = this.up('li').down('li').down('a').href; });
			anchor.observe('mousemove', self.reveal.bind(self));
		});
	},
	reveal: function(event) {
		var element = Event.element(event);
	    var currentSub = this.subnavs[element.nav];
	    var effectOptions = {duration: 0.25, queue: {position: 'end', scope: 'navscope'}};
	    if (currentSub.visible()) {
	        return;
	    } else {
        var effectarray = [];
        effectarray.push(new Effect.BlindDown(currentSub, {sync: true}));
        this.subnavs.each( function(s) {
            if (s.visible()) {
                effectarray.push(new Effect.BlindUp(s, {sync: true}));
            }
        });
        new Effect.Parallel(effectarray, {duration: 0.25, queue: {position: 'end', scope: 'navscope', limit: 1}});
	    }
    }
});
var TabRevealer = Class.create({
	initialize: function() {
		this.container = $('tabholder');
		this.pages = $$('div#tabholder > div');
		this.buttons = $$('div#tabholder > ul > li');
		this.currentPage = null;
		var self = this;
		this.pages.each( function(p) {
			p.hide();
		});
		this.buttons.each( function(b,i) {
			b.page = i;
			b.observe('mousemove', self.reveal.bind(self));
		});
	},
	reveal: function(event) {
		var element = Event.element(event);
		this.currentPage = this.pages[element.up('li').page];
		if (this.currentPage.visible()) {
		    return;
		} else {
			var found = false;
			var effectarray = [];
		    var effectOptions = {duration: .25, queue: {position: 'end', scope: 'tabscope', limit: 1}};
		    this.pages.each(function(p) {
		        if (p.visible()) {
		            effectarray.push(new Effect.SlideUp(p, {sync: true}));
		            found = true;
		        }
		    });
		    if (effectarray.size() > 0) {
				new Effect.Parallel(effectarray, {duration: .25, queue: {position: 'end', scope: 'tabscope', limit: 1}, afterFinish: this._afterReveal.bind(this)});
			} else {
				this._afterReveal();
			}
		}
    },
    _afterReveal: function() {
    	new Effect.SlideDown(this.currentPage, {duration: .25, queue: {position: 'end', scope: 'tabscope', limit: 1}});
    }
});

var mynav = null;
var mygallery = null;
var myform = null;
var mytabs = null;
	
document.observe('dom:loaded', function() {
	mynav = new Navigation();

    if ($('tabholder')) {
        mytabs = new TabRevealer();
    }
    if ($('gallery')) {
        mygallery = new Gallery();
    }

    if ($('supportform')) {
        myform = new SupportFormHandler();
    }
});