var Nav = Class.create();
Nav.prototype = {
	initialize: function(container) {
		this.container = $('nav');
		this.togglers  = this.container.childElements('li');
		this.tabs      = this.container.childElements('div.callout');
		this.setup();
	},
	setup: function() {
		this.togglers.each(function(el, i) {
			if (el.down('a.tab')) {
				Event.observe(el, 'mouseenter', this.open.bindAsEventListener(this, i));
				Event.observe(el, 'mouseleave', this.hide.bindAsEventListener(this, i));
			}
		}.bind(this));
	},
	open: function(event, i) {
		this.timeout = setTimeout(this.show.bind(this,i), 100);
		Event.stop(event);
	},
	show: function(i) {
		this.load(this.togglers[i]);
		this.togglers[i].className = 'active';
		clearTimeout(this.timeout);

	},
	hide: function(event, i) {
		if (this.timeout) {
			clearTimeout(this.timeout);
		}
		this.togglers[i].className = '';
		Event.stop(event);
	},
	load: function(tab) {
		var target = tab.down('div.progress');
		if (!target) return;

		switch(tab.id) {
			case 'account' :
				new Ajax.Updater(target, '/envelopes/control/myAccountTab?x='+(new Date().getTime()),
					{ method: 'get', onComplete:Element.removeClassName(target, 'progress') });
				break;
			case 'reorder' :
				new Ajax.Updater(target, '/envelopes/control/reorderCenterTab?x='+(new Date().getTime()),
					{ method: 'get', onComplete:Element.removeClassName(target, 'progress') });
				break;
		}
	}
};

/*--------------------------------------------------------------------------*/

var Tabs = Class.create();
Tabs.prototype = {
	initialize: function(container, active, options) {
		this.container = $(container);
		this.togglers  = this.container.getElementsBySelector('ul.togglers li');
		this.tabs      = this.container.getElementsBySelector('div.tab');
		this.active    = active || 0;
		this.options   = Object.extend({
							eventCat: '',
							clickCallback: ''
							},options || {});

		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');
					}

					if (this.options.eventCat) {
						var label = el.down('a') || el.down('div');
						GoogleAnalytics.trackEvent(this.options.eventCat, 'Tab', label.innerHTML);
					}

					(this.options.clickCallback || Prototype.emptyFunction)(i);
				}
				this.active = i;
				return false;
			}.bind(this);
		}.bind(this));
	}
};

/*--------------------------------------------------------------------------*/

var MiniCart = Class.create();
MiniCart.prototype = {
	initialize: function() {
		this.container = $('miniCart');
		this.checkout  = this.container.down('span.checkout');
		this.total     = this.container.down('span.total');
		this.setup();
	},
	setup: function() {
		var sessionId    = Cookie.get('JSESSIONID');
		var shoppingCart = Cookie.get('ShoppingCart');
		if (shoppingCart) {
			var matches = shoppingCart.match(/^QTY:([^|]+)\|TOTAL:([^|]+)\|JSESSIONID:([^|]+)$/);
			if (!sessionId || (sessionId != matches[3])) {
				Cookie.erase('ShoppingCart');
			} else if (matches[1] > 0) {
				this.total.innerHTML    = '(' + Format.dollar(matches[2]) + ')';
				this.checkout.innerHTML = '<a href="/envelopes/control/checkout">Checkout</a>';
			} else {
				this.total.innerHTML    = '';
				this.checkout.innerHTML = 'Checkout';
			}
		}
	}
};

/*--------------------------------------------------------------------------*/

// 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;
	w = element.offsetWidth;
	h = element.offsetHeight;
	Position.prepare();
	if (!parent) {
		var ws = Position.GetWindowSize();
		pw = ws[0];
		ph = ws[1];
	} else {
		pw = parent.offsetWidth;
		ph = parent.offsetHeight;
	}
	element.style.top = Math.round(Position.deltaY + 130) + 'px';
	element.style.left = Math.round((pw/2) - (w/2) -  Position.deltaX) + "px";
};

/*--------------------------------------------------------------------------*/

