var PopDown = Class.create();
PopDown.i = 0;
PopDown.prototype = {
	initialize: function(trigger, popup) {
		PopDown.open   = false;
		this.trigger = trigger;
		this.popup   = $(popup);
		this.options = Object.extend({}, arguments[2] || {});
		this.start();
	},
	start: function() {
		if (this.trigger instanceof Array) {
			this.triggers = this.trigger;
		} else {
			this.triggers = [this.trigger];
		}
		if(this.popup){
		this.popup.hide();
		}
		this.triggers.each(function(t) {
			Event.observe(t, 'click', this.openInternal.bindAsEventListener(this));
		}.bind(this));
	},
	openInternal: function(event) {
		this.popup.show();
		Event.stop(event);
		PopDown.open = this;
		(this.options.onOpen || Prototype.emptyFunction)();
		(this.options.trackEvent || Prototype.emptyFunction)();
	}
};

/*--------------------------------------------------------------------------*/

var HowItWorksPop = Class.create();
HowItWorksPop.i = 0;
HowItWorksPop.prototype = {
	initialize: function(trigger, popup) {
		HowItWorksPop.open   = false;
		this.trigger = trigger;
		this.popup   = $(popup);
		this.options = Object.extend({}, arguments[2] || {});
		this.popup_is_set = false;
		this.start();
	},
	start: function() {
		if (this.trigger instanceof Array) {
			this.triggers = this.trigger;
		} else {
			this.triggers = [this.trigger];
		}

		if(this.popup){
		this.popup.hide();
		}
		this.triggers.each(function(t) {
			Event.observe(t, 'click', this.openInternal.bindAsEventListener(this));
		}.bind(this));
	},
	openInternal: function(event) {
		this.toTop();
		$('modal_overlay').show();
		Position.Center(this.popup, $('container'));
		this.closebtn  = this.popup.getElementsBySelector('div.close').first();

		this.closeListener = this.closeInternal.bindAsEventListener(this);
		Event.observe(document, 'click', this.closeListener);
		Event.observe(this.closebtn, 'click', this.closeListener);
		Event.observe(this.popup, 'click', function(event) {
			this.falseAlarm = true;
			this.toTop();
		}.bind(this));
		Event.stop(event);
		
		GoogleAnalytics.trackEvent('Home Page', 'How it Works');
		
		if (HowItWorksPop.open) { HowItWorksPop.open.closeInternal(false); }
		HowItWorksPop.open = this;

		(this.options.onOpen || Prototype.emptyFunction)();
		
		if (!this.popup_is_set) {
			new Ajax.Updater('how_inner', '/envelopes/control/howitworkspop', {
				method: 'get',
				onLoading: function () {
					//this.loader.show();
				}.bind(this),
					onComplete: function (t) {
						this.popup_is_set = true;
						//this.loader.hide();
						
						new Tabs('how');
						this.gallery('how');
						
						this.popup.getElementsBySelector('.gallery_trigger').each(function(el) {
							new PopUp(el, $('design2'));
						});
					
						Event.observe($('artwork_trigger'), 'click', function(event) {
							var image = document.createElement('img');
							var frame = $('how_gallery_photo');
							var togglers = $('how_gallery').getElementsBySelector('ul.controls li');
							
							image.setAttribute('src', $('artwork_1').readAttribute('href'));
							frame.update();
							frame.appendChild(image);
							togglers.each(function(t) {
								t.removeClassName("active");
							});
							$('artwork_1').up('li').toggleClassName("active");
						}.bind(this));
						
				}.bind(this),
				onFailure: function (t) {
					//this.loader.hide();
				}
			});
		}

	},
	gallery: function (container) {
		var links = $(container).getElementsBySelector('ul.controls li a');
		var frame = $('how_gallery_photo');
		
		links.each(function (el) {
			Event.observe(el, 'click', function (ev) {
				var image = document.createElement('img');
				image.setAttribute('src', el.readAttribute('href'));
				frame.update();
				frame.appendChild(image);
				
				var togglers = $(container).getElementsBySelector('ul.controls li');
				togglers.each(function(t) {
					t.removeClassName("active");
				});
				
				el.up('li').toggleClassName("active");
				
				Event.stop(ev);
			}.bind(this));
		});
		
	},
	closeInternal: function(event) {
		if (this.falseAlarm) {
			this.falseAlarm = false;
			return;
		}
		
		HowItWorksPop.open = false;
		$('modal_overlay').hide();
		this.popup.hide();

		Event.stopObserving(document, 'click', this.closeListener);
		Event.stopObserving(this.closebtn, 'click', this.closeListener);
		Event.stop(event);

		(this.options.onClose || Prototype.emptyFunction)();
	},
	toTop: function() {
		HowItWorksPop.i = HowItWorksPop.i + 1;
		this.popup.style.zIndex = HowItWorksPop.i + 120;
		this.popup.show();
	}
};

