/******************************************************************************************************

	HOVER BUTTON
	-------------------------------------------------------------------------------------------
	searches for images with the class="hover_button" and adds event listeners to toggle over 
	and down states. 
	
	The images need be named yourImageName_off.gif, yourImageName_hover.gif, yourImageName_down.gif
	the file extension doesn't matter, just the _off. _hover. & _down.
	
	DEPENDECIES
	- mootools 1.2

******************************************************************************************************/

var hoverButton = new Class({
	initialize: function(options){
		this.options = options; //save our options.
		
		// set the properties for the object
		this.buttonElement = this.options.buttonElement;
		this.offState = this.buttonElement.src;
		this.hoverState = this.offState.replace('_off.', '_hover.');
		
		this.preloadImage([this.hoverState]);		
	},
	setState : function(newState) {
		this.buttonElement.src = newState;	
	},
	preloadImage : function(arrImagePaths) {
		var parentObject = this;
		var img = new Asset.images(arrImagePaths, { onComplete: function(){parentObject.addListeners()} });	
	},
	addListeners : function() {
		this.buttonElement.addEvent('mouseover', this.setState.pass(this.hoverState, this));
		this.buttonElement.addEvent('mouseleave', this.setState.pass(this.offState, this));
	}
});

var hoverButtonHandler = {
	arrHoverButtons : [],
	arrHoverInputs : [],
	
	init : function() {
		var arrButtons = $$('img.hover_button');
		var arrInputs = $$('input.hover_button');
	
		for (i=0; i<arrButtons.length; i++) {		
			hoverButtonHandler.arrHoverButtons[i] = new hoverButton({buttonElement: arrButtons[i]});		
		}	
		
		for (i=0; i<arrInputs.length; i++) {		
			hoverButtonHandler.arrHoverInputs[i] = new hoverButton({buttonElement: arrInputs[i]});		
		}
	}
}

window.addEvent('domready', hoverButtonHandler.init);