var PopUp = Class.create();
PopUp.i = 0;
PopUp.prototype = {
	initialize: function(trigger, popup) {
		PopUp.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.toTop();
		Position.Center(this.popup, $('container'));

		this.closebtn  = this.popup.getElementsBySelector('.close').first();
		this.handle    = this.popup.getElementsBySelector('.tbar').first();
		this.draggable = new Draggable(this.popup, {handle: this.handle, starteffect: false, endeffect: false });

		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);

		if (PopUp.open) { PopUp.open.closeInternal(false); }
		PopUp.open = this;

		(this.options.onOpen || Prototype.emptyFunction)();
		(this.options.trackEvent || Prototype.emptyFunction)();
	},
	closeInternal: function(event) {
		if (this.falseAlarm) {
			this.falseAlarm = false;
			return;
		}

		PopUp.open = false;
		this.popup.hide();

		this.draggable.destroy();

		Event.stopObserving(document, 'click', this.closeListener);
		Event.stopObserving(this.closebtn, 'click', this.closeListener);
		Event.stop(event);

		(this.options.onClose || Prototype.emptyFunction)();
	},
	toTop: function() {
		PopUp.i = PopUp.i + 1;
		this.popup.style.zIndex = PopUp.i + 1000;
		this.popup.show();
	}
};

/*--------------------------------------------------------------------------*/

var ForgotPassword = Class.create();
Object.extend(Object.extend(ForgotPassword.prototype, PopUp.prototype), {
	initialize: function(trigger, popup) {
		this.trigger = trigger;
		this.popup   = $(popup);
		this.options = {
			onOpen: this.open.bind(this)
		};
		this.start();
	},
	open: function() {
		this.popup.removeClassName('successful');
		this.popup.removeClassName('failure');
		this.form = this.popup.getElementsBySelector('form').first();
		this.validation = new Validation(this.form);
		this.validation.reset();
		if (this.setup_complete) return;
		this.setup_complete = true;
		Event.observe(this.form, 'submit', function(event) {
			if(this.validation.validate()){
				var myAjax = new Ajax.Request('/envelopes/control/forgotpassword',
					{ method: 'post', parameters: Form.serialize(this.form), onComplete: this.showResponse.bind(this) });
			}
			Event.stop(event);
		}.bind(this));
	},
	showResponse: function(request) {
		if (request.responseText) {
			var response = request.responseText.evalJSON();
			var status = response.message;
			if(status=='undefined' || status==null){
				status = response.status;
			}
			if (status == 'SUCCESS') {
				this.popup.addClassName('successful');
			} else {
				this.popup.addClassName('failure');
			}
		}
	}
});

/*--------------------------------------------------------------------------*/

var Subscriber = Class.create();
Object.extend(Object.extend(Subscriber.prototype, ForgotPassword.prototype), {
	open: function() {
		this.popup.removeClassName('successful');
		this.popup.removeClassName('failure');
		this.form = this.popup.getElementsBySelector('form').first();
		this.validation = new Validation(this.form);
		this.validation.reset();
		if (this.setup_complete) return;
		this.setup_complete = true;
		Event.observe(this.form, 'submit', function(event) {
			if(this.validation.validate()){
				var myAjax = new Ajax.Request('/envelopes/control/newsletterSubscription',
					{ method: 'post', parameters: Form.serialize(this.form), onComplete: this._trackSubscriber.bind(this) });
			}
			Event.stop(event);
		}.bind(this));
	},
	_trackSubscriber: function(request) {
		this.showResponse(request);
		GoogleAnalytics.trackPageview('/envelopes/control/newsletterThanks');
	}
});