Effect.Transitions.easeInOutQuad = function(pos){
	if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,2);
    return -0.5 * ((pos-=2)*pos - 2); 
}

var Accordion = Class.create();
Accordion.prototype = {
	initialize : function (container) {
		this.container = container;
		this.slides = $(this.container).getElementsBySelector('.slide');
		this.start();
	},
	start: function () {
		this.slides.each(function (el, i) {
			Event.observe(el, 'click', function () { 
				this.shift(i); 
			}.bind(this));
		}.bind(this));
	},
	shift: function (idx) {
		this.slides.each(function (el, i) {
			if (i == idx) {
				/*
				new Effect.Morph(this.slides[i], {
					style: 'width:50%',
					duration: 0.25,
					transition: Effect.Transitions.easeInOutQuad
				});
				el.addClassName('active');
				*/
				el.addClassName('active');
				
				var label = el.down('div.header').innerHTML;
				label = label.replace(/[^-A-Za-z0-9 ]/g, "");
				label = label.strip();
				GoogleAnalytics.trackEvent('Home Page', 'Accordion', label);
			}
			else {
				el.removeClassName('active');
				/*
				new Effect.Morph(this.slides[i], {
					style: 'width:25%',
					duration: 0.25,
					transition: Effect.Transitions.easeInOutQuad
				});
				*/
				
			}
		}.bind(this));

	}
};

var TaskPop = Class.create();
Object.extend(Object.extend(TaskPop.prototype, PopUp.prototype), {
	initialize: function(trigger, popup) {
		PopUp.open   = false;
		this.trigger = trigger;
		this.popup   = $(popup);
		this.options = Object.extend({}, arguments[2] || {});
		this.menutogglers = this.popup.getElementsBySelector('.popupurl');
		this.start();
	},
	start: function() {
		if (this.trigger instanceof Array) {
			this.triggers = this.trigger;
		} else {
			this.triggers = [this.trigger];
		}

		if(this.popup){
		this.popup.hide();
		}
		this.triggers.each(function(t) {
			Event.observe(t, 'click', this.openInternal.bindAsEventListener(this));
		}.bind(this));
		
		// bind new event
		this.menutogglers.each(function (el, i) {
			el.observe('click', this.closeInternal.bindAsEventListener(this, i));
		}.bind(this));
	}
});

