/* SlideShow
----------------------------------------------------------------------------------------*/
var SlideShow = Class.create();
SlideShow.prototype = {
	initialize : function(initial, contents, buttons, delay){
		this.initial = initial;
		this.contents = contents;
		this.buttons = buttons;
		this.delay = delay;
		this.showOnly(this.contents[this.initial]);
		this.current = initial;
		this.buttons[this.current].addClassName('active');
		this.start();
		this.show = null, this.hide = null;
		this.buttons.each(function(el, i){
			el.observe('click', (function(ev){
				ev.stop();
				this.pause();
				this.goTo(i, .5);
			}).bind(this));
		}.bind(this));
		
		this.buttons[0].up().observe('mouseleave', function(ev){
			this.start();
		}.bind(this));
	},
	start : function(){
		if (this.timer) return;
		this.timer = setTimeout(this.next.bind(this), this.delay * 1000); //new PeriodicalExecuter(this.next.bind(this), this.delay);
	},
	showOnly : function(el){
		this.contents.each(Element.hide);
		el.show();
	},
	pause : function(){
		if (this.timer){
			clearTimeout(this.timer);
			this.timer = false;
		}
		this.hide ? this.hide.cancel() : 0; 
		this.show ? this.show.cancel() : 0;
	},
	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 : dur || 2});
		this.buttons[this.current].removeClassName('active');
		this.current = idx;
		this.show = new Effect.Appear(this.contents[this.current],{duration: dur || 2});
		this.buttons[this.current].addClassName('active');
	},
	getCurrent : function(){
		return this.current;
	}
};

/* BasicSlideShow
----------------------------------------------------------------------------------------*/
var BasicSlideShow = Class.create();
BasicSlideShow.prototype = {
	initialize : function(initial, container, contents, prev, next, delay, options){
		this.initial = initial;
		this.container = container;
		this.contents = contents;
		this.delay = delay;
		this.showOnly(this.contents[this.initial]);
		this.current = initial;
		this.start();
		this.show = null, this.hide = null;
		
		this.options = Object.extend({
			modal: false
		}, options);		

		if(this.options.modal) {
			this.close = this.container.down('.close');
			this.close.observe('click', this.pause.bind(this));
		}
		
		prev.observe('click', this.back.bind(this));
		next.observe('click', this.forward.bind(this));
		
	},
	back: function(ev){
		ev.stop(); 
		if (this.show || this.hide) return;
		this.pause(); 
		if (this.current ==0 )
			this.goTo(this.contents.length-1);
		else
			this.goTo(this.current-1);
	},
	forward: function(ev){
		ev.stop(); 
		if (this.show || this.hide) return;
		this.pause();
		this.next();
	}, 
	start : function(){
		if (this.timer) return;
		this.timer = setTimeout(this.next.bind(this), this.delay * 1000); //new PeriodicalExecuter(this.next.bind(this), this.delay);
	},
	showOnly : function(el){
		this.contents.each(Element.hide);
		el.show();
	},
	pause : function(){
		if (this.timer){
			clearTimeout(this.timer);
			this.timer = false;
		}
		this.hide ? this.hide.cancel() : 0; 
		this.show ? this.show.cancel() : 0;
	},
	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 : dur || 1, afterFinish:function(){this.hide=null;}.bind(this)});
		this.current = idx;
		this.show = new Effect.Appear(this.contents[this.current],{duration: dur || 1, afterFinish:function(){this.show=null;}.bind(this)});
		this.start();
	},
	getCurrent : function(){
		return this.current;
	}
};

/* SimpleSlideShow
----------------------------------------------------------------------------------------*/
var SimpleSlideShow = Class.create();
SimpleSlideShow.prototype = {
	initialize : function(initial, contents, delay){
		this.initial = initial;
		this.contents = contents;
		this.delay = delay;
		this.showOnly(this.contents[this.initial]);
		this.current = initial;
		this.start();
		this.show = null, 
		this.hide = null;
	},
	start : function(){
		if (this.timer) return;
		this.timer = setTimeout(this.next.bind(this), this.delay * 1000); //new PeriodicalExecuter(this.next.bind(this), this.delay);
	},
	showOnly : function(el){
		this.contents.each(Element.hide);
		el.show();
	},
	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 : dur || 2});
		this.current = idx;
		this.show = new Effect.Appear(this.contents[this.current],{duration: dur || 2});
	},
	getCurrent : function(){
		return this.current;
	}
};