var ManagerSubscriber = Class.create();
Object.extend(Object.extend(ManagerSubscriber.prototype, ForgotPassword.prototype), {
	open: function() {
		this.popup.removeClassName('successful');
		this.popup.removeClassName('failure');		
		this.form = this.popup.getElementsBySelector ('form').first();		
		this.validationLogin = new Validation(this.form);		
		this.validationLogin.reset();
		if (this.setup_complete) return;
		this.setup_complete = true;		
		Event.observe(this.form, 'submit', function(event) {
			if(this.form.hasClassName('login_form')){
				if(this.validationLogin.validate()){				
					/*new Ajax.Updater('manager_content','/envelopes/control/managerLogin',
							{ method: 'post',parameters: Form.serialize(this.form), onComplete: function(response){} });*/
					new Ajax.Request('/envelopes/control/managerLogin',
							 { method: 'post',parameters: Form.serialize(this.form), onComplete: function(response){								
								$('manager_content').update(response.responseText);
								Event.observe('subscribe','submit',function(event){
								new Ajax.Request('/envelopes/control/newsletterSubscription',{method:'post',parameters:$('subscribe').serialize(),onComplete:function(request) {
									var response = request.responseText.evalJSON();
									var status = response.message;
									if(status=='undefined' || status==null){
										status = response.status;
									}
									if (status == 'SUCCESS') {										
										$('managerCallout').addClassName("successful")
										
									} else {										
										$('managerCallout').addClassName("failure")
									
									}
									GoogleAnalytics.trackPageview('/envelopes/control/newsletterThanks');
								}});
								Event.stop(event);
								});
							} 
					});
				}
			}else{					
				if(this.validationLogin.validate()){					
					var myAjax = new Ajax.Request('/envelopes/control/newsletterSubscription',
						{ method: 'post', parameters: Form.serialize(this.form), onComplete: this._trackSubscriber.bind(this) });
				}
				
				
			}
			Event.stop(event);
		}.bind(this));
	},
	_trackSubscriber: function(request) {
		this.showResponse(request);
		GoogleAnalytics.trackPageview('/envelopes/control/newsletterThanks');
	}
});

/*--------------------------------------------------------------------------*/

var Highlights = Class.create();
Highlights.prototype = {
	initialize: function(container) {
		this.container = $(container);
		this.container && this.setup();
	},
	setup: function() {
		var items = $$('.item');
		items.each(function(el) {
			Event.observe(el, 'mouseover', function() {
				Element.addClassName(el, 'active');
			});

			Event.observe(el, 'mouseout', function() {
				Element.removeClassName(el, 'active');
			});

			Event.observe(el, 'click', function() {
				var link = el.getElementsByTagName('a')[0];
				document.location.href = link.href;
			});
		});
	}
};

/*--------------------------------------------------------------------------*/

// Read and write cookies
// http://wiki.script.aculo.us/scriptaculous/show/Cookie
var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/');
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};

/*--------------------------------------------------------------------------*/

// Prototype's EventObserver fires only once when observing radio buttons
// http://dev.rubyonrails.org/ticket/7895
Form.Element.RadioEventObserver = Class.create();
Form.Element.RadioEventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
	initialize: function(form, name, callback) {
		this.elements = [];

		myElements = Form.getElements(form);
		for (var i = 0; i < myElements.length; i++) {
			if ((myElements[i].type == 'radio') && (myElements[i].name == name)) {
				this.elements.push(myElements[i]);
			}
		}

		this.callback = callback;
		this.lastValue = this.getValue();
		for (var i = 0; i < this.elements.length; i++) {
			this.registerCallback(this.elements[i]);
		}
	},

	getValue: function() {
		for (var i = 0; i < this.elements.length; i++) {
			var value = Form.Element.getValue(this.elements[i]);
			if (value) {
				return value;
			}
		}
	},

	onElementEvent: function() {
		var value = this.getValue();
		if (this.lastValue != value) {
			for (var i = 0; i < this.elements.length; i++) {
				if (Form.Element.getValue(this.elements[i])) {
 					this.callback(this.elements[i], value);
				}
			}
			this.lastValue = value;
		}
	}
});

/*--------------------------------------------------------------------------*/