/* ---------------------------------------------------------------------------------------------

	AMS TOOLBAR MESSAGE

------------------------------------------------------------------------------------------------ */
var ams_toolbarMessage = new Class({
	
	initialize: function(id, cookie, omniture, slide) {	
		
		// Temporarily disabled this message
		return;
		// Don't show anything if we're not dealing with a browser that supports the toolbar
		this.browser = this.detectBrowser(); 
		if (this.browser == 'Other') return;
		
		// Don't show anything if the message has already been shown during this session
		this.cookie = cookie;
		if (this.cookie != null && Cookie.read(this.cookie) == 'no') return;
				
		this.container = $(id);	
		this.omniture = omniture;
		this.slide = (slide == null) ? true : slide;
		
		if (this.browser == "MSIE6") {
			this.enableIE6Message.delay(500, this);
		} else {			
			// Wait half a second to give toolbar time to register itself
			this.enableToolbarMessage.delay(500, this); 
		}
	},
	
	enableIE6Message: function() {
		this.message = this.container.getElement('div.ie6');
		
		// If no IE 6 message exists (e.g. How it works page) 
		// then try showing the toolbar message
		if (!this.message) {
			this.enableToolbarMessage();
			return;
		}
				
		// Track the "ie 6" message to Omniture
		if (this.omniture != null) {
			this.omniture.obj[this.omniture.prop] = this.omniture.prefix + " - IE6" + this.browser;
			this.omniture.obj.linkTrackVars = this.omniture.prop;
			this.omniture.obj.tl(this, 'o');
		}
		
		this.display();
	},
	
	enableToolbarMessage: function() {	
		
		// Configure the container for the appropriate message		
		if (this.isToolbarInstalled()) {
			
			// Now that we know the toolbar is installed, set a 
			// session cookie so we don't have to keep checking on 
			// every page load
			if (this.cookie != null)
				var toolbarCookie = Cookie.write(this.cookie, 'no', {duration: 0});
			
			return; // Installed message TEMPORARILY disabled as per Paul's request.
			
			this.message = this.container.getElement('div.installed');
									
			// Track the "installed" message to Omniture
			if (this.omniture != null) {
				this.omniture.obj[this.omniture.prop] = this.omniture.prefix + " - Installed";
				this.omniture.obj.linkTrackVars = this.omniture.prop;
				this.omniture.obj.tl(this, 'o');
			}
		} else {					
			
			this.message = this.container.getElement('div.not_installed');
													
			// Enable the browser specific download button
			switch(this.browser)
			{
				case 'Firefox':
					this.container.getElement('a.ff_button').setStyle('display', 'inline');
					break;
				case 'MSIE':
				case 'MSIE6':
					this.container.getElement('a.ie_button').setStyle('display', 'inline');
					break;
			} 
			
			// Track the "not installed" message to Omniture
			if (this.omniture != null) {
				this.omniture.obj[this.omniture.prop] = this.omniture.prefix + " - NotInstalled" + this.browser;
				this.omniture.obj.linkTrackVars = this.omniture.prop;
				this.omniture.obj.tl(this, 'o');
			}
		}
		
		this.display();
	},
	
	display: function() {
		
		// If no message exists, there is nothing to display
		if (!this.message) return;
		
		this.message.setStyle('display', 'block');
		
		// Configure the close button
		this.close_button = this.message.getElement('a.close_button');
		if (this.close_button)
			this.close_button.addEvent('click', this.close.bind(this));
		
		// Show the toolbar message
		this.container.setStyle('display', 'block');
		if (this.slide) {
			var targetHeight = this.container.getStyle('height');
			this.container.setStyle('height', 0);	
			this.container.set('tween', {
				'duration':600,
				'transition': Fx.Transitions.Cubic.easeOut
			});
			this.container.tween('height', 0, targetHeight);
		}
		
		// Set a session cookie to signal that the message has been shown
		if (this.cookie != null)
			var toolbarCookie = Cookie.write(this.cookie, 'no', {duration: 0});
	},
	
	close : function() {
	
		this.container.set('tween', {
			'duration':400,
			'transition': Fx.Transitions.Back.easeIn
		});
		this.container.tween('height', 0);
	},
		
	isToolbarInstalled : function() {
	
		return toolbar.Toolbars.length > 0; 
	},
	
	detectBrowser : function() {
	
		var browser = navigator.userAgent;
		var b_version = navigator.appVersion;
		var version = parseFloat(b_version);
	 		 	
		if (browser.indexOf("Firefox") != -1) {
			return "Firefox";
		} else if (browser.indexOf("MSIE") != -1 && version >= 4) {
			return (b_version.indexOf("MSIE 6.0") != -1) ? "MSIE6" : "MSIE";
		} else {
			return "Other";
		}
	}
		
});


