// Init
var webroot = '/'; // Change this if the server moves
var theme = 'fall2010/'; // 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({
			evalScripts: true,
			evalResponse: true,
			onComplete: function(tree, el, html, js) {
				nextPage.set('html', html);
				initScrollbars(nextPage);
				if (nextPage.getElement('.fb_button')) {
					nextPage.getElement('.fb_button').addEvent('click', function(e) {
						e.stop();
						var link_url = nextPage.getElement('.fb_button').get('href');
						popBrowserWindow(link_url, 600, 500);
					});
				}
				
			}
		}).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;
		updateScrollbars(el);
	});
}

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, #calendar_list a, .nested_list 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', '.events a', '.nested_list 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');
	}
}
// Lets open the Facebook button in a popup window like the original does

function popBrowserWindow(url, custom_width, custom_height){
	var popUp = new Browser.Popup(url, {
		width: 600,
		height: 400
	});
	
}

// 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();
							}
						});
						$('lightbox').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().chain(function() {
						if (!$(document.body).getElement('.scrollarea')){
							initScrollbars($(document.body));
						}
						updateScrollbars($(document.body));
					});
				}
			});
		});
	}
	
	// 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);
					// Check to see if we're filtering for Bridal Guide stores
					var active_filter = $('filters').getElement('.active');
					var href = '';
					var rel = '';
					if (active_filter) {
						if (active_filter.get('rel') == 'bridal_guide') {
							href = this.get('href').replace(/^(.*?)\/directory\/store\/(.+)$/, '$1/shopping/bridal/$2');
							rel = this.get('rel') + '-bridal';
						} else {
							href = this.get('href');
							rel = this.get('rel');
						}
					}
					display(rel, 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');
		});
	});
	
	// Initialize the custom scrollbars
	initScrollbars($(document.body));
	
	// Set up the cookie so that we can track back to a store from a promo
	setCookie('ajax_last', '');
	
	enableJS();
	
	// Handeling sliding calendar AJAX panel
	
	var calendarSlidingPane = function() {
		if ($('calendar_list')) {
			$('right-pane').setStyles({
				'position': 'relative',
				'overflow': 'hidden',
				'min-height': '493px'
			});
			// List of pages exists, so implement the panel
			$$('#calendar_list 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 (visiblePages.length) {
							// Some pages are already showing, clear them out
							visiblePages.each(function(id) {
								swipeLeft(loadedPages.get(id));
							});
							visiblePages.empty();
							unmaskNav('disabled');
						}
						if (!this.hasClass('active') && !loading) {
							runLoadAnim(this);
							display(this.get('rel'), this.get('href'), 'windowed/', $('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'));
				// 	}
				// });
			});
		}
	}
	
	
	// Initialize Calendar links
	$$('.calendarCell a', '.calendarToday a').each(function(el){
		el.addEvent('click',function(event){
			event.stop();
			url = this.getProperty('href');
			
			var itemsRequest = new Request.HTML({
				url: url,
				method: 'get',
				update: $('calendar_items'),
				onSuccess: function(responseText, responseXML) {
					calendarSlidingPane();
					updateScrollbars($(document.body));
				}
			}).send();
			$$('.calendarCell a', '.calendarToday a').each(function(ele){
				if(ele.hasClass('active')){
					ele.removeClass('active');
				}
			});
			el.addClass('active');
		});
	});
	// Handeling sliding calendar AJAX panel
	
	calendarSlidingPane();
	
	// Staff for the By Store page of the Events section
	var byStoreSlidingPane = function() {
		if ($('by_store_list')) {
			$('right-pane').setStyles({
				'position': 'relative',
				'overflow': 'hidden',
				'height': '493px'
			});
			// List of pages exists, so implement the panel
			$$('#by_store_list .nested_list 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 (visiblePages.length) {
							// Some pages are already showing, clear them out
							visiblePages.each(function(id) {
								swipeLeft(loadedPages.get(id));
							});
							visiblePages.empty();
							unmaskNav('disabled');
							
						}
						
						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'));
				// 	}
				// });
			});
		}
	}
	
	var byStoreAccordion = new Accordion($('by_store_list'), 'span.toggler', 'div.list', {
			opacity: false,
			display: -1,
			onActive: function(toggler, element){
				
				if (visiblePages.length) {
					// Some pages are already showing, clear them out
					visiblePages.each(function(id) {
						swipeLeft(loadedPages.get(id));
					});
					visiblePages.empty();
					unmaskNav('disabled');	
				}	
			},
			onBackground: function(toggler, element){
			}
		});
	byStoreSlidingPane();
	//If there is FB Share button, lets open it on a popup window
	if ($$('a.fb_button')) {
		$$('a.fb_button').each(function(element){
			element.addEvent('click', function(e) {
				e.stop();
				var link_url = element.get('href');
				popBrowserWindow(link_url, 600, 500);
			});
		});
	}
	
	
	
	
	
	/* Added by Will Drewes on May 2 */

	// Setup the homepage rotator

	if ($('home_banner')) {
		var frames = $('home_banner').getElements('.slide_nav a.frame-link');
		new TIControlledRotator(frames, $('home_banner'), {
			duration: 3.75,
			transition: Fx.Transitions.Quad.easeOut,
			fade_duration: 2.5,
			frame_class: 'slide',
			controls: {
				play_on_jump: true,
				buttons: {
					'play': $('home_banner').getElement('.play_pause_button'),
					'next': null,
					'prev': null
				}
			}
		});
	}
	
	if ($('landing_slideshow')) {
		var frames = $('landing_slideshow').getElements('.slide_nav a.frame-link');
		new TIControlledRotator(frames, $('landing_slideshow'), {
			duration: 3.75,
			transition: Fx.Transitions.Quad.easeOut,
			fade_duration: 2.5,
			frame_class: 'slide',
			controls: {
				play_on_jump: true,
				buttons: {
					'play': $('landing_slideshow').getElement('.play_pause_button'),
					'next': null,
					'prev': null
				}
			}
		});
	}


/* Added by Will Drewes on May 2 */



	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
});

// IE 6 is a bitch; force it to think again about those scrollbars
// Turns out Safari sometimes screws up, too, if there's a large image causing the scrolling
if (Browser.Engine.trident4 || Browser.Engine.webkit) {
	window.addEvent('load', function() {
		updateScrollbars($(document.body));
	});
}