// Scroll to an element inside an overflow:auto container.
// http://elia.wordpress.com/2007/01/18/overflow-smooth-scroll-with-scriptaculous/
Effect.MoveTo = Class.create();
Object.extend(Object.extend(Effect.MoveTo.prototype, Effect.Base.prototype), {
	initialize: function(element) {
		this.element = $(element);
		var options = Object.extend({
			x: 0,
			y: 0,
			to_element: null,
			mode: 'absolute'
		} , arguments[1] || {} );
		this.start(options);
	},
	setup: function() {
		if (this.options.continuous && !this.element._ext ) {
			this.element.cleanWhitespace();
			this.element._ext=true;
			this.element.appendChild(this.element.firstChild);
		}
		this.originalLeft=this.element.scrollLeft;
		this.originalTop=this.element.scrollTop;
		if (this.options.to_element) {
			toElement=$(this.options.to_element);
			container_dims=this.element.getDimensions();
			to_element_dims=toElement.getDimensions();
			Position.prepare();
			containerOffset = Position.cumulativeOffset(this.element);
			elementOffset = Position.cumulativeOffset(toElement);
			this.options.x=this.options.x+elementOffset[0]-containerOffset[0]-(container_dims.width/2 - to_element_dims.width/2);
			this.options.y=this.options.y+elementOffset[1]-containerOffset[1]-(container_dims.height/2 - to_element_dims.height/2);
		}
		if(this.options.mode == 'absolute') {
			this.options.x -= this.originalLeft;
			this.options.y -= this.originalTop;
		}
	},
	update: function(position) {
		this.element.scrollLeft = this.options.x * position + this.originalLeft;
		this.element.scrollTop = this.options.y * position + this.originalTop;
	}
});

/*--------------------------------------------------------------------------*/

Effect.Persistent = Class.create();
Effect.Persistent.prototype = {
	initialize: function(element, container) {
		this.element   = $(element);
		this.container = $(container);
		this.setup();
	},
	setup: function() {
		Event.observe(window, 'scroll', this.test.bind(this));
	},
	test: function() {
		if (this.timeout) {
			clearTimeout(this.timeout);
		} else {
			Position.prepare();
			this.startY = Position.deltaY;
		}
		this.timeout = setInterval(this.slide.bind(this), 300);
	},
	slide: function() {
		Position.prepare();
		if (this.startY == Position.deltaY) {
			clearInterval(this.timeout);
			this.timeout = null;
			this.move(Position.deltaY);
		}
		this.startY = Position.deltaY;
	},
	move: function(y) {
		Position.prepare();
		var pos       = Position.cumulativeOffset(this.element.up());
		var height    = this.element.getHeight();
		var maxHeight = this.container.getHeight();

		if (y + height > maxHeight) {
			new Effect.Move(this.element, {x:0, y: maxHeight - height - 30, mode: 'absolute'});
		} else if (y > (pos[1] - 10)) {
			new Effect.Move(this.element, {x:0, y: y - (pos[1] - 10), mode: 'absolute'});
		} else {
			new Effect.Move(this.element, {x:0, y: 0, mode: 'absolute'});
		}
	}
};

var ReorderPop = Class.create();
ReorderPop.i = 0;
ReorderPop.prototype = {
	initialize: function(trigger, popup) {
		ReorderPop.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();
		new Effect.Morph(this.popup, {
			style: 'top:197px',
			duration: 0.5,
			transition: Effect.Transitions.easeInOutQuad
		});

		this.closebtn  = document.getElementById('reorder_changes_cancel');
		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);

		if (ReorderPop.open) { ReorderPop.open.closeInternal(false); }
		ReorderPop.open = this;

		(this.options.onOpen || Prototype.emptyFunction)();
	},
	closeInternal: function(event) {
		if (this.falseAlarm) {
			this.falseAlarm = false;
			return;
		}

		ReorderPop.open = false;

		this.popup.setStyle({top: '0'});
		this.popup.hide();

		Event.stopObserving(document, 'click', this.closeListener);
		Event.stopObserving(this.closebtn, 'click', this.closeListener);
		//Event.stop(event);

		(this.options.onClose || Prototype.emptyFunction)();
	}
};