/* ---------------------------------------------------------------------------------------------

	AMS OUR STORES NAV

------------------------------------------------------------------------------------------------ */
var ams_ourStoresNav = {
	animation: null,
	menu: null,
	link: null,
	link_pos: null,
	aft_link: null,
	menu_height: null,
	open_timer: null,
	close_timer: null,
	menu_open: false,
	
	init: function() {
		ams_ourStoresNav.link = $('our_stores_nav_link');
		ams_ourStoresNav.aft_link = ams_ourStoresNav.link.getNext();
		ams_ourStoresNav.menu = $('our_stores_nav');
		ams_ourStoresNav.menu_height = ams_ourStoresNav.menu.getCoordinates().height;
		ams_ourStoresNav.link_pos = ams_ourStoresNav.link.getCoordinates('header_nav_bar');
		
		ams_ourStoresNav.menu.setStyles({
			'visibility': 'visible',
			'display': 'none',
			'left': ams_ourStoresNav.link_pos.left + 1
		})
		
		ams_ourStoresNav.animation = new Fx.Tween(ams_ourStoresNav.menu, {
			duration: 300, 
			transition: Fx.Transitions.Quad.easeOut,
			onComplete: function() {
				if(ams_ourStoresNav.menu.getStyle('height').toInt() == 0) {
					ams_ourStoresNav.link.removeClass('dark_tab');
					ams_ourStoresNav.aft_link.removeClass('after_dark_tab');
				}
				ams_ourStoresNav.menu_open = !ams_ourStoresNav.menu_open;
			}
		});
		
		ams_ourStoresNav.link.addEvent('mouseenter', function(){
			clearTimeout(ams_ourStoresNav.close_timer);
			ams_ourStoresNav.open_timer = setTimeout('ams_ourStoresNav.open();', 200);
		});
		ams_ourStoresNav.link.addEvent('mouseleave', function(){
			clearTimeout(ams_ourStoresNav.open_timer);
			ams_ourStoresNav.close_timer = setTimeout('ams_ourStoresNav.close();', 200);
		});
		ams_ourStoresNav.menu.addEvent('mouseenter', function(){
			clearTimeout(ams_ourStoresNav.close_timer);
		})
		ams_ourStoresNav.menu.addEvent('mouseleave', function(){
			ams_ourStoresNav.close_timer = setTimeout('ams_ourStoresNav.close();', 200);
		});
	},
	
	open: function() {	
		if (!ams_ourStoresNav.menu_open) {	
			ams_ourStoresNav.link.addClass('dark_tab');
			ams_ourStoresNav.aft_link.addClass('after_dark_tab');
			ams_ourStoresNav.menu.setStyles({
				'height':0,
				'display':'block'
			})
			ams_ourStoresNav.animation.start('height', ams_ourStoresNav.menu_height);	
		}
	},
	
	close: function() {	
		if (ams_ourStoresNav.menu_open) {			
			ams_ourStoresNav.animation.start('height', 0);
		}
	}
}



/* ---------------------------------------------------------------------------------------------

	AMS AUTO CLEAR FIELD

------------------------------------------------------------------------------------------------ */
var ams_autoClearField = new Class({
    initialize: function(fieldID){
    	this.textfield = $(fieldID);
    	if (this.textfield) {
	        this.defaultValue = this.textfield.value;
	        
	        this.textfield.addEvent('focus', this.clearField.bind(this));
	        this.textfield.addEvent('blur', this.resetField.bind(this));
        }
        else {
        	throw('ams_autoClearField: no field with the id of '+fieldID+' was found');
        }
    },
    
    clearField: function() {
    	if (this.textfield.value == this.defaultValue) {
    		this.textfield.value = '';
    	}
    },
    
    resetField: function() {
    	if (this.textfield.value == '') {
    		this.textfield.value = this.defaultValue;
    	}
    }
});

var ams_setupCollectorField = new Class({
	initialize: function(fieldID, defaultText){
		this.textfield = $(fieldID);
		this.defaultValue = defaultText;
		
		if (this.textfield) {
			this.textfield.maxLength = 11;
			this.resetField();
			this.textfield.addEvent('focus', this.clearField.bind(this));
			this.textfield.addEvent('blur', this.resetField.bind(this));
		} else {
			throw('ams_setupCollectorField: no field with id of '+fieldID+' was found');
		}
	},
	
	clearField: function() {
		if (this.textfield.value == this.defaultValue) {
			this.textfield.value = '';
			this.textfield.maxLength = 11;
		}
	},
	
	resetField: function() {
		if (this.textfield.value == '') {
			this.textfield.maxLength = this.defaultValue.length+1;
			this.textfield.value = this.defaultValue;
		}
	}
});

