/**
 * Albertsons Homepage
 * Version 1.0.0 - 11/23/2008
 * @author Benjamin Truyman
 **/
var flag = false;
var ABS = ABS || {};

// Albertsons Homepage
ABS.Homepage = {
	initialize: function () {
		if ($('#cmm').get(0)) { ABS.Homepage.CMM.initialize(); }
		if ($('#store-details-link').get(0)) { ABS.Homepage.StoreDetails.initialize(); }
		
		if ($('#tabbed-body').get(0)) { ABS.Homepage.TabbedContent.initialize(); }
		if ($('#coupon-scroller').get(0)) { ABS.Homepage.TabbedContent.CouponScroller.initialize(); }
		if ($('#our-own-brands').get(0)) { ABS.Homepage.OOB.initialize(); }
		if ($('#tab-savings-weekly').get(0)) { ABS.Homepage.TabbedContent.WeeklyAds.initialize(); }
		if ($('#tab-savings-personal').get(0)) { ABS.Homepage.TabbedContent.PersonalizedCoupons.initialize(); }
		if ($('#tab-savings-preferred').get(0)) { ABS.Homepage.TabbedContent.PreferredSavings.initialize(); }
		if ($('#tab-meal-search').get(0)) { ABS.Homepage.TabbedContent.RecipeSearch.initialize(); }
	}
};

// Corporate Monthly Messaging
ABS.Homepage.CMM = {
	analytics: {
		category: 'Corporate Monthly Messaging'
	},
	buttons: {},
	containers: {},
	information: {
		previousSlide: null,
		currentSlide: null,
		hasLooped: false,
		isBusy: false,
		isPlaying: false
	},
	interval: null,
	messages: [],
	navigation: [],
	options: {
		duration: 1000,
		wait: 10000
	},
	
	initialize: function () {
		// Define Containers
		this.containers.main = $('#cmm').get(0);
		this.containers.viewport = $('#cmm-viewport').get(0);
		this.containers.messages = $('#cmm-messages').get(0);
		this.containers.navigation = $('#cmm-navigation').get(0);
		
		// Define Buttons
		this.buttons.playpause = $('#cmm-playpause').get(0);
		
		// Build Navigation
		this.buildNavigation();
		
		// Build Slides
		this.buildSlides();
		
		// Start Slideshow
		this.startSlideshow();
	},
	
	getMessages: function () {
		// Find all messages in message container
		return $('li', this.containers.messages).get();
	},
	
	getNavigation: function () {
		// Find all navigation elements in navigation container
		return $('li a[id!="cmm-playpause"]', this.containers.navigation).get();
	},
	
	getSlideIndexById: function (id) {
		for (var i=0; i < this.messages.length; i++) {
			if (id === this.messages[i].id) {
				return i;
			}
		};
	},
	
	buildNavigation: function () {
		var that = this;
		
		// Get all navigation elements
		this.navigation = this.getNavigation();
		
		// Set Navigation Items click handler and set first to active
		$(this.navigation).each(function(index) {
			if (index === 0) {
				$(this).addClass('active');
			}
			
			this.rel = this.hash.substr(1);
			$(this).bind('mousedown', ABS.Utils.Delegate.create(that, that.handleNavigation)).bind('click', ABS.Utils.dummyEventHandler);
		});
		
		// Set Play/Pause click handler
		$(this.buttons.playpause).bind('mousedown', ABS.Utils.Delegate.create(this, this.handlePlayPause)).bind('click', ABS.Utils.dummyEventHandler);
	},
	
	buildSlides: function () {
		// Get All Messages
		this.messages = this.getMessages();
		
		// Set initial currentSlide index
		this.information.currentSlide = this.information.previousSlide = 0;
		
		// Hide all messages except for first
		for (var i=0; i < this.messages.length; i++) {
			if(i !== 0) {
				$(this.messages[i]).hide();
			}
		}
	},
	
	startSlideshow: function () {
		// Set State
		this.information.isPlaying = true;
		
		// Set Play Button
		$(this.buttons.playpause).removeClass('play');
		$(this.buttons.playpause).addClass('pause');
		
		// Start Interval
		this.interval = setInterval(ABS.Utils.Delegate.create(this, this.nextSlide), this.options.wait);
	},
	
	stopSlideshow: function () {
		// Set State
		this.information.isPlaying = false;
		
		// Set Pause Button
		$(this.buttons.playpause).removeClass('pause');
		$(this.buttons.playpause).addClass('play');
		
		// Stop Interval
		clearInterval(this.interval);
	},
	
	goToSlide: function (index) {
		// Don't transition if current slide is the one selected or if it's currently animating
		if (index === this.information.currentSlide || this.information.isBusy) return;
		
		// Set current slide to previous
		this.information.previousSlide = this.information.currentSlide;
		this.information.currentSlide = index;
		
		// Set to busy
		this.information.isBusy = true;
		
		// Fade out current slide
		$(this.messages[this.information.previousSlide]).fadeOut({duration: this.options.duration});
		
		// Fade in next slide
		$(this.messages[index]).fadeIn(this.options.duration, function () {
			ABS.Homepage.CMM.information.isBusy = false;
		});
		
		// Set active navigation item
		for (var i=0; i < this.navigation.length; i++) {
			if (this.navigation[i].rel === this.messages[index].id) {
				$(this.navigation[i]).addClass('active');
			} else {
				$(this.navigation[i]).removeClass('active');
			}
		}
		
		// Stop slideshow on slide 1 if it has looped once
		if (this.information.hasLooped && index === 0) {
			this.stopSlideshow();
		}
	},
	
	nextSlide: function (e) {
		// Determine Next Slide
		if (this.information.currentSlide + 1 === this.messages.length) {
			this.information.hasLooped = true;
			this.goToSlide(0);
		} else {
			this.goToSlide(this.information.currentSlide + 1);
		}
		
	},
	
	handlePlayPause: function (e) {
		if(this.information.isPlaying === true) {
			// Track click event
			ABS.Helpers.Analytics.trackEvent(this.analytics.category, 'Pause');
			
			// Pause slideshow
			this.isPlaying = false;
			this.stopSlideshow();
		} else {
			// Track click event
			ABS.Helpers.Analytics.trackEvent(this.analytics.category, 'Play');
			
			// Play slideshow
			this.information.isPlaying = true;
			this.startSlideshow();
		}
	},
	
	handleNavigation: function (e) {
		// Get index and hold it temporarily
		var index = this.getSlideIndexById(e.currentTarget.rel);
		
		// Track click event
		ABS.Helpers.Analytics.trackEvent(this.analytics.category, 'Slide ' + Number(index + 1));
		
		// Go to slide by index
		this.information.hasLooped = false;
		this.stopSlideshow();
		this.goToSlide(index);
	}
};

