// Init
var webroot = '/'; // Change this if the server moves
var theme = 'spring2010/'; // Change this if we're using a custom theme (name of the theme images folder); needs trailing slash

var backgrounds = new Array('background_banner.png'); // To add backgrounds just add them to this array; CURRENTLY DISABLED BECAUSE IT'S NOT IN USE
var loadedPages = new Hash(); // Used to store references to all the divs the user loads
var visiblePages = new Array(); // Stores references to all visible pages so we can close them all out
var loading = false; // tracks if we're actively loading the next page
var loadingAnim; // Tracks periodical for showing the loading animation
var offstage = -679; // location of offstage elements; 2 pixels larger than width to accomodate floating window
var ff2 = window.navigator.userAgent; // Have to sniff for FF 2 Mac thanks to scrollbar bugs with lightbox
ff2 = (ff2.indexOf('Firefox') > 0 && ff2.indexOf('2.0.') > 0) ? true : false;
	
// Handler functions for sliding window
// Main handler
function display(id, url, addendum, parent) {
	if (loadedPages.has(id)) {
		// We've already loaded this element, so just show it
		loading = true;
		var nextPage = loadedPages.get(id).setStyle('right', offstage).inject(parent, 'bottom');
		if (nextPage.getElement('.root').get('id').indexOf('store') >= 0) {
			setCookie('ajax_last', url);
		}
		swipeRight(nextPage);
	} else {
		// Load the element and display
		var nextPage = new Element('div',{
			'styles': {
				'width': 677,
				'position': 'absolute',
				'right': offstage
			},
			'class': 'floater'
		}).inject(parent);
		loading = true;
		new Request.HTML({
			'onComplete': function(tree, el, html, js) {
				nextPage.set('html', html);
				initScrollbars($(document.body));
			}
		}).get(url + addendum).chain(function() {
			// Set up the close button if it exists
			if (nextPage.getElement('.close-btn')) {
				nextPage.getElement('.close-btn').addEvent('click', function(e) {
					e.stop();
					swipeLeft(nextPage);
					if (nextPage.getElement('.root').hasClass('store')) {
						// Only unmask if it's the store, not the promo
						unmaskNav('disabled');
					}
				});
			}
			// Enable anything that requires Javascript
			enableJS(nextPage);
			// Add to hash so we don't have to fetch this page again
			loadedPages.set(id, nextPage);
			swipeRight(nextPage);
			// If it's a store that was grabbed, set the ajax_last in case we visit a promo
			if (nextPage.getElement('.root').get('id').indexOf('store') >= 0) {
				setCookie('ajax_last', url);
			}
		});
	}
	// Track which pages are visible
	visiblePages.push(id);
}

// Animate the page
function swipeRight(el) {
	new Fx.Tween(el, {'duration': 1000}).start('right', 0).chain(function() {
		loading = false;
	});
}

function swipeLeft(el) {
	new Fx.Tween(el, {'duration': 1000}).start('right', offstage);
}

// Animate the loading element for lists
function runLoadAnim(el) {
	resetActiveNav();
	(function() {
		el.addClass('active');
	}).delay(550);
	el.setStyle('background', 'url(' + webroot + 'images/common/' + theme + 'list-active.png) no-repeat -255px 0px');
	new Fx.Tween(el, {'duration': 750}).start('background-position', '0px 0px').chain(function() {
		(function() {
			if (loading) {
				el.setStyle('background-image', 'url(' + webroot + 'images/common/' + theme + 'list-loading.gif)');
				loadingAnim = checkLoadAnim.periodical(100, el);
			}
		}).delay(800);
	});
}

function resetActiveNav() {
	// Remove the active state for any other items
	$$('#list a, .nested-nav ul a').each(function(el) {
		el.removeClass('active').setStyle('background', '');
	});
}

function checkLoadAnim() {
	if (!loading) {
		this.setStyle('background-image', 'url(' + webroot + 'images/common/' + theme + 'list-active.png)');
		loadingAnim = $clear(loadingAnim);
	}
}

// Mask the non-active navigation (applies only to directory page)
// Accepts an object to set the active state on, or a classname (all of which will be active)
function maskNav(active) {
	if (typeof(active) == 'object') {
		// Disable all elements that aren't the active element
		$$('.column a').each(function(el) {
			if (el == active) {
				el.addClass('active');
			} else {
				el.addClass('disabled');
			}
		});
	} else {
		// Disable all the elements that don't have the active filter class
		$$('.column a').each(function(el) {
			if (!el.hasClass(active)) {
				el.addClass('filtered');
			}
		});
	}
}

// Remove masking for the passed in class
function unmaskNav(removal) {
	$$('.column a').each(function(el) {
		if (el.hasClass(removal)) {
			el.removeClass(removal);
		} else if (removal == 'disabled' && el.hasClass('active')) {
			el.removeClass('active');
		}
	});
}