var ReorderMsg = Class.create();
ReorderMsg.prototype = {
	initialize: function() {
		this.start();
	},
	start: function () {
		// cookie test has come back positive, so this class is instantiated
		// make ajax request

		new Ajax.Updater('globalAlert', '/envelopes/control/global-message', {
			method: 'get',
			onLoading: function () {
				//this.loader.show();
			}.bind(this),
			onComplete: function (t) {
				//this.loader.hide();
				var reorder = $('global_reorder');
				var changeform = $('reorder_changes_wrap');
				var changecontent = changeform.innerHTML;

				new Insertion.Before($('header_wrap'), changecontent);

				$('globalAlert').show();

				reorder.show();

				new ReorderPop('reorder_pop_trigger', 'reorder_changes');
				this.closebtn  = reorder.getElementsBySelector('.close').first();
				this.closeListener = this.closeInternal.bindAsEventListener(this);
				Event.observe(this.closebtn, 'click', this.closeListener);

			}.bind(this),
			onFailure: function (t) {
				//this.loader.hide();
			},
			insertion: Insertion.Bottom
		});

	},
	closeInternal: function(event) {
		$('reorder_changes').remove();
		$('global_reorder').remove();
	}
};

var GlobalMessage = Class.create();
GlobalMessage.prototype = {
	initialize: function(communicationEventId, partyId) {
		this.start();
	},
	start: function () {
		// cookie test has come back
		// make an ajax request dependent on message

		new Ajax.Updater('globalAlert', '/envelopes/control/global-message?x='+(new Date().getTime()), {
			method: 'get',
			onLoading: function () {
				//this.loader.show();
			}.bind(this),
			onComplete: function (t) {
				//this.loader.hide();
				$('globalAlert').className = 'active';

				var message = $('global_message');
				if(message!=null){
					this.closebtn  = message.getElementsBySelector('.close').first();
					this.closeListener = this.closeInternal.bindAsEventListener(this);

					Event.observe(this.closebtn, 'click', this.closeListener);
				}else{
					var reorder = $('global_reorder');

					if(reorder!=null){

						reorder.show();

						this.closebtn  = reorder.getElementsBySelector('.close').first();
						this.closeListener = this.closeInternal.bindAsEventListener(this);
						Event.observe(this.closebtn, 'click', this.closeListener);

						var changeform = $('reorder_changes_wrap');
						if(changeform!=null){
							var changecontent = changeform.innerHTML;

							new Insertion.Before($('globalAlert'), changecontent);
							new ReorderPop('reorder_pop_trigger', 'reorder_changes');
						}
					}
				}

			}.bind(this),
			onFailure: function (t) {
				//this.loader.hide();
			},
			insertion: Insertion.Bottom
		});

	},
	closeInternal: function(event) {
		this.markMessageRead();
		$('globalAlert').hide();
	},
	markMessageRead: function() {
		var form = $('communicationEventForm');

		var params = {
			communicationEventId: form.communicationEventId.value,
			partyId: form.partyId.value
		}
		var myAjax = new Ajax.Updater('globalAlert', '/envelopes/control/markAsRead',
			{method: 'post', parameters: params, onComplete: function() {
				$('globalAlert').show();

				var message = $('global_message');
				if(message!=null){
					this.closebtn  = message.getElementsBySelector('.close').first();
					this.closeListener = this.closeInternal.bindAsEventListener(this);

					Event.observe(this.closebtn, 'click', this.closeListener);
				}else{

					var reorder = $('global_reorder');

					if(reorder!=null){

						reorder.show();

						this.closebtn  = reorder.getElementsBySelector('.close').first();
						this.closeListener = this.closeInternal.bindAsEventListener(this);
						Event.observe(this.closebtn, 'click', this.closeListener);

						var changeform = $('reorder_changes_wrap');
						if(changeform!=null){
							var changecontent = changeform.innerHTML;

							new Insertion.Before($('globalAlert'), changecontent);
							new ReorderPop('reorder_pop_trigger', 'reorder_changes');
						}
					}
				}
			}.bind(this)
			});
	}
};

/*--------------------------------------------------------------------------*/
var AlertMessage = Class.create();
AlertMessage.prototype = {
		initialize: function() {
			this.start();
		},
		start:function(){
			var myAjax = new Ajax.Request('/envelopes/control/alertMessage',
				{ method: 'post', onComplete: function(response){
				$('alertMessage').innerHTML = response.responseText
					if(response.responseText !="") {
						$('alertMessage').style.display = "block";
					}
				} 
			});
		}		
}