// Store Details
ABS.Homepage.StoreDetails = {
	analytics: {
		category: 'Store Details Popup'
	},
	buttons: {},
	containers: {},
	
	initialize: function () {
		// Define buttons
		this.buttons.open = $('#store-details-link').get(0);
		
		// get the content of storedetails html from div element
		var storedetailsdataHtml = document.getElementById("hiddenStoreDetialsHtml");
		storedetailsdataHtml =  storedetailsdataHtml.textContent ? storedetailsdataHtml.textContent : storedetailsdataHtml.innerText;
		
		//if cannot connect to webservice to bring data then show error message
		if(storedetailsdataHtml.length <= 2){
			storedetailsdataHtml =  '<div id="store-details">' +
			'<a href="#" id="store-details-close"><span class="fir">Close</span></a>' +
			'<p class="address">' +
			'<br><br><br>Sorry, this function is currently unavailable. ' +
			'Please try your request later.<br />' +
			'</p>' +
			'</div>';
		}
		
		// Build popup
		this.buildPopup(storedetailsdataHtml);
		
		// More buttons
		this.buttons.close = $('#store-details-close').get(0);
		
		// Build navigation
		this.buildNavigation();
	},
	
	buildNavigation: function () {
		$(this.buttons.open).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
		$(this.buttons.close).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
	},
	
	buildPopup: function (htmlContent) {
		this.containers.main = ABS.Managers.Popup.add($(htmlContent));
		
		var container = $('#local-store-nav');
		var button = $(this.buttons.open);
		
		
		$(this.containers.main).css({
			position: 'absolute',
			top: 134,
			left: container.position().left + button.position().left + (button.width() / 2) - ($(this.containers.main).width() / 2)
		});
	},
	
	showPopup: function () {
		ABS.Homepage.StoreFinder.hidePopup();
		$(this.containers.main).fadeIn(250);
	},
	
	hidePopup: function () {
		$(this.containers.main).fadeOut(250);
	},
	
	handleNavigation: function (e) {
		if (e.currentTarget === this.buttons.open) {
			// Track click event
			ABS.Helpers.Analytics.trackEvent(this.analytics.category, 'Open');
			
			// Show popup
			this.showPopup();
		} else if (e.currentTarget === this.buttons.close) {
			// Track click event
			ABS.Helpers.Analytics.trackEvent(this.analytics.category, 'Close');
			
			// Hide popup
			this.hidePopup();
		}
	}
};