/* ---------------------------------------------------------------------------------------------

	AMS CAROUSEL

------------------------------------------------------------------------------------------------ */
var ams_carousel = new Class({
	Implements: Chain,
	initialize: function(carouselID, numItemsDisplayed, numItemsTotal, numItemsMove, animateMethod, animateSpeed) {
		this.carousel = $(carouselID);
		this.numItemsDisplayed = (numItemsDisplayed != null) ? numItemsDisplayed : 1;
		this.numItemsTotal = (numItemsTotal != null) ? numItemsTotal : 0;
		this.numItemsMove = (numItemsMove != null) ? numItemsMove : 1;
		this.animateMethod = (animateMethod != null) ? animateMethod : 'slide';
		this.animateSpeed = (animateSpeed != null) ? animateSpeed : 500;
		
		this.carouselItemsContainer = this.carousel.getElement('.items');
		this.numCarouselItems = this.carousel.getElements('.item').length;
		this.carouselItemsContainer.setStyle('left', 0);
		
		this.carouselItem = this.carousel.getElement('.item');
		this.carouselItemWidth = this.carouselItem.getCoordinates().width;
		this.carouselItemMarginWidth = this.carouselItem.getStyle('marginRight').toInt();
				
		this.carouselOffset = (this.carouselItemWidth * this.numItemsMove) + (this.carouselItemMarginWidth * this.numItemsMove);
		this.maxOffset = (this.numCarouselItems - (this.numItemsDisplayed)) * (this.carouselItemWidth + this.carouselItemMarginWidth);
		
		this.carouselItemsContainer.set('tween', {
			duration: this.animateSpeed, 
			transition: Fx.Transitions.Quad.easeOut,
			onStart: function(){
				this.animating = true;
			}.bind(this),
			onComplete: function(){
				this.animating = false;
				this.callChain();
			}.bind(this)
		});
		
		if (this.carousel.getElement('.carousel_previous')) {
			this.nextButton = this.carousel.getElement('.carousel_next');
			this.previousButton = this.carousel.getElement('.carousel_previous');
			
			this.previousButton .addEvent('click', this.goPrevious.bind(this));
			this.nextButton.addEvent('click', this.goNext.bind(this));
			
			this.previousButton.setStyle('opacity', 0.5);
		}
		else if(this.carousel.getElement('.carousel_previous_small')) {
			this.nextButton = this.carousel.getElement('.carousel_next_small');
			this.previousButton = this.carousel.getElement('.carousel_previous_small');
			
			this.previousButton.addEvent('click', this.goPrevious.bind(this));
			this.nextButton.addEvent('click', this.goNext.bind(this));
			
			this.previousButton.setStyle('opacity', 0.5);
		}
		else {
			throw('ams_carousel: could not find previous and next buttons');
			return;
		}
		
		// Center the items and hide the next/prev buttons
		if (this.numItemsTotal <= this.numItemsDisplayed) {
			var totalWidth = (this.numItemsTotal * this.carouselItemWidth) + ((this.numItemsTotal - 1) * this.carouselItemMarginWidth);
			var maxWidth = (this.numItemsDisplayed * this.carouselItemWidth) + ((this.numItemsDisplayed - 1) * this.carouselItemMarginWidth);
			var offset = (maxWidth - totalWidth) / 2;
			
			this.carouselItemsContainer.setStyle('left', offset);
			this.previousButton.setStyle('display', 'none');
			this.nextButton.setStyle('display', 'none');
		}
	},
	
	goPrevious : function() {
		if (! this.animating) {
			
			var currLeft = this.carouselItemsContainer.getStyle('left').toInt();
			var newLeft = ((currLeft + this.carouselOffset) < 0) ? currLeft + this.carouselOffset : 0;
			var isEnd = (newLeft == 0) ? true : false;
			
			if (currLeft != newLeft) {
				if (this.animateMethod == 'fade') {
					this.chain(
						function(){this.carouselItemsContainer.tween('opacity', 0)},
						function(){this.carouselItemsContainer.setStyle('left', newLeft); this.callChain();},
						function(){this.carouselItemsContainer.tween('opacity', 1)}
					);
					this.callChain();
				}
				else if (this.animateMethod == 'slide') {
					this.carouselItemsContainer.tween('left', newLeft);
				}
			}
			
			if (isEnd) {
				this.previousButton.setStyle('opacity', 0.5);
			}
			else {
				this.previousButton.setStyle('opacity', 1);
			}
			
			this.nextButton.setStyle('opacity', 1);		
		}
		
		return false;
	},
	
	goNext : function() {
		if (! this.animating) {
			var currLeft = this.carouselItemsContainer.getStyle('left').toInt();
			var newLeft = (((currLeft - this.carouselOffset) * -1) < this.maxOffset) ? currLeft - this.carouselOffset : (this.maxOffset * -1);
			var isEnd = ((newLeft * -1) < this.maxOffset) ? false : true;
			
			if (currLeft != newLeft) {
				if (this.animateMethod == 'fade') {
					this.chain(
						function(){this.carouselItemsContainer.tween('opacity', 0)},
						function(){this.carouselItemsContainer.setStyle('left', newLeft); this.callChain();},
						function(){this.carouselItemsContainer.tween('opacity', 1)}
					);
					this.callChain();
				}
				else if (this.animateMethod == 'slide') {
					this.carouselItemsContainer.tween('left', newLeft);
				}
			}
			
			if (isEnd) {
				this.nextButton.setStyle('opacity', 0.5);
			}
			else {
				this.nextButton.setStyle('opacity', 1);
			}
			
			this.previousButton.setStyle('opacity', 1);
		}
		
		return false;
	}

});