/*---------------------------------------------------------------------------*/
var Format = {
	dollar: function(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)) { num = "0"; }
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10) { cents = "0" + cents; }
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
			num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
		}
		return (((sign)?'':'-') + '$' + num + '.' + cents);
	},
	bytes: function(size) {
		var str = 'bytes';
		if (size > 1024 + 256) { size /= 1024; str = 'KB'; }
		if (size > 1024 + 256) { size /= 1024; str = 'MB'; }
		if (size > 1024 + 256) { size /= 1024; str = 'GB'; }
		if (size > 1024 + 256) { size /= 1024; str = 'TB'; }
		size = Math.round(size * 100) / 100;
		return size + ' ' + str;
	}
};

/*--------------------------------------------------------------------------*/

var GoogleAnalytics = {
	trackEvent: function(category, action, label) {
		_gaq.push(['_trackEvent', category, action, label]);
	},
	trackPageview: function(url) {
		_gaq.push(['_trackPageview', url]);
	}
}

/*--------------------------------------------------------------------------*/

// Returns the value of the selected radio button in the radio group, null if
// none are selected, and false if the button group doesn't exist
// http://aaron.xavisys.com/using-prototype-javascript-to-get-the-value-of-a-radio-group/
function $RF(el, radioGroup) {
	if($(el).type && $(el).type.toLowerCase() == 'radio') {
		radioGroup = $(el).name;
		el = $(el).form;
	} else if ($(el).tagName.toLowerCase() != 'form') {
		return false;
	}

	var checked = $(el).getInputs('radio', radioGroup).find(
		function(re) { return re.checked; }
	);

	return (checked) ? $F(checked) : null;
}


function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
	 var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
	 var aQueryString = strQueryString.split("&");
	 for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
		if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
		  var aParam = aQueryString[iParam].split("=");
		  strReturn = aParam[1];
		  break;
		}
	 }
  }
  return unescape(strReturn);
}


/*--------------------------------------------------------------------------*/

Event.onDOMReady(function(){
	new Nav('nav');

	if ($('miniCart')) {
		new MiniCart();
	}

	if($('searchBtn')){
		$('searchBtn').onclick = function(){
			$('search').submit();
		};
	}

	if($('forgotCallout')) {
		new ForgotPassword($$('a.forgot'), 'forgotCallout');
	}

	if ($('subscribeLink') && $('subscribeCallout')) {
		new Subscriber('subscribeLink', 'subscribeCallout');
	}
	
	if ($('holidayLink') && $('holidayCallout')) {
		new PopUp('holidayLink', 'holidayCallout');
	}

	if ($('holidayLinkBack') && $('holidayCallout')) {
		new PopUp('holidayLinkBack', 'holidayCallout');
	}
	
	if ($('holidayLinkMail') && $('holidayLinkMailCallout')) {
		new PopUp('holidayLinkMail', 'holidayLinkMailCallout');
	}
	if ($('holidayLinkMailOne') && $('holidayLinkMailCallout')) {
		new PopUp('holidayLinkMailOne', 'holidayLinkMailCallout');
	}

	if ($('examplesLink') && $('examplesCallout')) {
		new PopUp('examplesLink', 'examplesCallout');
	}

	if ($('examplesLink2') && $('examplesCallout2')) {
		new PopUp('examplesLink2', 'examplesCallout2');
	}

	if ($('freeShippingLink') && $('freeShippingCallout')) {
		new PopUp('freeShippingLink', 'freeShippingCallout');
	}
	
	if ($('itemList')) {
		new Highlights('itemList');
	}
	
	new Ajax.Updater('manager_content','/envelopes/control/managerCallout',
			{ method: 'post', onComplete: function(response){} });
	
	if ($('managerLink') && $('managerCallout')) {
		new ManagerSubscriber('managerLink', 'managerCallout');
	}
	
	if ($$('.show_more').length > 0) {
		$$('.show_more').each(function(el){
								
			new ShowMore($(el), "more", "less");
		});
		
	}
});

/*--------------------------------------------------------------------------*/