// Store Finder
ABS.Homepage.StoreFinder = {
	analytics: {
		category: 'Store Finder'
	},
	buttons: {},
	containers: {},
	inputs: {},
	validator: null,
	
	initialize: function () {
		// Define buttons
		this.buttons.open = $('#find-store-link').get(0);
		var findStoreHtml = '<div id="store-finder">' +
			'<p class="address">' +
			'<form action="#" method="post" id="store-finder-form">' +
			'<br><br><br><br><br><br><strong>Searching for stores, please wait...</strong><br/>' +
			'</form>' +
			'</p>' +
			'</div>';
		this.buildPopup(findStoreHtml);
		this.showPopup();
		//get the contents of store details by making an Ajax call.
		var findStoreDetailsHtml = findNewStore("/FindAStoreAction.do?action=findANewStore&zipCode=" + 
					document.getElementById("zipCode").value + "&unitId=" + document.getElementById("unitId").value);
		ABS.Homepage.StoreFinder.hidePopup();
		   
		//if cannot connect to webservice to bring data then show error message
		if(findStoreDetailsHtml.length <= 2){
			findStoreDetailsHtml =  '<div id="store-finder">' +
			'<a href="#" id="store-finder-close"><span class="fir">Close</span></a>' +
			'<p class="address">' +
			'<form action="#" method="post" id="store-finder-form">' +
			'<br><br><br><br><br><br>Sorry, this function is currently unavailable.<br />' +
			'Please try your request later.<br />' +
			'</form>' +
			'</p>' +
			'</div>';
		}
		
		// Build Popup
		this.buildPopup(findStoreDetailsHtml);
		
		// Define a few more buttons
		this.buttons.close = $('#store-finder-close').get(0);
		this.buttons.submit = $('#store-finder-submit').get(0);
		
		// Define containers
		this.containers.form = $('#store-finder-form').get(0);
		this.containers.error1 = $('#store-finder-error1').get(0);
		this.containers.error2 = $('#store-finder-error2').get(0);
		this.containers.error3 = $('#store-finder-error3').get(0);
		
		// Define inputs
		this.inputs.zip = $('#store-finder-zip').get(0);
		this.inputs.city = $('#store-finder-city').get(0);
		this.inputs.state = $('#store-finder-state').get(0);
		
		// Create shortcut to validator
		this.validator = ABS.Helpers.FormValidator;
		
		// Build search form
		this.buildForm();
		
		// Build navigation
		this.buildNavigation();
		
		// Build form validator
		this.buildValidator();
		ABS.Homepage.StoreFinder.showPopup();
	},
	
	buildPopup: function (htmlContent) {
		this.containers.main = ABS.Managers.Popup.add($(htmlContent));
		
		var container = $('#local-store-nav');
		var button = $(this.buttons.open);
		
		$(this.containers.main).css({
			position: 'absolute',
			top: 66,
			left: container.position().left + button.position().left + (button.width() / 2) - ($(this.containers.main).width() / 2)
		});
	},
	
	buildForm: function () {
		$(this.containers.form).submit(ABS.Utils.Delegate.create(this, this.handleSubmit));
		$(this.inputs.zip).keydown(ABS.Utils.Delegate.create(this, this.handleInput));
		$(this.inputs.city).keydown(ABS.Utils.Delegate.create(this, this.handleInput));
		$(this.inputs.state).change(ABS.Utils.Delegate.create(this, this.handleInput));
	},
	
	buildNavigation: function () {
		$(this.buttons.open).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
		$(this.buttons.close).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
	},
	
	buildValidator: function () {
		this.validator = ABS.Helpers.FormValidator({
			form: this.containers.form,
			elements: [
				{
					name: 'zip',
					options: {
						required: true,
						zip: true
					}
				},
				{
					name: 'city',
					options: {
						required: true
					}
				},
				{
					name: 'state',
					options: {
						required: true
					}
				}
			]
		});
	},
	
	showPopup: function () {
		ABS.Homepage.StoreDetails.hidePopup();
		$(this.containers.main).fadeIn(250);
	},
	
	hidePopup: function () {
		$(this.containers.main).fadeOut(250);
	},
	
	handleInput: function (e) {
		$(this.containers.error1).fadeOut(200);
		$(this.containers.error2).fadeOut(200);
		$(this.containers.error3).fadeOut(200);
	},
	
	handleNavigation: function (e) {
		if (e.currentTarget === this.buttons.open) {
			// Track click event
			ABS.Helpers.Analytics.trackEvent(this.analytics.category, 'Open');
			
			// Show popup
			this.showPopup();
		} else if (e.currentTarget === this.buttons.close) {
			// Track click event
			ABS.Helpers.Analytics.trackEvent(this.analytics.category, 'Close');
			
			// Hide popup
			this.hidePopup();
		}
	},
	
	handleSubmit: function (e) {
		var that = this;
		var results = this.validator.run();
		
		if (results.areValid) {
		} else {
			if (results.elements.failed.length === 3) {
				$(this.containers.error1).fadeIn(200);
				e.preventDefault();
			} else {
				var failed = {
					zip: false,
					city: false,
					state: false
				};
				$(results.elements.failed).each( function () {
					if (this.name === 'zip') failed.zip = true;
					else if (this.name === 'city') failed.city = true;
					else if (this.name === 'state') failed.state = true;
				});
				if (failed.zip && failed.state) {
					$(this.containers.error3).fadeIn(200);
					e.preventDefault();
				} else if (failed.zip && failed.city) {
					$(this.containers.error2).fadeIn(200);
					e.preventDefault();
				}
			}
		}
	}
};