/* ---------------------------------------------------------------------------------------------

	AMS OVERLAY

------------------------------------------------------------------------------------------------ */
var ams_overlay = new Class({
	initialize: function(overlayID, targetUrl) {
		this.overlay = $(overlayID);
		this.targetUrl = targetUrl;
		this.blackout = $('blackout');
		this.visible = false;
		
		this.animation = new Fx.Tween(this.blackout, {
			duration: '200',
			transition: Fx.Transitions.Quad.easeOut,
			onComplete: function() {
				if (! this.visible) {
					this.showOverlay();					
				}
				else {
					this.visible = ! this.visible;
				}
			}.bind(this)
		});
		
		window.addEvent('resize', this.resize.bind(this));
	},
	
	show: function(targetUrl) {
		this.targetUrl = targetUrl;
		
		 var windowScrollSize = window.getScrollSize();
		
		this.blackout.setStyles({
			'display': 'block',
			'opacity': 0,
			'height': windowScrollSize.y,
			'width': windowScrollSize.x
		});
		
		this.animation.start('opacity', 0.5);
		
		return false;
	},
	
	showOverlay: function() {
		var windowSize = window.getSize();
		var windowScrollSize = window.getScrollSize();		
		var overlaySize = this.overlay.getSize();
		var scrollPos = window.getScroll().y;
        
        if (this.frame == null) {
        	this.frame = new IFrame({'src': this.targetUrl,
                            'name':'overlayFrame',
                            'id':'overlayFrame',
                            'scrolling': 'no',
                            'frameborder' : '0',
                            'allowTransparency' : 'true'
                            });
 
        	this.overlay.adopt(this.frame); 
        } else {
        	this.frame.src = this.targetUrl;
        }			
		this.overlay.setStyles({
			'top' : scrollPos + 120,
			'left' : (windowSize.x / 2) - (overlaySize.x / 2),
			'visibility' : 'visible'
		});
		
		this.visible = true;
	},
	
	hide: function(loginValue) {
		if (loginValue != null && loginValue == "Success") {
			var reloadUrl = location.href.replace(/\&gotoStore=\w+/,'').replace(/\?gotoStore=\w+/,'');
			location.href = reloadUrl;
		}
		this.overlay.setStyle('visibility', 'hidden');
		//$('overlayFrame').dispose();
		//this.frame = null;
		
		this.animation.start('opacity', 0);
	},
	
	hideOverlay: function() {
		this.overlay.setStyle('visibility', 'hidden');
		this.visible = false;
	},
	
	resize: function() {	
		if (this.visible) {
			var windowSize = window.getSize();
			var windowScrollSize = window.getScrollSize();		
			var overlaySize = this.overlay.getSize();
			var scrollPos = window.getScroll().y;
			
			this.overlay.setStyles({
				'top' : scrollPos + 120,
				'left' : (windowSize.x / 2) - (overlaySize.x / 2)
			});
			
			this.blackout.setStyles({
				'width': windowScrollSize.x,
				'height': windowScrollSize.y
			});
		}
	}
});


/* ---------------------------------------------------------------------------------------------

	SEARCH SLIDER WIDGET

------------------------------------------------------------------------------------------------ */
var activeSlider;
var maxSliderLeft = 150;
var maxPoints;
var minValue;
var maxValue;

