/* 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";
}

/* 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;
	}
};

/* 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.togglers.each(function(el, i) {
			if (i == this.active) {
				this.togglers[i].addClassName('active');
				this.tabs[i].addClassName('active');
			} else {
				this.togglers[i].removeClassName('active');
				this.tabs[i].removeClassName('active');
			}
			
			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));
	}
});

/* 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: 0.2 }); 
		ev.stop();
	}
});

/* HoverDelay
----------------------------------------------------------------------------------------*/
var HoverDelay = Class.create({
	initialize : function(trigger, options){
		this.options = Object.extend({closeSelector : '.close', enterCb : function(){},	leaveCb : function(){},	delay : 0.5}, options || {});
		this.trigger = $(trigger);
		this.timeout = null; 
		this.active = false;
		this.setup();
		this.homeSlide = $('home_slide');
		this.modules = $('modules');
	},
	setup : function(){
		var eEvt = this.open.bindAsEventListener(this);
		var lEvt = this.close.bindAsEventListener(this);
		this.trigger.observe('click', function(event) { 
			if (event.element().hasClassName('trigger')) {
				event.stop();
			}
		}.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;
			if (this.homeSlide && this.modules){
				this.homeSlide.style.zIndex = '1';
				this.modules.style.zIndex = '99';
			}
			this.trigger.removeClassName("active");
		}
	}
});

/* PopUp
----------------------------------------------------------------------------------------*/
var PopUp = Class.create({
	initialize : function(trigger, pop, options){
		this.trigger = trigger;
		this.pop = $(pop);
		
		this.options = Object.extend({
			modal:  false,
			centered: false,
			fade: false,
			cancel: false,
			closeSelector:  '.close',
			handleSelector: '.overlay_head'
		}, options || {});
		
		PopUp.i = 0;
		PopUp.open = false;		
		
		this.setup();
	},
	setup : function(){
		this.pop.hide();
		this.pop.style.zIndex = 101;
		this.trigger.observe('click', this.open.bindAsEventListener(this));
	},
	open : function(ev){
		if (ev) ev.stop();

		this.trigger.addClassName("active");
		
		// close button(s)
		this.pop.select(this.options.closeSelector).each(function(el){
			el.observe('click', this.close.bind(this));
		}.bind(this));
		
		// draggable handle
		this.pop.select(this.options.handleSelector).each(function(el){
			this.draggable = new Draggable(this.pop, { handle: this.handle, starteffect: false, endeffect: false });
		}.bind(this));
		
		// close pop if user clicks anywhere in document
		this.close_listener = this.close.bindAsEventListener(this);
		Event.observe(document, 'click', this.close_listener);
		document.observe('pop:close',  this.close_listener);
		
		this.pop.observe('mouseenter', function() {
			Event.stopObserving(document, 'click', this.close_listener); 
		}.bind(this));

		this.pop.observe('mouseleave', function() {
			Event.observe(document, 'click', this.close_listener); 
		}.bind(this));
		
		// modal version
		if(this.options.modal)
			this.initModalWindow('modal_overlay');
		
		// centered version
		if(this.options.centered)
			this.center();

		// fade
		if(this.options.fade)
			this.pop.appear({duration: .2});
		// else just show
		else
			this.pop.show();
		
		// allow only one popup opened at a time
		if (PopUp.open) { PopUp.open.close(false); }
		PopUp.open = this;
		
		(this.options.onOpen || Prototype.emptyFunction)();
		
		if (typeof(event) == 'object') { event.stop(); }
	},
	close : function(ev){
		if (ev) ev.stop();
		PopUp.open = false;

		this.trigger.removeClassName("active");
		if(this.options.modal)
			$('modal_overlay').hide();
		if(this.options.fade)
			this.pop.fade({duration:.2});

		else
			this.pop.hide();
			
		Event.stopObserving(document, 'click', this.close_listener);
		document.stopObserving('pop:close',  this.close_listener);
		this.pop.stopObserving('mouseenter');
		this.pop.stopObserving('mouseleave');
		
		(this.options.onClose || Prototype.emptyFunction)();
		if(event) event.stop();
	},
	initModalWindow: function(el) {
		$(el).setStyle({
			height: $$('body').first().getHeight() + "px",
			zIndex: 100
		});
		$(el).show();
	},
	center: function() {
		if (this.hasBeenCentered) { return; }
		var w, h, pw, ph;
		w = this.pop.offsetWidth;
		h = this.pop.offsetHeight;
		Position.prepare();
		var ws = this.get_window_size();
		pw = ws[0];
		ph = ws[1];
		this.pop.setStyle({
			top: Math.round(Position.deltaY + 130) + 'px',
			left: Math.round((pw/2) - (w/2) -  Position.deltaX) + "px"
		});
		this.hasBeenCentered = true;
	},
	get_window_size: 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];
	}
});