/* ModalSlideShow
----------------------------------------------------------------------------------------*/
var ModalSlideShow = Class.create();
ModalSlideShow.prototype = {
	initialize : function(initial, trigger, container, contents, prev, next, delay){
		this.initial = initial;
		this.trigger = trigger;
		this.container = container;
		this.contents = contents;
		this.delay = delay;
		this.showOnly(this.contents[this.initial]);
		this.current = initial;
		//this.start();
		this.show = null, this.hide = null;
		this.close = this.container.down('.close');
		
		//this.trigger.observe('click', this.start.bind(this));
		this.close.observe('click', this.pause.bind(this));
		prev.observe('click', this.back.bind(this));
		next.observe('click', this.forward.bind(this));
		
	},
	back: function(ev){
		ev.stop(); 
		if (this.show || this.hide) return;
		this.pause(); 
		if (this.current ==0 )
			this.goTo(this.contents.length-1);
		else
			this.goTo(this.current-1);
	},
	forward: function(ev){
		ev.stop(); 
		if (this.show || this.hide) return;
		this.pause();
		this.next();
	}, 
	start : function(){
		if (this.timer) return;
		this.timer = setTimeout(this.next.bind(this), this.delay * 1000); //new PeriodicalExecuter(this.next.bind(this), this.delay);
	},
	showOnly : function(el){
		this.contents.each(Element.hide);
		el.show();
	},
	pause : function(){
		if (this.timer){
			clearTimeout(this.timer);
			this.timer = false;
		}
		//this.hide ? this.hide.cancel() : 0; 
		//this.show ? this.show.cancel() : 0;
	},
	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 : dur || 1, afterFinish:function(){this.hide=null;}.bind(this)});
		this.current = idx;
		this.show = new Effect.Appear(this.contents[this.current],{duration: dur || 1, afterFinish:function(){this.show=null;}.bind(this)});
		this.start();
	},
	getCurrent : function(){
		return this.current;
	}
};



/* Prototype-based javascript window dimensions
http://textsnippets.com/posts/show/835 
----------------------------------------------------------------------------------------*/
Position.GetWindowSize = function(w) {
        w = w ? w : window;
        var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
        var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
        return [width, height]
}

/* Center a DOM element, prototype based
http://textsnippets.com/posts/show/836
----------------------------------------------------------------------------------------*/
Position.Center = function(element, parent) {
	var w, h, pw, ph;
	var d = Element.getDimensions(element);
	w = d.width;
	h = d.height;
	Position.prepare();
	if (!parent) {
			var ws = Position.GetWindowSize();
			pw = ws[0];
			ph = ws[1];
	} else {
			pw = parent.offsetWidth;
			ph = parent.offsetHeight;
	}
	element.style.top = (ph/2) - (h/2) +  Position.deltaY + "px";
	element.style.left = (pw/2) - (w/2) +  Position.deltaX + "px";
}

/* CenteredPop
----------------------------------------------------------------------------------------*/
var CenteredPop = Class.create({
	initialize : function(trigger, pop, options){
		this.trigger = trigger;
		this.pop = pop;
		
		this.options = Object.extend({
			modal: false,
			cancel: false
		}, options);		
		
		if(this.options.cancel)
			this.options.cancel.observe('click', this.close.bind(this));
		
		this.trigger.observe('click', this.open.bind(this));
		this.pop.down('.close').observe('click', this.close.bind(this));
		this.bound_close = this.close.bind(this);	

	},
	open : function(ev){
		ev.stop();
		document.fire("pop:active");
		Position.Center(this.pop);
		this.pop.appear({duration:.1});
		if(this.options.modal) {	
			$('modal_overlay').style.height = Position.GetWindowSize()[1] + 500 + "px";
			$('modal_overlay').show();
		}
	},
	close : function(ev){
		ev.stop();
		document.stopObserving('pop:active', this.bound_close);
		this.pop.fade({duration:.1});
		if(this.options.modal) {
			$('modal_overlay').hide();
		}
	}
});

/* SimplePop
----------------------------------------------------------------------------------------*/
var SimplePop = Class.create({
	initialize : function(trigger, pop){
		this.trigger = trigger;
		this.pop = pop;
		this.trigger.observe('click', this.open.bind(this));
		this.pop.down('.close').observe('click', this.close.bind(this));
	},
	open : function(ev){
		ev.stop();
		this.pop.show();
	},
	close : function(ev){
		ev.stop();
		this.pop.hide();
	}
});