function SearchInit() {
	var slider = document.getElementById("slider");
	
	if (slider == null)
		return;
	
	var sliders = slider.getElementsByTagName("div");
	for (var i = 0; i < sliders.length; i++) {
		d = new Drag.Move(sliders[i], {container:slider,onDrag:sliderMove,onComplete:sliderStop});
	}
	// set slider locations based on current values
	maxPoints = parseInt(document.getElementById("findreward").maxpoints.value);
	minValue = parseInt(document.getElementById("findreward").min.value);
	maxValue = parseInt(document.getElementById("findreward").max.value);
	document.getElementById("slider_low").style.left = parseInt(maxSliderLeft * (minValue / maxPoints)) + "px";
	document.getElementById("slider_high").style.left = parseInt(maxSliderLeft * (maxValue / maxPoints)) + "px";
	//document.getElementById("slider_value").innerHTML = "From " + formatNumber(minValue) + " to " + formatNumber(maxValue) + " points";
	sliderStop();
}

function sliderMove(e) {
	minValue = parseInt(maxPoints * (parseInt(document.getElementById("slider_low").style.left) / maxSliderLeft));
	minValue = minValue - (minValue % 5);
	maxValue = parseInt(maxPoints * (parseInt(document.getElementById("slider_high").style.left) / maxSliderLeft));
	maxValue = maxValue - (maxValue % 5);
	document.getElementById("findreward").min.value = minValue;
	document.getElementById("findreward").max.value = maxValue;
	//document.getElementById("slider_value").innerHTML = "From " + formatNumber(minValue) + " to " + formatNumber(maxValue) + " points";
}

function sliderStop(e) {
	if (minValue > maxValue) {
		var tempPos = document.getElementById("slider_low").style.left;
		document.getElementById("slider_low").style.left = document.getElementById("slider_high").style.left;
		document.getElementById("slider_high").style.left = tempPos;
		sliderMove(e);
	}
}