/* 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')
		}
	}
});

/* PromptHighlighter
----------------------------------------------------------------------------------------*/
var PromptHighlighter = 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));
	},
	focus: function() {
		if (this.field.value == this.field.defaultValue) {
			this.field.value = '';
		}
		this.field.addClassName('highlighted');
	},
	blur: function() {
		if (this.field.value == '') {
			this.field.value = this.field.defaultValue;
		}
		this.field.removeClassName('highlighted')
	}
});

/* MegaSlide
----------------------------------------------------------------------------------------*/
var MegaSlide = Class.create({
	initialize: function(togglers, content) {
		this.togglers = $(togglers);
		this.content = content;
		
		if(this.content)
			this.setup();
	},
	setup: function() {
		this.togglers.each(function(el) {
			el.observe('click', this.slider.bind(this));
		}.bind(this));
	},
	slider: function(ev) {
		Effect.toggle(this.content, 'slide', { duration: 0.2 }); 
		ev.stop();
	}
});

/* Navigation
----------------------------------------------------------------------------------------*/
var Navigation = Class.create({
	initialize: function(container) {
		this.container = $(container);
		this.togglers = this.container.select('li.toggle');
		this.menus = this.container.select('.menu');
		
		this.setup();
	},
	setup: function(){
		this.togglers.each(function(el, i) {
			new HoverDelay(el,{
				delay   : 0.4,
				enterCb: this.show.bindAsEventListener(this, i),
				leaveCb: this.hide.bindAsEventListener(this, i)
			});
		}.bind(this));
	},
	show: function(ev, i) {
		this.menus[i].show();
		if(ev) ev.stop();
	},
	hide: function(ev, i) {
		this.menus[i].hide();
		//if(ev) ev.stop();
	}
});

/*----------------------------------------------------------------------------------------*/

Validation.add('required-prompt', 'This field is required.', function (value, field) {
    if(value == $(field).defaultValue){
        return false;
    }
     return !Validation.get('IsEmpty').test(value)
});

Validation.add('required-phone', 'Please enter your phone number.', function (value, field) {
    return field.form.phone1.value && field.form.phone2.value && field.form.phone3.value
});

function addValidation(id, notAutomatic){
    onSubmit = !notAutomatic;
    return new Validation(id, {
    		onElementValidate: function(success, element){
    			if(success)
    				$(element).removeClassName('validation-failed');
    			else
    				$(element).addClassName('validation-failed');
    		},
    		'onSubmit' : onSubmit
    	});
}

var bigDropValidate;
document.observe('dom:loaded', function(){	
	try {
	  document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}

	new Navigation('nav');
	
	if($('bigDrop')) {
		new MegaSlide($$('.megaToggle'), $('bigDrop'));
		$$("#bigDrop input.prompt").each(function(el) { new PromptHighlighter(el); })
		bigDropValidate = addValidation('bigDropForm');
	}
	
	if($('faqs')) {
		$$('#faqs li').each(function(el) {
			new SimpleToggler(el.down('.faqTrigger'), el.down('.faqContent'));
		});
	}
	if($('form_login')) {
		$$("#form_login input.prompt").each(function(el) { new PromptHighlighter(el); })
	}
});

function submitBigDrop(){
    if(!bigDropValidate.validate())
        return false;
	new Ajax.Request('/contact', {
	  parameters: $('bigDropForm').serialize(true),
	  onComplete: function(transport){
	      if(transport.request.success()){
		      var json = transport.responseText.evalJSON();
  	 		  if(json.success){ // valid form data
    				$('bigDrop_ajaxStatus').update("");
    				$('bigDrop').addClassName("thanks");
    				$('bigDropForm').hide();
    				mboxDefine("undefined_placeholder","contactSubmitted");
    				mboxUpdate('contactSubmitted');
    			}else{
    			  $('bigDrop_ajaxStatus').update(json.error_message);
    			}
		    }else{
  		    $('bigDrop_ajaxStatus').update("Error.  Please try again.");
  		  }
	   },
			'onException': function(request, except){
				//$('bigDrop_ajaxStatus').update("Error contacting server -- please try again.");
			}
	  });
	$('bigDrop_ajaxStatus').update("Please wait ...")
	return false;  // don't submit manually
}