var TaskTabs = Class.create();
TaskTabs.prototype  = {
	initialize: function (container, options) {
		this.container  = $(container);
		this.togglers = this.container.getElementsBySelector('.togglers li');
		this.tabs = this.container.getElementsBySelector('.tab');
		this.itemlists = this.container.getElementsBySelector('.tab .items');
		this.urls = this.container.getElementsBySelector('.url');
		this.menutogglers = $('task_menu').getElementsBySelector('.popupurl');
		this.loader = $('task_loader');
		this.setup();
	},
	setup: function () {
		this.togglers.each(function (el, i) {
			el.observe('click', this.showTab.bindAsEventListener(this, i));
		}.bind(this));
		
		this.menutogglers.each(function (el, i) {
			el.observe('click', this.createTab.bindAsEventListener(this, i));
		}.bind(this));
		
		new TaskPop('task_menu_trigger', 'task_menu');

	},
	showTab: function (ev, i) {
		var labelTitle = this.urls[i].readAttribute('title');
		new Ajax.Updater(this.itemlists[i], ('/envelopes/control/task-invitations?title='+labelTitle), {
			method: 'get',
			onLoading: function () {
				$('task_loader').show();
			}.bind(this),
			onSuccess: function (t) {
				$('task_loader').hide();
				this.togglers.invoke('removeClassName', 'active');
				this.togglers[i].addClassName('active');
				this.tabs.invoke('removeClassName', 'active');
				$('tab_extra').removeClassName('active');
				this.tabs[i].addClassName('active');
				GoogleAnalytics.trackEvent('Home Page', 'Tasks', labelTitle.capitalize());
			}.bind(this),
			onFailure: function (t) {
				this.loader.hide();
			}
		});

		if (ev) {
			Event.stop(ev);
		}
	},
	createTab: function (ev, i) {
		var labelTitle = this.menutogglers[i].readAttribute('title');
		new Ajax.Updater(($('tab_extra').getElementsBySelector('.items')[0]), ('/envelopes/control/task-invitations?title='+labelTitle), {
			method: 'get',
			onLoading: function () {
				$('task_loader').show();
			}.bind(this),
			onSuccess: function (t) {
				$('task_loader').hide();
				this.togglers.invoke('removeClassName', 'active');
				this.tabs.invoke('removeClassName', 'active');
				
				//$('task_menu').hide();
				GoogleAnalytics.trackEvent('Home Page', 'Tasks', labelTitle.capitalize());
				$('tab_extra').getElementsBySelector('.header')[0].update(this.menutogglers[i].innerHTML);
				$('tab_extra').addClassName('active');
			}.bind(this),
			onFailure: function (t) {
				this.loader.hide();
			}
		});
		
		if (ev) {
			Event.stop(ev);
		}
	},
	close: function (ev, i) {
		this.togglers.invoke('removeClassName', 'active');
		this.tabs.invoke('removeClassName', 'active');
		if (ev) {
			Event.stop(ev);
		}
	}
};


var SlideShow = Class.create();
SlideShow.prototype = {
	initialize : function (initial, container, contents, delay, options) {
		this.initial = initial;
		this.container = container;
		this.contents = contents;
		this.delay = delay;
		this.fadeDuration = 0.5;
		this.showOnly(this.contents[this.initial]);
		this.current = initial;
		this.show = null;
		this.hide = null;
		
		this.options = Object.extend({
			prevToggler: '.prev',
			nextToggler: '.next',
			btnToggler: '.controls li'
		}, options || {});
		
		if (this.container.getElementsBySelector(this.options.prevToggler).length > 0 && this.container.getElementsBySelector(this.options.nextToggler).length > 0) {
			this.prevBtn = this.container.getElementsBySelector('.prev')[0].addClassName('active');
			this.nextBtn = this.container.getElementsBySelector('.next')[0].addClassName('active');
			this.prevBtn.observe('click', this.back.bindAsEventListener(this));
			this.nextBtn.observe('click', this.forward.bindAsEventListener(this));
		}
		else if (this.container.getElementsBySelector(this.options.btnToggler).length > 0) {
			this.buttons = this.container.getElementsBySelector(this.options.btnToggler);
			this.buttons.each(function (el, i) {
				
				el.observe('click', function (ev) {
					Event.stop(ev);
					this.pause();
					this.goTo(i, 0.5);
				}.bind(this));
				
			}.bind(this));
			
			this.buttons[this.current].addClassName('active');
		}
		else { 
			return;
		}
		
		//document.observe('pop:active',  this.pause.bind(this));
		//document.observe('pop:inactive',  this.start.bind(this));
		
		this.start();
	},
	start : function () {
		if (this.timer) { 
			return;
		}
		this.timer = setTimeout(this.next.bind(this), this.delay * 1000);
	},
	showOnly : function (el) {
		this.contents.invoke('hide');
		el.show();
	},
	pause : function () {
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = false;
		}
		if (this.hide) {
			this.hide.cancel();
		}
		else {
			return;
		}
	},
	back: function (ev) {
		if (this.show) {
			this.show.cancel();
			return;
		}	
		if (this.hide) {
			this.hide.cancel();
			return;
		}	

		this.pause(); 
		if (this.current === 0) {
			this.goTo(this.contents.length - 1);
		}
		else {
			this.goTo(this.current - 1);
		}
		Event.stop(ev);
	},
	forward: function (ev) {
		if (this.show) {
			this.show.cancel();
			return;
		}	
		if (this.hide) {
			this.hide.cancel();
			return;
		}	
		
		this.pause();
		this.next();
		Event.stop(ev);
	}, 
	next: function () {
		this.timer = false;
		if (this.current === this.contents.length - 1) {
			this.goTo(0);
		}
		else {
			this.goTo(this.current + 1);
		}
		this.start();
	},	
	goTo: function (idx, dur) {
		if (idx === this.current) { 
			return;
		}
		this.hide = new Effect.Fade(this.contents[this.current], { duration: this.fadeDuration || 2, afterFinish: function () {
			this.hide = null;
		}.bind(this)});
		
		if (this.buttons) {
			this.buttons[this.current].removeClassName('active');
		}
		
		this.current = idx;
		this.show = new Effect.Appear(this.contents[this.current], { duration: this.fadeDuration || 2, afterFinish: function () {
			this.show = null; 
		}.bind(this)});
		
		if (this.buttons) {
			this.buttons[this.current].addClassName('active');
			this.start();
		}
	}
};