/* ---------------------------------------------------------------------------------------------------------

	QUICK SEARCH
	
------------------------------------------------------------------------------------------------------------ */
var QuickSearch = new Class({

	arrMatches : [],

	initialize: function(fieldID, targetUrl, submitID) {
		this.field = $(fieldID);
		this.target = targetUrl;
		this.submitBtn = $(submitID);
		
		this.field.addEvent('keyup', function(event){
			eventField = event.target;
			
			if (event.key == 'up') {
				this.changeSelection('up');
			}
			else if (event.key == 'down') {
				this.changeSelection('down');
			}
			else if (event.key == 'enter') {
				this.goToSelection();
			}
			else if (event.key == 'right' || event.key == 'left') {
				
			}
			else {
				this.doSearch(eventField.value);
			}
		}.bind(this));
		
		this.field.addEvent('blur', function(event){
			this.hideList.delay('500', this);
		}.bind(this));
		
		this.field.addEvent('focus', function(event){
			eventField = event.target;
			this.doSearch(eventField.value);
		}.bind(this));
		
		fieldCoords = this.field.getCoordinates($$('.master_container')[0]);
		
		this.ListContainer = new Element('ul', {
			'class' : 'quick_search_list',
			'styles' : {
				'position':'absolute',
				'display':'none',
				'top':fieldCoords.top + fieldCoords.height,
				'left':(fieldCoords.left - 1),
				'width':(fieldCoords.width - 2),
				'z-index':'500'
			}
		});
		this.ListContainer.inject($$('.master_container')[0]);
		
		if (this.submitBtn) {
			this.submitBtn.addEvent('click', this.submitForm.bind(this));
		}
	},
	
	doSearch: function(searchTerm) {
		this.arrMatches = [];
		searchTerm = searchTerm.toLowerCase();
			
		if (searchTerm.length > 2) {			
			quickSearchStores.each(function(item, index) {
				itemText = item[0].toLowerCase();
				if (itemText.indexOf(searchTerm) >= 0) {
					match = [item[0], itemText.indexOf(searchTerm), item[1]];
					this.arrMatches.push(match);
				} 
			}.bind(this));
			
			this.buildList();
		}
		
		if (this.arrMatches.length <= 0)
			this.hideList();
	},
	
	sortResult: function(item1, item2) {
		var a = item1[1];
		var b = item2[1];
		if (a > b) return 1;
  		if (a < b) return -1;
  		return 0;
	},
	
	buildList: function() {	
		this.ListContainer.set('html', '');	
		var listSize = 0;
		this.arrMatches.each(function(item, index) {
			if (listSize < 10) {
				var newListItem = new Element('li', {
					'html': item[0],
					'id': item[2]
				});
				newListItem.inject(this.ListContainer);
				
				newListItem.addEvent('click', function(e){
					e = new Event(e);
					//console.log(e);
					e.target.addClass('highlighted');
					this.goToSelection();
				}.bind(this));
				listSize++;
			}
		}.bind(this));
		
		this.showList();
	},
	
	showList: function() {
		this.ListContainer.setStyle('display', 'block');
	},
	
	hideList: function() {
		this.ListContainer.setStyle('display', 'none');
	},
	
	changeSelection: function(direction) {
		var currHighlighted = this.ListContainer.getElement('.highlighted');
		var firstRun = false;
		
		if (!currHighlighted) {
			currHighlighted = this.ListContainer.getElement('li');
			if (!currHighlighted)
				return;
				
			currHighlighted.addClass('highlighted');	
		}
		else {
			nextHighlighted = (direction == 'up') ? $(currHighlighted).getPrevious() : $(currHighlighted).getNext();
				
			if (! nextHighlighted) {
				nextHighlighted = (direction == 'up') ? this.ListContainer.getLast() : this.ListContainer.getElement('li');
			}
			$(currHighlighted).removeClass('highlighted');
			
			currHighlighted = nextHighlighted;
				
			currHighlighted.addClass('highlighted');
			
		}
		this.field.value = html_entity_decode(currHighlighted.get('html'));
	},
	
	goToSelection: function() {
		var currHighlighted = this.ListContainer.getElement('.highlighted');
		if (currHighlighted) {
			var currStoreID = currHighlighted.id;
			goToLinkWithParamAddParam(this.target, currStoreID);
			//window.location = 'SearchByStore?RetailerID=' + currStoreID;
		}
	},
	
	submitForm: function(event) {
		if (this.ListContainer.getElement('.highlighted')) {
			event.stop();
			this.goToSelection();
		}		
	}
});

/* -----------------------------------------------------------------------------------------
	
	QUICK STORES SEARCH LIST
	
	this is the list of stores used for the Quick Store Lookup on the browse stores pages.
	each element in the array is an array that represents a store
	[0] - first element in a store array is the store's name
	[1] - second element in the store array is an id that gets passed to the store details page
	
	you can place alternate spellings for a store in the list as long as both spellings have 
	the same store id. However this will cause both spellings to appear in the suggestions 
	list as we didn't build any logic to eliminate multiple spellings of the same store from 
	appearing.
	

-------------------------------------------------------------------------------------------- */


function html_entity_decode(str) {	
	var tarea=document.createElement('textarea');	
	tarea.innerHTML = str; return tarea.value;	
	tarea.parentNode.removeChild(tarea);
}

// -- AMS GLOBAL FUNCTIONS --

/* Ads */

// Stuff for ads
var RN = new String (Math.random());
var RNS = RN.substring (2, 11);

var protocol = document.location.href.substring(0,document.location.href.indexOf(":")+3);
var oas = protocol + "adserver.airmiles.ca/RealMedia/ads/"; 

var _version = 11;
if (navigator.userAgent.indexOf('Mozilla/3') != -1){
	_version=10;
}