/* Tabs
----------------------------------------------------------------------------------------*/
var Tabs = Class.create({
	initialize: function(container, togglers, tabs, active) {
		this.container = $(container);
		this.togglers = $(togglers);
		this.tabs = $(tabs);
		this.active    = active || 0;
		this.setup();
	},
	setup: function() {
		this.tabs[this.active].addClassName('active');
		this.togglers[this.active].addClassName('active');
		this.togglers.each(function(el, i) {
			el.onclick = function() {
				if (i != this.active) {
					el.addClassName('active');
					this.togglers[this.active].removeClassName('active');
					
					if(this.tabs.length == this.togglers.length){
						this.tabs[this.active].removeClassName('active');
						this.tabs[i].addClassName('active');
					}
				}
				this.active = i;
				return false;
			}.bind(this);
		}.bind(this));
	}
});

/* Revealer
----------------------------------------------------------------------------------------*/
var Revealer = Class.create({
	initialize: function(trigger, content, options) {
		this.trigger = trigger;
		this.content = content;
		this.options = options;
		
		console.log(this.content);
		
		if(this.trigger && this.content)
			this.setup();
	},
	setup: function() {
		this.trigger.observe('click', this.open.bind(this));
		if(this.options) {
			if(this.options.deactivate)
				this.options.deactivate.observe('click', this.close.bind(this));
		}
	},
	open: function(ev) {
		if(!this.content.hasClassName("active")) {
			Effect.SlideDown(this.content, { duration: .6 });
			this.content.addClassName("active");
		}
	},
	close: function(ev) {
		if(this.content.hasClassName("active")) {
			Effect.SlideUp(this.content, { duration: .6 });
			this.content.removeClassName("active");
		}
	}
});

/* SimpleToggler
----------------------------------------------------------------------------------------*/
var SimpleToggler = Class.create({
	initialize: function(trigger, content) {
		this.trigger = trigger;
		this.content = content;
		
		if(this.trigger && this.content)
			this.setup();
	},
	setup: function() {
		//this.calcHeight();
		this.trigger.observe('click', this.toggler.bind(this));
	},
	calcHeight: function() {
		var dimensions = this.content.getDimensions();
		this.content.style.height = dimensions.height + "px";
	},
	toggler: function(ev) {
		this.trigger.toggleClassName("active");
		Effect.toggle(this.content, 'slide', { duration: .4 }); 
		ev.stop();
	}
});

/* HoverDelay
----------------------------------------------------------------------------------------*/
var HoverDelay = Class.create({
	initialize : function(trigger, options){
		this.options = Object.extend({enterCb : function(){},	leaveCb : function(){},	delay : 0.5}, options || {});
		this.trigger = $(trigger);
		this.timeout = null; this.active = false;
		this.setup();
	},
	setup : function(){
		var eEvt = this.open.bindAsEventListener(this);
		var lEvt = this.close.bindAsEventListener(this);
		this.trigger.observe('mouseenter', eEvt);
		this.trigger.observe('mouseleave', lEvt);
		this.trigger.observe('hoverdelay:stop', function(){
			this.trigger.stopObserving('mouseenter', eEvt);
			this.trigger.stopObserving('mouseleave', lEvt);
		}.bind(this));
		/*
		document.observe('pop:active', function(){this.inactive=true;}.bind(this));
		document.observe('pop:inactive', function(){this.inactive=false;}.bind(this));
		*/
	}, 
	open : function(event){
		if (this.inactive) return;
		this.timeout = (function(){
			this.trigger.addClassName("active");
			this.options.enterCb.bind(this)();
			this.active = true;
		}).bind(this).delay(this.options.delay);
	},
	close : function(){
		if (this.inactive) return;
		if (this.timeout) {
			window.clearTimeout(this.timeout);
			this.timeout = null;
		}
		if (this.active){
			this.options.leaveCb.bind(this)();
			this.active = false;
			this.trigger.removeClassName("active");
		}
	}
});