var hiddenTABHighlightIndex = document.getElementById("hiddenTABHighlightIndex");
hiddenTABHighlightIndex =  hiddenTABHighlightIndex.textContent ? hiddenTABHighlightIndex.textContent : hiddenTABHighlightIndex.innerText;
if(hiddenTABHighlightIndex.length = 0){
hiddenTABHighlightIndex = 0;
}

// Tabbed Content
ABS.Homepage.TabbedContent = {
	analytics: {
		categories: {
			tabs: 'Tabbed Navigation',
			accordions: 'Tabbed Accordion'
		}
	},
	initialIndex: parseInt(hiddenTABHighlightIndex),
	containers: {},
	navigation: [],
	sections: [],
	
	initialize: function () {
		// Define Containers
		this.containers.main = $('#tabbed-body').get(0);
		this.containers.viewport = $('#tabbed-body-viewport').get(0);
		this.containers.navigation = $('#tabbed-nav').get(0);
		
		// Build Sections
		this.buildSections();
		
		// Build Navigation
		this.buildNavigation();
		
		// Force the tabbed body to move back to the left
		this.containers.main.scrollLeft = 0;
	},
	
	getSections: function () {
		var that = this;
		var items = [];
		
		// Find all navigation elements in navigation element
		$('li.section', this.containers.viewport).each(function () {
			items.push(new ABS.Homepage.TabbedContent.Section(this));
		});
		
		return items;
	},
	
	getNavigation: function () {
		// Find all navigation elements in navigation container
		return $('li a', this.containers.navigation).get();
	},
	
	buildSections: function () {
		var that = this;
		
		this.sections = this.getSections();
		
		$(this.sections).each(function (index) {
			this.build();
			if (index !== that.initialIndex) {
				$(this.dom).hide();
			}
		});
	},
	
	buildNavigation: function () {
		var that = this;
		
		this.navigation = this.getNavigation();
		
		$(this.navigation).each(function (index) {
			if (index === that.initialIndex) {
				$(this).addClass('active');
			}
			$(this).mousedown(that.handleNavigation).click(ABS.Utils.dummyEventHandler);
		});
	},
	
	handleNavigation: function (e) {
		var that = ABS.Homepage.TabbedContent;
		
		e.preventDefault();
		
		// Track click event
		ABS.Helpers.Analytics.trackEvent(that.analytics.categories.tabs, $(this).text());
		
		// Deactivate all navigation items
		$(that.navigation).each(function () {
			$(this).removeClass('active');
		});
		
		// Make navigation item active
		$(this).addClass('active');
		
		// Hide all sections
		$(that.sections).each(function () {
			$(this.dom).hide();
		});
		
		// Show new section
		$(this.hash).show();
	}
};

// Recipe Search
ABS.Homepage.TabbedContent.RecipeSearch = {
	buttons: {},
	containers: {},
	inputs: {},
	validator: null,
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#tab-meal-search').get(0);
		this.containers.form = $('#recipe-search-form').get(0);
		this.containers.error = $('#recipe-search-error').get(0);
		
		// Define buttons
		this.buttons.submit = $('#recipe-search-submit').get(0);
		
		// Define inputs
		this.inputs.ingredients = $('#recipe-search-ingredients').get(0);
		this.inputs.recipeSearchType = $('#recipe-search-type').get(0);
		this.inputs.recipeSearchTime = $('#recipe-search-time').get(0);
		
		// Create shortcut to validator
		this.validator = ABS.Helpers.FormValidator;
		
		// Build search form
		this.buildForm();
		
		// Build form validator
		this.buildValidator();
	},
	
	buildForm: function () {
		$(this.containers.form).submit(ABS.Utils.Delegate.create(this, this.handleSubmit));
		$(this.inputs.ingredients).keydown(ABS.Utils.Delegate.create(this, this.handleInput));
	},
	
	buildValidator: function () {
		this.validator = ABS.Helpers.FormValidator({
			form: this.containers.form,
			elements: [
				{
					name: 'ingredients',
					options: {
						required: true
					}
				}
			]
		});
	},
	
	handleInput: function (e) {
		$(this.containers.error).fadeOut(200);
	},
	
	handleSubmit: function (e) {
		var that = this;
		var results = this.validator.run();
		
		if (results.areValid) {
		this.containers.form.action = this.containers.form.action 
										  +"&remoteQuery="+ this.inputs.ingredients.value
										  +"&cboMealType="+ this.inputs.recipeSearchType.value
										  +"&cboCookTime="+ this.inputs.recipeSearchTime.value;	
		
		} else {
			e.preventDefault();
			$(that.containers.error).fadeIn(200);
		}
	}
};