/**
* Ai Tablet Tracking:
* The following snippet adds Google Analytics event tracking
* to detect an iPad device and it's current orientation as
* the user browses the site. Note that at this time Ai is
* is only interested in measuring iPad performance, and not
* all tablets.
*/
Event.onDOMReady(function(){
	if (navigator.userAgent.indexOf("iPad") > -1) {
		// Returns the current orientation (Landscape or Portrait)
		function detectIPadOrientation() {
			return (Math.abs(window.orientation) == 90) ? "Landscape" : "Portrait";
		}
		
		// Save the user's current orientation
		var currentIPadOrientation = detectIPadOrientation();
		
		// Track the orientation when the page is loaded
		GoogleAnalytics.trackEvent("Tablet", "Orientation", currentIPadOrientation);
		
		// Observe the browser window to track orientation changes as a separate event
		Event.observe(window, "orientationchange", function() {
			var newIPadOrientation = detectIPadOrientation();
			if (newIPadOrientation != currentIPadOrientation) {
				var eventLabel = currentIPadOrientation + " to " + newIPadOrientation;
				GoogleAnalytics.trackEvent("Tablet", "Changed Orientation", eventLabel);
				currentIPadOrientation = newIPadOrientation;
			}
		});
		
		// Track the orientation when the user goes to checkout
		if ($('placeOrderBtn')) {
			Event.observe($("placeOrderBtn"), "click", function() {
				GoogleAnalytics.trackEvent("Tablet", "Checkout", currentIPadOrientation);
			});
		}
	}
});

/*--------------------------------------------------------------------------*/

/**
* Event.simulate(@element, eventName[, options]) -> Element
*
* - @element: element to fire event on
* - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
* - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
*
* $('foo').simulate('click'); // => fires "click" event on an element with id=foo
*
**/
Event.onDOMReady(function(){
  
  var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  }
  var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
  }
  
  Event.simulate = function(element, eventName) {
    var options = Object.extend(Object.clone(defaultOptions), arguments[2] || { });
    var oEvent, eventType = null;
    
    element = $(element);
    
    for (var name in eventMatchers) {
      if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }

    if (!eventType)
      throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');

    if (document.createEvent) {
      oEvent = document.createEvent(eventType);
      if (eventType == 'HTMLEvents') {
        oEvent.initEvent(eventName, options.bubbles, options.cancelable);
      }
      else {
        oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
      }
      element.dispatchEvent(oEvent);
    }
    else {
      options.clientX = options.pointerX;
      options.clientY = options.pointerY;
      oEvent = Object.extend(document.createEventObject(), options);
      element.fireEvent('on' + eventName, oEvent);
    }
    return element;
  }
  
  Element.addMethods({ simulate: Event.simulate });
});
/*--------------------------------------------------------------------------*/
/*Popup for coupon/email on page load*/

var PageCouponPopup = Class.create();
Object.extend(Object.extend(PageCouponPopup.prototype, PopUp.prototype), {
	initialize: function(trigger, popup) {
		this.trigger = trigger;
		this.popup   = $(popup);
		this.options = {
			onOpen: this.setup.bind(this)
		}
		this.start();
	},
	setup: function() {
		this.popup.removeClassName('successful');
		this.popup.removeClassName('failure');
		this.form = this.popup.getElementsByTagName('form')[0];
		this.validator = new Validation(this.form, {onSubmit: false});
		Event.observe(this.form, 'submit', this.validate.bindAsEventListener(this));
	},
	validate: function(event) {
		if (this.validator.validate()) {
			var myAjax = new Ajax.Request('/envelopes/control/subscribeAnon',
				{method: 'post', parameters: Form.serialize(this.form), onComplete: this.respond.bind(this)});
		}
		Event.stop(event);
	},
	respond: function(request) {
		if (request.responseText) {
			var response = request.responseText.evalJSON();
			if (response.status == 'SUCCESS') {
				this.popup.addClassName('successful');
				GoogleAnalytics.trackEvent("New Visitor", "PopUp No Coupon", "Success");
			} else {
				this.popup.addClassName('failure');
				GoogleAnalytics.trackEvent("New Visitor", "PopUp No Coupon", "Error");
			}
		}
	}
});

Event.onDOMReady(function() {
	new PageCouponPopup('callPageCoupon', 'pageCoupon');
});
/*--------------------------------------------------------------------------*/