function DisplayAds (position, width, height, sitepage, qs, productid) {
	var oaspage = sitepage + '/1' + RNS + '@' + position + "?" + qs + "&paid=" + productid;

	if (_version < 11) {
		document.write ('<A HREF="' + oas + 'click_nx.ads/'+ oaspage + '" TARGET="_top" ><IMG SRC="' + oas + 'adstream_nx.cgi/' + oaspage + '" BORDER="0" WIDTH="' + width + '" HEIGHT="' + height + '"></a>');
	} 
	else {
		document.write ('<SCR' + 'IPT LANGUAGE="JavaScript1.1" SRC="' + oas + 'adstream_jx.ads/' + oaspage + '">');
		document.write ('\<\!-- --\>');
		document.write ('\<\/SCR' + 'IPT\>');
		document.write ('\<\!-- --\>');
	}
}

function getCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0])
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}

/* Onload Events */
var onloadcalls = [];

function appendOnLoad(func) {
	if(window.onload != allOnLoad) {
		if(window.onload != undefined)
			onloadcalls[onloadcalls.length] = window.onload;
		window.onload = allOnLoad;
	}
	onloadcalls[onloadcalls.length] = func;
}

function allOnLoad() {
	var len = onloadcalls.length;
	for(var i = 0; i < len; ++i) {
		onloadcalls[i]();
	}
}

/* ---------------------------------------------------------------------------------------------------------

	Imported from old java script
	
------------------------------------------------------------------------------------------------------------ */
var formbusy = false;
function disableForm() {
	if(formbusy) {
		return false;
	} else {
		formbusy = true;
		return true;
	}
}

function changeLocation(url) {
	window.location=url;
}

function changeLocale(newLocale){
	var currentLocation = location.href.replace(/\&changeLocale=\w+/,'').replace(/\?changeLocale=\w+/,'');
	
	location.href = currentLocation + (currentLocation.indexOf('?') != -1 ? "&" : "?") + "changeLocale=" + newLocale;
	
}

function goToLinkWithParamAddParam(linkUrl, param, param2)
{

	//var newLinkUrl = linkUrl + "_" + param;
	var newLinkUrl = linkUrl;
	
	
	if (param2) {
		newLinkUrl += "-" + param2;
		newLinkUrl = newLinkUrl.replace(/param2/g, param2);
	}
	
	document.location=newLinkUrl.replace(/param/g, param);
}

function removeFilterBy(urlString)
{
	var temp = urlString;
	if (temp.indexOf("&filterby=")>0)
	{
		temp = temp.substring(0, temp.indexOf("&filterby="));

	}
	return temp;
}

function goStore(url) {
	if (url)
		window.open(url);
}
function displayPopUP(e,divName)
{
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if(!e) {return;}
	if (e.pageX || e.pageY)
	{
		posx = e.pageX;
		posy = e.pageY + 25;
	}
	else if (e.clientX || e.clientY)
	{
		posx=e.clientX + document.body.scrollLeft - document.body.clientLeft;
		posy=e.clientY + document.documentElement.scrollTop + 25;
	}
	
	// div .master_container has position:relative
	var container = $$(".master_container")[0];
	var offsetLeft = container && container.offsetLeft ? container.offsetLeft : 0;
	
	document.getElementById(divName).style.left=(posx-offsetLeft-5)+"px";
	document.getElementById(divName).style.top=(posy)+"px";
	document.getElementById(divName).style.display= 'block';
}
function hidePopUP(e,divName)
{
	document.getElementById(divName).style.display= 'none';
}
//------------------------------------------------
//	clear text field
//------------------------------------------------
function clearText(id){
	//	retrieve object
	//------------------------------
	OBJ	= getObject(id);	

	//	clear value
	//------------------------------
	OBJ.value = "";
}

function isblank(val) {
  if (val == null) { return true; }
  for (var i=0; i < val.length; i++) {
    if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n")) { return false; }
  }
  return true;
}


function isAlphaSpecial(checkStr,extraChars) {
 var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"+extraChars;

 if (checkStr==null) return false;

 for (i = 0;  i < checkStr.length;  i++) {
	ch = checkStr.charAt(i);
	for (j = 0;  j < checkOK.length;  j++)
		if (ch == checkOK.charAt(j))
			break;
  	if (j == checkOK.length) {

		return false;
	}
 }

 return true;
}