// Weekly Ads
ABS.Homepage.TabbedContent.WeeklyAds = {
	buttons: {},
	containers: {},
	inputs: {},
	validator: null,
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#tab-savings-weekly').get(0);
		this.containers.form = $('#weekly-ads-form').get(0);
		this.containers.error = $('#weekly-ads-error').get(0);
		
		// Define buttons
		this.buttons.submit = $('#weekly-ads-form-submit');
		
		// Define inputs
		this.inputs.categories = $('#weekly-ads-form-categories');
		
		// If the form exists
		if (this.containers.form) {
			// Create shortcut to validator
			this.validator = ABS.Helpers.FormValidator;

			// Build search form
			this.buildForm();

			// Build form validator
			this.buildValidator();
		}
	},
	
	buildForm: function () {
		$(this.containers.form).submit(ABS.Utils.Delegate.create(this, this.handleSubmit));
		$(this.inputs.categories).change(ABS.Utils.Delegate.create(this, this.handleInput));
	},
	
	buildValidator: function () {
		this.validator = ABS.Helpers.FormValidator({
			form: this.containers.form,
			elements: [
				{
					name: 'categories',
					options: {
						required: true
					}
				}
			]
		});
	},
	
	handleInput: function (e) {
		$(this.containers.error).fadeOut(200);
	},
	
	handleSubmit: function (e) {
		var results = this.validator.run();
		
		if (results.areValid) {
		} else {
			e.preventDefault();
			$(this.containers.error).fadeIn(200);
		}
	}
};

// Personalized Coupons
ABS.Homepage.TabbedContent.PersonalizedCoupons = {
	buttons: {},
	containers: {},
	inputs: {},
	validator: null,
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#tab-savings-personal').get(0);
		this.containers.form = $('#preferred-card-form').get(0);
		this.containers.error1 = $('#card-error1').get(0);
		this.containers.error2 = $('#card-error2').get(0);
		
		// Build popup
		this.buildPopup();
		
		// Define buttons
		this.buttons.submit = $('#preferred-card-form-submit').get(0);
		this.buttons.open = $('#preferred-card-popup-open').get(0);
		this.buttons.close = $('#preferred-card-popup-close').get(0);
		
		// Define inputs
		this.inputs.number = $('#preferred-card-form-number').get(0);
		this.inputs.confirm = $('#preferred-card-form-confirm').get(0);
		
		// Create shortcut to validator
		this.validator = ABS.Helpers.FormValidator;
		
		// Build search form
		this.buildForm();
		
		// Build Navigation
		this.buildNavigation();
		
		// Build form validator
		this.buildValidator();
	},
	
	buildPopup: function () {
		var html = '<div id="preferred-card-popup">' +
		'	<a href="#" id="preferred-card-popup-close"><span class="fir">Close</span></a>' +
		'	<p>Locate your Preferred Card Number on the back of your card or on your in-store receipt.</p>' +
		'</div>';
		this.containers.popup = ABS.Managers.Popup.add($(html));
		$(this.containers.popup).css({
			position: 'absolute',
			top: 305,
			left: 315
		});
	},
	
	buildForm: function () {
		$(this.containers.form).submit(ABS.Utils.Delegate.create(this, this.handleSubmit));
		$(this.inputs.number).keydown(ABS.Utils.Delegate.create(this, this.handleInput));
		$(this.inputs.confirm).keydown(ABS.Utils.Delegate.create(this, this.handleInput));
	},
	
	buildNavigation: function () {
		$(this.buttons.open).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
		$(this.buttons.close).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
	},
	
	buildValidator: function () {
		this.validator = ABS.Helpers.FormValidator({
			form: this.containers.form,
			elements: [
				{
					name: 'number',
					options: {
						required: true
					}
				},
				{
					name: 'confirm',
					options: {
						required: true
					}
				}
			]
		});
	},
	
	showPopup: function () {
		$(this.containers.popup).fadeIn(250);
	},
	
	hidePopup: function () {
		$(this.containers.popup).fadeOut(250);
	},
	
	handleInput: function (e) {
		if (e.currentTarget.name === 'number') {
			$(this.containers.error1).fadeOut(200);
		}
		if (e.currentTarget.name === 'confirm') {
			$(this.containers.error2).fadeOut(200);
		}
	},
	
	handleNavigation: function (e) {
		if (e.currentTarget === this.buttons.open) {
			this.showPopup();
		} else if (e.currentTarget === this.buttons.close) {
			this.hidePopup();
		}
	},
	
	handleSubmit: function (e) {
		var that = this;
		var results = this.validator.run();
		
		if (results.areValid) {
		} else {
			e.preventDefault();
			$(results.elements.failed).each(function () {
				if (this.name === 'number') {
					$(that.containers.error1).fadeIn(200);
				}
				if (this.name === 'confirm') {
					$(that.containers.error2).fadeIn(200);
				}
			});
		}
	}
};