// Common cookie setting
function setCookie(name, value) {
	Cookie.write(name, value, {'path': webroot});
}

// Enable Javascript-specific resources
function enableJS(parent) {
	if ($type(parent)) {
		$(parent).getElements('.req-js').setStyle('display', 'block');
		$(parent).getElements('.req-js-inline').setStyle('display', 'inline');
	} else {
		$$('.req-js').setStyle('display', 'block');
		$$('.req-js-inline').setStyle('display', 'inline');
	}
}


// Let's work the magic!
window.addEvent('domready', function() {		
	// If we're on the homepage, choose a background to display; otherwise set the background if there's a cookie
	// Disabled because Coakley is currently not taking advantage of it
	/*if ($('homepage')) {
		setCookie('page_bg', backgrounds[Math.floor(Math.random()*backgrounds.length)]);
	}
	if (Cookie.read('page_bg')) {
		var page_bg = 'url(' + webroot + 'images/common/' + Cookie.read('page_bg') + ')';
		$('page').setStyle('background-image', page_bg);
		$('wrapper').setStyle('background-image', page_bg);
	}*/
	
	// Set up the requisite resources for the lightbox
	var overlay = new Element('div', {
		'id': 'lightbox-overlay',
		'styles': {
			'opacity': 0
		}
	}).inject('page');
	var overlayIn = new Fx.Tween($('lightbox-overlay'));
	function lightboxIn() {
		// Do this every time in case they resize the window
		$('lightbox-overlay').setStyles({
			'width': window.getScrollSize().x + 'px',
			'height': window.getScrollSize().y + 'px'
		});
		$('lightbox').setStyle('left', ((window.getScrollSize().x/2) - 375) + 'px');
		if(ff2) {
			new IFrame({
				'id': 'ff-scrollfix',
				'styles': {
					'width': window.getScrollSize().x + 'px',
					'height': window.getScrollSize().y + 'px'
				}
			}).inject('page');
		}
		overlayIn.start('opacity', .6).chain(function() {
			$('lightbox').setStyle('display', 'block');
		});
	}
	// Set up the Store Map lightbox links
	$$('a.lightbox').each(function(el) {
		el.addEvent('click', function(e) {
			e.stop();
			if (!$('lightbox')) {
				var lightbox = new Element('div', {
					'id': 'lightbox'
				}).inject('page');
				new Request.HTML({'update': lightbox}).get(this.href + 'inline/').chain(function() {
					lightbox.getElement('.close-btn').addEvent('click', function(e) {
						e.stop();
						$('lightbox').setStyle('display', 'none');
						overlayIn.start('opacity', 0).chain(function() {
							if (ff2) {
								$('ff-scrollfix').destroy();
							}	
						});
					});
					lightboxIn();
				});
			} else {
				lightboxIn();
			}
		});
	});
	
	// Check to see if we need to run the navigation animation
	if (show_nav_animation) { // Variable that is set on the header, since we don't have access to segment info here
		var top_active = $('top-nav').getElement('a.active');
		var top_start = top_active.getSize().y;
		top_active.setStyle('background-position', '0 ' + top_start + 'px');
		// Set up and run the animation
		if ($('sub-nav')) {
			$('main').setStyles({
				'height': '493px',
				'overflow': 'hidden'
			});
			$('sub-nav').setStyle('top', '-' + $('sub-nav').getSize().y + 'px');
			var subnav_slide = new Fx.Tween($('sub-nav'), {'duration': 750});
			(function() { subnav_slide.start('top', '0px'); }).delay(250);
		}
		var topnav_slide = new Fx.Tween(top_active, {'duration': 750}).start('background-position', '0 0');
	} else if ($('top-nav')) {
		$('top-nav').getElement('a.active').setStyle('background-position', 'left top');
	}
	
	// Set up the handling for the default sliding Ajax panel
	if ($('list') || $('nav_cat_archive')) {
		$('right-pane').setStyles({
			'position': 'relative',
			'overflow': 'hidden',
			'height': '493px'
		});
		// List of pages exists, so implement the panel
		$$('#list a, .nested-nav ul a').each(function(el) {
			el.addEvents({
				'mouseenter': function() {
					if (!this.hasClass('active')) {
						this.setStyle('background', 'background: url(' + webroot + 'images/common/' + theme + 'list-active.png) no-repeat -255px top');
					}
				},
				'mouseleave': function() {
					if (!this.hasClass('active')) {
						this.setStyle('background', 'background: none');
					}
				},
				'click': function(e) {
					e.stop();
					if (!this.hasClass('active') && !loading) {
						runLoadAnim(this);
						display(this.get('rel'), this.get('href'), 'inline/', $('right-pane'));
					}
				}
			});
			// el.addEvent('click', function(e) {
			// 	e.stop();
			// 	if (!this.hasClass('active') && !loading) {
			// 		runLoadAnim(this);
			// 		display(this.get('rel'), this.get('href'), 'inline/', $('right-pane'));
			// 	}
			// });
		});
		// Set up the special case handling for the nested-navs
		$$('.nested-nav > li > a').each(function(el) {
			el.getParent('li').getFirst('ul').hide();
			el.addEvents({
				'click': function(e) {
					e.stop();
					this.getNext('ul').get('reveal').toggle();
				}
			});
		});
	}
	
	// Set up handling for the windowed panel
	if ($('directory-listing')) {
		// If we're on an individual store page, then we need to set up the close button
		var curPage = $('directory-listing').getElement('.floater');
		if (curPage) {
			curPage.getElement('.close-btn').addEvent('click', function(e) {
				e.stop();
				swipeLeft(curPage);
				unmaskNav('disabled');
			});
			var curId = curPage.getElement('.root').get('id');
			loadedPages.set(curId, curPage);
			visiblePages.push(curId);
		}
		$$('ul.column a').each(function(el) {
			el.addEvent('click', function(e) {
				e.stop();
				if (!this.hasClass('active') && !loading && !this.hasClass('disabled') && !this.hasClass('filtered')) {
					maskNav(this);
					display(this.get('rel'), this.get('href'), 'windowed/', $('directory-listing'));
				}
			});
			// If on a store page, we have to populate the cookie to make sure the promo link works again
			if (curPage && el.hasClass('active')) {
				setCookie('ajax_last', el.get('href'));
			}
		});
		// Set up the filters
		$$('#filters a').each(function(el){
			el.addEvent('click', function(e) {
				if ( this.get('rel') != 'link'){
					e.stop();
					if (!loading) {
						if (visiblePages.length) {
							// Some pages are already showing, clear them out
							visiblePages.each(function(id) {
								swipeLeft(loadedPages.get(id));
							});
							visiblePages.empty();
							unmaskNav('disabled');
						}
						if (this.get('rel') == 'reset') {
							unmaskNav('filtered');
						} else {
							unmaskNav('filtered');
							maskNav(this.get('rel'));
						}
						$$('#filters a').removeClass('active');
						this.addClass('active');
					}
				}
			});
		});
	}
	
	// Set up the counters, if any
	$$('.countdown').each(function(el) {
		new MooCountdown({
			element: el,
			leadingZeroes: true
		}).start();
	});
	
	// Set up the weather widget if it's there
	if ($('rainy-day')) {
		var staticWeatherWidget = false;
		var weatherWidgetTimer = null;
		var wrapper = $('rainy-day').getElement('.wrapper');
		wrapper.addClass('closed');
		wrapper.addEvents({
			mouseenter: function(e) {
				weatherWidgetTimer = $clear(weatherWidgetTimer);
				if (this.hasClass('closed')) {
					weatherWidgetTimer = function(){ this.removeClass('closed'); }.delay(150, this);
				}
			},
			mouseleave: function(e) {
				weatherWidgetTimer = $clear(weatherWidgetTimer);
				if (!this.hasClass('closed')) {
					weatherWidgetTimer = function(){ this.addClass('closed'); }.delay(250, this);
				}
			},
			click: function(e) {
				e.stop();
				location.href = this.getElement('.more a').get('href');
			}
		});
	}
	
	// Set up any rotating promos
	var promo_wait = 3000;
	function rotate_promo(parent) {
		var target = parent.getElement('.promo:last-child');
		target.get('tween', {
			property: 'opacity',
			onComplete: function() {
				parent.grab(target, 'top');
				target.get('tween').set(1);
				// Rotate with a variance of 0 - 2000 ms
				rotate_promo.delay(promo_wait + (100 * Math.floor(Math.random()*21)), this, parent);
			}
		}).start(0);
	}
	$$('.rotating-promo').each(function(el){
		if (el.getElements('.promo').length > 1) {
			// Rotate with a variance of 0 - 2000 ms
			rotate_promo.delay(promo_wait + (100 * Math.floor(Math.random()*21)), this, el);
		}
	});
	
	// For the bridal page, setup the datepicker
	if ($('bridal-registration')) {
		new DatePicker('.dateinput', {
			format: 'F j, Y',
			inputOutputFormat: 'F j, Y',
			dayShort: 1,
			animationDuration: 1,
			positionOffset: {x: -6, y: 2},
			startDay: 0,
			allowEmpty: true
		});
	}
	
	// Blog comment setup
	$$('.comments_toggle').each(function(el) {
		var href = el.get('href');
		href = href.substr(href.lastIndexOf('#') + 1);
		$(href).set('slide').slide('hide');
		//Togles the comment-box in and out
		el.addEvent('click', function(e){
			e.stop();
			$(href).slide('toggle');
		});
	});
	
	// Set up the cookie so that we can track back to a store from a promo
	setCookie('ajax_last', '');
	
	enableJS();
});