/* ModalPop
----------------------------------------------------------------------------------------*/
var PopUp = Class.create({
	initialize : function(link, pop, opts){
		this.options = Object.extend({closeSelector : '.close', modal: false}, opts || {});
		this.pop = pop.setStyle({display:'none'});
		this.link = link;
		this.setup();
		this.pop.observe('pop:close', this.close.bind(this));
	},
	setup : function(){
		this.link.observe('click', this.open.bind(this));
		this.pop.select(this.options.closeSelector).each(function(el){
			el.observe('click', this.close.bind(this));
		}.bind(this));
	},
	open : function(ev){
		if (ev) ev.stop();
		if(this.options.modal) {
			$('modal_overlay').show();
			Position.Center(this.pop);
		}
		this.pop.appear({duration:.2});
		if (this.options.modal)document.fire('pop:active');
	},
	close : function(ev){
		if (ev) ev.stop();
		if(this.options.modal)
			$('modal_overlay').hide();
		this.pop.fade({duration:.2});
		if (this.options.modal) document.fire('pop:inactive');
	}
});

/* Custom ModalPop
----------------------------------------------------------------------------------------*/
var CustomPopUp = Class.create({
	initialize : function(pop, opts){
		this.options = Object.extend({closeSelector : '.close', modal: false}, opts || {});
		this.pop = pop.setStyle({display:'none'});
		this.setup();
		this.pop.observe('pop:close', this.close.bind(this));

    return this;
	},
	setup : function(){
		this.pop.select(this.options.closeSelector).each(function(el){
			el.observe('click', this.close.bind(this));
		}.bind(this));
	},
	open : function(ev){
		if (ev) ev.stop();
		if(this.options.modal) {
			$('modal_overlay').show();
			Position.Center(this.pop);
		}
		this.pop.appear({duration:.2});
		if (this.options.modal)document.fire('pop:active');
	},
	close : function(ev){
		if (ev) ev.stop();
		if(this.options.modal)
			$('modal_overlay').hide();
		this.pop.fade({duration:.2});
		if (this.options.modal) document.fire('pop:inactive');
	}
});

/* KickOut
----------------------------------------------------------------------------------------*/
var KickOut = Class.create(PopUp, {
	setup : function(){
		new HoverDelay(this.link, {
      delay   : 0.1,
			enterCb : this.open.bind(this),
			leaveCb : this.close.bind(this)
		});
	}
});

/* ToolTip
----------------------------------------------------------------------------------------*/
var ToolTip = Class.create(PopUp, {
	setup : function(){
		new HoverDelay(this.link, {
			enterCb : this.open.bind(this),
			leaveCb : this.close.bind(this),
			delay : 1
		});
	}
});

/* PageSlide
----------------------------------------------------------------------------------------*/
var PageSlide = Class.create({
	initialize : function(contents, num_slides, options){
		if(options.width)
			this.width = options.width;
		else
			this.width = 959;
		this.contents = contents;
		this.offset = contents.positionedOffset()[0];
		
		this.pArrow = $('btn_prev');
		this.nArrow = $('btn_next');
		this.slideCount = num_slides;

		this.steps = this.contents.select('.step');
		this.steps.each(function(el, idx) {
			el.observe('click', function(ev) {
				this.go(idx);
				//new Effect.Move(this.contents, { mode: 'absolute', x: (-(idx*el.getWidth())+this.offset), duration: 1, transition:Effect.Transitions.EaseFromTo });
			}.bind(this));
		}.bind(this));
		
		if (options.next) 
			options.next.observe('click', this.next.bind(this));
		
		if (options.prev)
			options.prev.observe('click', this.prev.bind(this));
		this.go(0);
	},
	go : function(idx){
		//this.contents.select('.step')[this.current || 0].fire('slide:go');
		if (this.current == idx) return;
		document.fire('slide:go');

		if (idx < 0 || idx >= this.slideCount) return;
		this.current = idx;
		
		if (this.moving) this.moving.cancel();
	
		this.moving = new Effect.Move(this.contents, {mode: 'absolute', x:(-(idx*this.width)+this.offset), duration: 1, transition:Effect.Transitions.EaseFromTo, afterFinish: function(){
    		if(this.current == 0)
				this.pArrow.addClassName("inactive");
			else
				this.pArrow.removeClassName("inactive");
			if(this.current==this.slideCount-1)
				this.nArrow.addClassName("inactive");
			else
				this.nArrow.removeClassName("inactive");
		}.bind(this)});

	},
	next : function(ev){
		ev.stop();
		this.go(this.current+1);
	},
	prev : function(ev){
		ev.stop();
		this.go(this.current-1);
	}
});