// Preferred Savings
ABS.Homepage.TabbedContent.PreferredSavings = {
	buttons: {},
	containers: {},
	inputs: {},
	validator: null,
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#tab-savings-preferred').get(0);
		this.containers.popup = $('#upromise-popup').get(0);
		
		// Define buttons
		this.buttons.open = $('#upromise-popup-open').get(0);
		this.buttons.close = $('#upromise-popup-close').get(0);
		
		// Build Navigation
		this.buildNavigation();
	},
	
	buildNavigation: function () {
		$(this.buttons.open).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
		$(this.buttons.close).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
	},
	
	showPopup: function () {
		$(this.containers.popup).fadeIn(250);
	},
	
	hidePopup: function () {
		$(this.containers.popup).fadeOut(250);
	},
	
	handleNavigation: function (e) {
		if (e.currentTarget === this.buttons.open) {
			this.showPopup();
		} else if (e.currentTarget === this.buttons.close) {
			this.hidePopup();
		}
	}
};

// Coupon Scroller
// TODO: Create Carousel class
ABS.Homepage.TabbedContent.CouponScroller = {
	displayItems: [],
	buttons: {},
	containers: {},
	information: {
		numberOfItemsShown: 3,
		currentIndex: null
	},
	options: {
		enabledNavigationClass: 'enabled',
		item: {
			width: 138
		},
		speed: 700
	},
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#coupon-scroller').get(0);
		this.containers.viewport = $('#coupon-scroller-viewport').get(0);
		this.containers.content = $('#coupon-scroller-content').get(0);
		
		// Define buttons
		this.buttons.left = $('.left a', this.containers.main).get(0);
		this.buttons.right = $('.right a', this.containers.main).get(0);
		
		// Build brand items
		this.buildDisplayItems();
		
		// Build brand items
		this.buildNavigation();
	},
	
	getDisplayItems: function () {
		return $('li', this.containers.content).get();
	},
	
	getFirstViewableIndex: function () {
		return this.information.currentIndex;
	},
	
	getLastViewableIndex: function () {
		return this.information.currentIndex + this.information.numberOfItemsShown;
	},
	
	buildDisplayItems: function () {
		// Get brand items
		this.displayItems = this.getDisplayItems();
		
		// Reset scroller positioning
		this.reset();
	},
	
	buildNavigation: function () {
		$(this.buttons.left).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
		$(this.buttons.right).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
	},
	
	checkNavigation: function () {
		if (this.information.currentIndex > 0) {
			this.enableNavigation(this.buttons.left);
		} else {
			this.disableNavigation(this.buttons.left);
		}
		if (this.getLastViewableIndex() !== this.displayItems.length) {
			this.enableNavigation(this.buttons.right);
		} else {
			this.disableNavigation(this.buttons.right);
		}
	},
	
	disableNavigation: function (dom) {
		$(dom).removeClass(this.options.enabledNavigationClass);
	},
	
	enableNavigation: function (dom) {
		$(dom).addClass(this.options.enabledNavigationClass);
	},
	
	slideTo: function (x, animate) {
		if (typeof animate === 'undefined' || animate === true) {
			$(this.containers.viewport).stop().animate({scrollLeft: x + 'px'}, this.options.speed);
		} else {
			this.containers.viewport.scrollLeft = x;
		}
	},
	
	slideLeft: function () {
		if (this.information.currentIndex > 0) {
			this.information.currentIndex--;
			this.slideTo(this.information.currentIndex * this.options.item.width);
		}
		
		this.checkNavigation();
	},
	
	slideRight: function () {
		if (this.getLastViewableIndex() !== this.displayItems.length) {
			this.information.currentIndex++;
			this.slideTo(this.information.currentIndex * this.options.item.width);
		}
		
		this.checkNavigation();
	},
	
	reset: function () {
		this.information.currentIndex = 0;
		this.slideTo(0, false);
		this.checkNavigation();
	},
	
	handleNavigation: function (e) {
		var that = ABS.Homepage.OOB;
		switch(e.currentTarget.rel) {
			// Handle "Scroll Left" Click
			case 'left':
				// Track click event
				ABS.Helpers.Analytics.trackEvent(that.analytics.category, 'Scroll Left');
				
				// Scroll Left
				this.slideLeft();
				break;
			// Handle "Scroll Right" Click
			case 'right':
				// Track click event
				ABS.Helpers.Analytics.trackEvent(that.analytics.category, 'Scroll Right');
				
				// Scroll Right
				this.slideRight();
				break;
			default: return;
		}
	}
};