/*--------------------------------------------------------------------------*/

Event.onDOMReady(function(){
								  
	// cache background images in ie6 to prevent multiple http requests
	if (Prototype.Browser.IE6) {
		try {
			document.execCommand('BackgroundImageCache', false, true);
		} catch (e) {}
	}
								  
	if ($('slideshow')) {
		new SlideShow(0, $('slideshow'), $$('#slideshow .slide'), 8);
	}
	
	new Tabs('tabs', 0, { eventCat: 'Home Page' });
	
	if ($('style_business_trigger') && $('style_business_pop')) {
		new PopUp('style_business_trigger', 'style_business_pop', {
			trackEvent: function() { GoogleAnalytics.trackEvent('Home Page', 'Menu', 'Business Envelopes') }});
	}
	
	if ($('style_social_trigger') && $('style_social_pop')) {
		new PopUp('style_social_trigger', 'style_social_pop', {
			trackEvent: function() { GoogleAnalytics.trackEvent('Home Page', 'Menu', 'Social & Invitation') }});
	}
	
	if ($('style_shipping_trigger') && $('style_shipping_pop')) {
		new PopUp('style_shipping_trigger', 'style_shipping_pop', {
			trackEvent: function() { GoogleAnalytics.trackEvent('Home Page', 'Menu', 'Shipping & Packaging') }});
	}
	
	if ($('style_paper_trigger') && $('style_paper_pop')) {
		new PopUp('style_paper_trigger', 'style_paper_pop', {
			trackEvent: function() { GoogleAnalytics.trackEvent('Home Page', 'Menu', 'Paper & More') }});
	}
	
	if ($('popular_trigger') && $('popular_down')) {
		new PopDown('popular_trigger', 'popular_down', {
			trackEvent: function() { GoogleAnalytics.trackEvent('Home Page', 'Menu', 'Most Popular Sizes') }});
	}
	
	if ($('how_it_works_trigger') && $('how')) {
		new HowItWorksPop('how_it_works_trigger', 'how');
	}

	if ($('accordion')) {
		new Accordion('accordion');
	}
	
	if ($('task_tabs')) {
		new TaskTabs($('task_tabs'));
	}
	
	if ($('learn_more_popup_trigger') && $('learn_more_popup')) {
		new PopUp('learn_more_popup_trigger', 'learn_more_popup');
	}

});