var MultiPager = Class.create(PageSlide, {
	next : function(ev){
        ev.stop();
        this.go(Math.min(this.slideCount, this.current+3));
    },
    prev : function(ev){
        ev.stop();
        this.go(Math.max(0, this.current-3));
    }
});

Effect.Transitions.EaseFromTo = function(pos) {
    if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
    return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);   
}; 

/* ProcessAnimator
----------------------------------------------------------------------------------------*/
var ProcessAnimator = Class.create({
	initialize: function(slide) {
		this.slide = slide;
		this.slide_photo = this.slide.down('img');
		this.slide_copy = this.slide.down('.step_info');
		this.close_btn = this.slide_copy.down('.close');
		this.setup();
	},
	setup: function() {
		this.slide.observe('mouseenter', this.highlight.bind(this));
		this.slide.observe('mouseleave', this.dehighlight.bind(this));
		this.slide.observe('click', this.open.bind(this));
		this.close_btn.observe('click', this.close.bind(this));
		this.bound_close = this.close.bind(this);
	},
	highlight: function(ev) {
		ev.stop();
		if (ProcessAnimator.is_open) return;
		this.slide.addClassName("active");
		this.slide.down('.details').appear({duration: .4});
	},
	dehighlight: function(ev) {
		ev.stop();
		if (ProcessAnimator.is_open) return;
		this.slide.removeClassName("active");
		this.slide.down('.details').fade({duration: .4});
	},
	open: function(ev) {
		ev.stop();
        //if (this == ProcessAnimator.active) return;
		this.slide.addClassName("active");
		this.slide_copy.appear({duration: 1.0});
		this.slide.down('.details').fade({duration: .4});
		ProcessAnimator.is_open = true;
		//ProcessAnimator.active = this;
		document.observe('slide:go', this.bound_close);
	},
	close: function(ev) {
		if(ev) ev.stop();
		ProcessAnimator.is_open = false;
		document.stopObserving('slide:go', this.bound_close);
		this.slide_copy.fade({duration: .4});
		this.slide.removeClassName("active");
	}
});

ProcessAnimator.is_open = false;
ProcessAnimator.active = null;

/* EqualHeight
----------------------------------------------------------------------------------------*/
var EqualHeight = Class.create({
	initialize: function(col1, col2) {
		this.col1 = col1;
		this.col2 = col2;
		
		if(this.col1.getHeight() > this.col2.getHeight()) {
			this.col2.style.height = this.col1.getHeight() + "px";
			this.col2.style.minHeight = this.col1.getHeight() + "px";
		}
		else {
			this.col1.style.height = this.col2.getHeight() + "px";
			this.col1.style.minHeight = this.col2.getHeight() + "px";
		}
	}
});

/* ExternalLink
----------------------------------------------------------------------------------------*/
var ExternalLink = Class.create({
	initialize: function(selector) {
		this.selector = selector;
		this.setup();
	},
	setup: function() {
		if(this.selector.getAttribute("href") && this.selector.getAttribute("rel") == "external")
			this.selector.observe('click', this.open_window.bind(this));
	},
	open_window: function(ev) {
		window.open(this.selector.href);
		ev.stop();
	}
});


/* Prompt
----------------------------------------------------------------------------------------*/
var Prompt = Class.create({
	initialize: function(field) {
		this.field = $(field);
		this.setup();
	},
	setup: function() {
		this.field.observe('focus', this.focus.bind(this));
		this.field.observe('blur', this.blur.bind(this));
		this.field.setAttribute('autocomplete', 'off');
	},
	focus: function() {
		if (this.field.value == this.field.defaultValue) {
			this.field.value = '';
			this.field.addClassName('active');
		}
	},
	blur: function() {
		if (this.field.value == '') {
			this.field.value = this.field.defaultValue;
			this.field.removeClassName('active')
		}
	}
});


function getParam(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function setMailChimpCookies() {
  var mc_cid = getParam('mc_cid');
  var mc_eid = getParam('mc_eid');
  if(mc_cid != '') {
    setCookie('_mail_chimp_campaign_id', mc_cid, 30, '/', window.location.hostname, false);
  }
  if(mc_eid != '') {
    setCookie('_mail_chimp_email_id', mc_eid, 30, '/', window.location.hostname, false);
  }
};

document.observe('dom:loaded', function(){
  $$('a').each(function(el) { new ExternalLink(el); });
  $$("input.prompt").each(function(el) { new Prompt(el); });
	try {
	  document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}

  setMailChimpCookies();
});