// Tabbed Content Section class
ABS.Homepage.TabbedContent.Section = function (el) {
	if (arguments.length !== 1) {
		throw new Error('Expected an argument of one but recieved ' + arguments.length);
	}
	
	this.dom = el;
	
	this.information = {
		currentlyOpen: null
	};
	this.options = {
		closedHeight: 31,
		openedHeight: 200,
		duration: 700
	};
};

ABS.Homepage.TabbedContent.Section.prototype = {
	build: function () {
		// Retrieve children (subsections)
		this.children = this.getChildren();
		
		// Build header links
		this.buildHeaders();
		
		// Close all but first subsection
		for (var i=0; i < this.children.length; i++) {
			if (i !== 0) {
				this.information.currentlyOpen = 0;
				this.closeChild(i, false);
			}
		}
		
	},
	
	getChildren: function () {
		return $('div.subsection', this.dom).get();
	},
	
	getChildIndexById: function (id) {
		$(this.children).each(function(index) {
			if(this.id == id) {}
		});
	},
	
	buildHeaders: function () {
		var that = this;
		
		for (var i=0; i < this.children.length; i++) {
			$('h3', this.children[i]).each(function () {
				this.innerHTML = '<a href="#">' +  this.innerHTML + '</a>';
			});
			$('h3 > a', this.children[i]).each(function () {
				// TODO: Make this prettier
				var x = i;
				$(this).bind('mousedown', function (e) {
					that.handleHeaderLink(e, x);
				}).bind('click', ABS.Utils.dummyEventHandler);
			});
		}
	},
	
	closeChild: function (index, animate) {
		if (typeof animate === undefined || animate === true) {
			$(this.children[index]).animate({
				height: this.options.closedHeight
			}, this.options.duration, function () {
				// Hides this child node's input children
				// This fixes an issue when the user attempts to tab through to hit form inputs
				$(this).children(':input').hide();
			}).addClass('closed');
			
			// TODO: Abstract this out
			ABS.Homepage.TabbedContent.PersonalizedCoupons.hidePopup();
			ABS.Homepage.TabbedContent.PreferredSavings.hidePopup();
			
		} else {
			$(this.children[index]).css('height', this.options.closedHeight).addClass('closed');
			// Hides this child nodes children
			// This fixes an issue when the user attempts to tab through to hit form inputs
			$(this.children[index]).children(':input').hide();
		}
	},
	
	openChild: function (index, animate) {
		$(this.children[index]).animate({
			height: this.options.openedHeight
		}, this.options.duration).removeClass('closed');
		
		// Show a section's children to prevent issues with tabbing
		$(this.children[index]).children(':input').show();
	},
	
	handleHeaderLink: function (e, openIndex) {
		var that = this;

		e.preventDefault();
		
		// Don't do anything if user clicks currently open section
		if (openIndex === this.information.currentlyOpen) return;
		
		// Track click event
		ABS.Helpers.Analytics.trackEvent(ABS.Homepage.TabbedContent.analytics.categories.accordions, $('h3', this.children[openIndex]).text(), $('.active', ABS.Homepage.TabbedContent.containers.navigation).text());
		
		// Animate accordion to show new content
		this.closeChild(this.information.currentlyOpen, true);
		this.information.currentlyOpen = openIndex;
		this.openChild(openIndex);
	}
};

// Our Own Brands
ABS.Homepage.OOB = {
	analytics: {
		category: 'Our Own Brands'
	},
	brandItems: [],
	buttons: {},
	containers: {},
	information: {
		numberOfItemsShown: 3,
		currentIndex: null
	},
	options: {
		enabledNavigationClass: 'enabled',
		item: {
			width: 240
		},
		speed: 700
	},
	
	initialize: function () {
		// Define containers
		this.containers.main = $('#brand-scroller').get(0);
		this.containers.viewport = $('#brand-scroller-viewport').get(0);
		this.containers.content = $('#brand-scroller-content').get(0);
		
		// Define buttons
		this.buttons.left = $('.left a', this.containers.main).get(0);
		this.buttons.right = $('.right a', this.containers.main).get(0);
		
		// Build brand items
		this.buildBrandItems();
		
		// Build brand items
		this.buildNavigation();
	},
	
	getBrandItems: function () {
		return $('li', this.containers.content).get();
	},
	
	getFirstViewableIndex: function () {
		return this.information.currentIndex;
	},
	
	getLastViewableIndex: function () {
		return this.information.currentIndex + this.information.numberOfItemsShown;
	},
	
	buildBrandItems: function () {
		// Get brand items
		this.brandItems = this.getBrandItems();
		
		// Reset scroller positioning
		this.reset();
	},
	
	buildNavigation: function () {
		$(this.buttons.left).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
		$(this.buttons.right).mousedown(ABS.Utils.Delegate.create(this, this.handleNavigation)).click(ABS.Utils.dummyEventHandler);
	},
	
	checkNavigation: function () {
		if (this.information.currentIndex > 0) {
			this.enableNavigation(this.buttons.left);
		} else {
			this.disableNavigation(this.buttons.left);
		}
		if (this.getLastViewableIndex() !== this.brandItems.length) {
			this.enableNavigation(this.buttons.right);
		} else {
			this.disableNavigation(this.buttons.right);
		}
	},
	
	disableNavigation: function (dom) {
		$(dom).removeClass(this.options.enabledNavigationClass);
	},
	
	enableNavigation: function (dom) {
		$(dom).addClass(this.options.enabledNavigationClass);
	},
	
	slideTo: function (x, animate) {
		if (typeof animate === 'undefined' || animate === true) {
			$(this.containers.viewport).stop().animate({scrollLeft: x + 'px'}, this.options.speed);
		} else {
			this.containers.viewport.scrollLeft = x;
		}
	},
	
	slideLeft: function () {
		if (this.information.currentIndex > 0) {
			this.information.currentIndex--;
			this.slideTo(this.information.currentIndex * this.options.item.width);
		}
		
		this.checkNavigation();
	},
	
	slideRight: function () {
		if (this.getLastViewableIndex() !== this.brandItems.length) {
			this.information.currentIndex++;
			this.slideTo(this.information.currentIndex * this.options.item.width);
		}
		
		this.checkNavigation();
	},
	
	reset: function () {
		this.information.currentIndex = 0;
		this.slideTo(0, false);
		this.checkNavigation();
	},
	
	handleNavigation: function (e) {
		var that = ABS.Homepage.OOB;
		switch(e.currentTarget.rel) {
			// Handle "Scroll Left" Click
			case 'left':
				// Track click event
				ABS.Helpers.Analytics.trackEvent(that.analytics.category, 'Scroll Left');
				
				// Track click event
				this.slideLeft();
				break;
			// Handle "Scroll Right" Click
			case 'right':
				// Track click event
				ABS.Helpers.Analytics.trackEvent(that.analytics.category, 'Scroll Right');
				
				// Slide Right
				this.slideRight();
				break;
			default: return;
		}
	}
};

$(document).ready(function () {
	ABS.Homepage.initialize();
});

//Start: code to make an Ajax call for a find a Store link in the homepage

function newStoreRequestObject() {
	var xmlReq = false;
	 if (window.XMLHttpRequest){
	 	//Code for IE7+, Firefox, Chrome, Opera, Safari
	 	xmlReq =  new XMLHttpRequest();
 		 if(xmlReq.overrideMimeType) {
 		 	xmlReq.overrideMimeType('text/html');
 		 }
	 }
	  	
 	if (window.ActiveXObject) {
 		//Code for IE6,IE5
 		try {
 			xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
 		} catch(e1) {
	 		try {
	 			xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
	 		} catch(e2) {
	 			xmlReq = false;
	 		}
 		}
	 }
	
	return xmlReq;
}

// variable declaration
var http;

// function to make an action call to get store details
function findNewStore(url){
	if(http && http.readyState != 0) {
		http.abort();
	}
	http = newStoreRequestObject();
    http.open('GET', url, false);
   	http.send('');
   	return http.responseText;
}

// Handling the server response
function newStoreDetailsResponse() {
	if(http.readyState == 4){
		if(http.status == 200){  
		   	return http.responseText;
  		}
  	}
 }
 
function onClickFindNewStore() {
  if ($('#find-store-link').get(0)) { 
    if(flag == false) {
    	ABS.Homepage.StoreFinder.initialize();
    	flag = true;
    }
  }
}

//End: code to make an Ajax call for a find a Store link in the homepage 
 
