var Best = Class.create({
	initialize: function () {
		this.cachedImages = [];
	},
	/* Image Caching */
	cacheImage: function (url, width, height) {
		var img;
		if (width > 0 && height > 0)
			img = new Image(width, height);
		else
			img = new Image();
		img.src = url;
		img.className = '-best-cached-image';
		img.style.display = 'none';
		this.cachedImages.push($(img));
	},
	cacheImages: function () {
		var args = $A(arguments);
		args.each(function (value) {
			this.cacheImage.apply(this, value);
		}.bind(this));
	},
	linkPopup: function (obj, options) {
		options = Object.extend({
			stop: true,
			name: 'LINKPOPUP',
			arguments: 'scrollbars,resizable'
		}, options);
		obj = $(obj);
		if (!obj || !obj.href) return;
		var url = '' + obj.href;
		if (!url.startsWith('#') && !url.startsWith('javascript:')) {
			var win = window.open(url, options.name, options.arguments);
			return false;
		}
	},
	addLinkPopup: function (obj, options) {
		obj = $(obj);
		if (!obj) return false;
		Event.observe(obj, 'click', function (event) {
			if (obj.href) {
				this.linkPopup(obj, options);
				Event.stop(event);
			}
		}.bindAsEventListener(this));
	}
});

window.best = new Best();

window.best.Tabset = Class.create({
	initialize: function (obj, current, options) {
		this.box = $(obj);
		this.options = Object.extend({
			cssTabBox: '.tabs',
			cssTabBtn: 'li a.tab-btn',
			cssPageBox: '.contents .pages',
			cssPage: '.page',
			clsTabSel: 'over'
		}, options);
		this.tabBox = this.box.select(this.options.cssTabBox).reduce();
		this.pageBox = this.box.select(this.options.cssPageBox).reduce();
		this.buttons = this.tabBox.select(this.options.cssTabBtn);
		this.pages = this.pageBox.select(this.options.cssPage);
		this.current = current || 0;
		// Bound Methods
		this.selectButtonBoundEvt = function (evt) {
			var btn = $(evt.target);
			var index = this.buttons.indexOf(btn)
			if (index == -1) {
				btn = $(btn).up(this.options.cssTabBtn);
			}
			if (btn) {
				this.selectButton(btn);
			}			
		}.bindAsEventListener(this);
		// Event Handlers
		this.buttons.invoke('observe', 'click', this.selectButtonBoundEvt);
		this.buttons.each(function(btn) {
			btn.onclick = function () {btn.blur(); return false;};
		});
		this.busyShowing = false;
		this.busyHiding = false;
		// Normalize Dimensions
		this.normalize.bind(this).defer();
		// Fire loaded and show first tab
		this.showTab.bind(this).defer(this.current);
	},
	normalize: function () {
		this.pages.invoke('hide');
		this.pageDims = this.pageBox.getDimensions();
		if (this.pageDims.width == 0) {
			this.pageDims.width = this.pages.max(function (page) {
				page.show();
				return page.getWidth();
			});
		}
		if (this.pageDims.height == 0) {
			this.pageDims.height = this.pages.max(function (page) {
				page.show();
				return page.getHeight();
			});		
		}
		this.pageBox.setStyle({width: this.pageDims.width + 'px', height: this.pageDims.height + 'px'});
		this.pages.invoke('setStyle', {display: 'none', opacity: 0, position: 'absolute', top: 0, left: 0, width: this.pageDims.width, height: this.pageDims.height, overflow: 'auto'})
		this.box.fire('best:load');
	},
	selectButton: function (btn) {
		var next = this.buttons.indexOf(btn);
		if (this.busyShowing || this.busyHiding || next == -1) return;
		if (this.current >= 0) {
			if (this.buttons[this.current] == btn) return;
			this.hideTab(this.current); 
		}
		this.current = next;
		if (this.current >= 0) {
			this.showTab(this.current);
		}
	},
	showTab: function (index) {
		if (index < 0) return;
		var btn = this.buttons[index];
		var page = this.pages[index];
		if (this.busyShowing) return;
		this.box.fire('best:beforeShow', {kind: 'tab', index: index})
		this.busyShowing = true;
		page.style.display = 'block';
		$(btn.parentNode).addClassName(this.options.clsTabSel);
		new Effect.Opacity(page, {to: 1, duration: 0.5,
			afterFinish: function () {
				this.box.fire('best:afterShow', {kind: 'tab', index: index})
				this.busyShowing = false;
			}.bind(this)
		});
		
	},
	hideTab: function (index) {
		if (index < 0) return false;
		var btn = this.buttons[index];
		var page = this.pages[index];
		if (this.busyHiding) return;
		this.box.fire('best:beforeHide', {kind: 'tab', index: index})
		this.busyHiding = true;
		$(btn.parentNode).removeClassName(this.options.clsTabSel);
		new Effect.Opacity(page, {to: 0, duration: 0.5,
			afterFinish: function () {
				page.style.display = 'none';
				this.box.fire('best:afterHide', {kind: 'tab', index: index})
				this.busyHiding = false;				
			}.bind(this)
		});
	}
});

window.best.FixedScroller = Class.create({
	initialize: function (container, hUpLeft, hDownRight, options) {
		this.container = $(container);
		this.clipper = $(this.container.parentNode);
		this.hUpLeft = $(hUpLeft);
		this.hDownRight = $(hDownRight);
		this.options = Object.extend({
			cssItem: 'a.item',
			dir: 'horiz',
			size: 1,
			duration: 0.5
		}, options);
		this.items = this.container.select(this.options.cssItem);
		this.cancelClick = function (evt) {
			evt = evt || window.event;
			var target = Event.element(evt);
			if (target)	target.blur();
			return false;
		};
		this.current = 0;
		this.scrolling = false;
		this.normalize();
		this.hUpLeft.onclick = this.cancelClick;
		this.hDownRight.onclick = this.cancelClick;
		this.hUpLeft.observe('click', this.scrollUpLeft.bindAsEventListener(this));
		this.hDownRight.observe('click', this.scrollDownRight.bindAsEventListener(this));
		this.container.fire('best:load');
	},
	normalize: function () {
		if (this.scrolling) return;
		this.container.absolutize();
		this.container.setStyle({'float': 'none'});
		var lastX = 0, lastY = 0; 
		this.items.each(function (item) {
			var dims = item.getDimensions();
			item.setStyle({position: 'absolute', top: lastY + 'px', left: lastX + 'px'});
			lastX += this.options.dir == 'horiz' ? dims.width : 0;
			lastY += this.options.dir == 'vert' ? dims.height : 0;
		}.bind(this));
		if (lastX > 0) {
			this.container.setStyle({width: lastX + this.clipper.getWidth() + 'px'});
		}
		if (lastY > 0) {
			this.container.setStyle({height: lastY + this.clipper.getHeight() + 'px'});
		}
		this.current = 0;
	},
	getCumulativeScroll: function (fromItem, toItem) {
		var scroll = {x: 0, y: 0};
		for (var k = fromItem; k < toItem; k++) {
			var dims = this.items[k].getDimensions();
			scroll.x += this.options.dir == 'horiz' ? dims.width : 0;
			scroll.y += this.options.dir == 'vert' ? dims.height : 0;
		}
		return scroll;
	},
	scrollUpLeft: function () {
		if (this.scrolling) return;
		this.scrolling = true;
		var next = Math.max(this.current - this.options.size, 0);
		var position = this.container.positionedOffset();
		var scroll = this.getCumulativeScroll(next, this.current);
		if (scroll.x || scroll.y) {
			new Effect.Move(this.container, {x: position.left + scroll.x, y: position.top + scroll.y, mode: 'absolute',
				duration: this.options.duration,
				afterFinish: function () {this.scrolling = false;}.bind(this)
			});
		} else {
			this.scrolling = false;
		}
		this.current = next;
	},
	scrollDownRight: function () {
		if (this.scrolling) return;
		this.scrolling = true;
		var next = Math.min(this.current + this.options.size, this.items.length - 1);
		var position = this.container.positionedOffset();
		var scroll = this.getCumulativeScroll(this.current, next);
		if (scroll.x || scroll.y) {
			new Effect.Move(this.container, {x: position.left - scroll.x, y: position.top - scroll.y, mode: 'absolute',
				duration: this.options.duration,
				afterFinish: function () {this.scrolling = false;}.bind(this)
			});
		} else {
			this.scrolling = false;
		}
		this.current = next;
	}
});

window.best.BlockTip = Class.create({
	initialize: function (target, tipbox, options) {
		this.target = $(target);
		this.tipbox = $(tipbox)
		this.options = Object.extend({
			opacity: 0.8,
			align: 'bottom'
		}, options);
		this.normalize();
		this.target.observe('mouseover', this.showTip.bindAsEventListener(this));
		this.target.observe('mouseout', this.hideTip.bindAsEventListener(this));
		this.tipbox.observe('mouseout', this.hideTip.bindAsEventListener(this));
	},
	normalize: function () {
		var parent = $(this.target.parentNode);
		var width = this.target.getWidth();
		parent.appendChild(this.tipbox);
		switch(this.options.align) {
			case 'top':
				this.tipbox.setStyle({position: 'absolute', top: 0, left: 0, zIndex: 20000, width: width + 'px', opacity: this.options.opacity});
				break;
			case 'bottom':
				this.tipbox.setStyle({position: 'absolute', bottom: 0, left: 0, zIndex: 20000, width: width + 'px', opacity: this.options.opacity});
				break;
		}
		this.tipbox.hide();
		this.visible = false;
	},
	showTip: function (event) {
		var evt = event || window.event;
		if (!evt || this.visible) return;
		var el = Event.element(evt);
		var rel = evt.relatedTarget || evt.fromElement;
		this.tipbox.setOpacity(0)
		this.tipbox.show();
		new Effect.Opacity(this.tipbox, {to: this.options.opacity, duration: 0.5,
			afterFinish: function () {
				this.tipbox.fire('best:afterShow', {kind: 'tip'});
			}.bind(this)
		});
		this.visible = true;
	},
	hideTip: function (event) {
		var evt = event || window.event;
		if (!evt || !this.visible) return;
		var el = Event.element(evt);
		var rel = evt.relatedTarget || evt.toElement;
		if (rel && rel != this.target && rel != this.tipbox && !rel.descendantOf(this.tipbox) && !rel.descendantOf(this.target)) {
			this.tipbox.hide();
			this.visible = false;			
		}
	}
});


window.best.Accordion = Class.create({
	initialize: function(container, options) {
		this.container = $(container);
		this.options = Object.extend({
			duration: 1,
			classNames: {
				toggle: 'accordion-toggle',
				toggleActive: 'accordion-toggle-active',
				content: 'accordion-content'
			},
			defaultSize: {
				height: null,
				width: null
			},
			direction: 'vertical',
			onEvent: 'click'
		}, options);
		this.showAccordion = null;
		this.currentAccordion = null;
		this.duration = null;
		this.effects = [];
		this.animating = false;

		var accordions = $$('#'+container+' .'+this.options.classNames.toggle);
		accordions.each(function(accordion) {
			Event.observe(accordion, this.options.onEvent, this.activate.bind(this, accordion), false);
			if (this.options.onEvent == 'click') {accordion.onclick = function() {return false;};}

			var options = (this.options.direction == 'horizontal') ? {width: '0px'} : {height: '0px'};  
			options.display = 'none';			
			this.currentAccordion = $(accordion.next(0)).setStyle(options);			
		}.bind(this));
	},
	
	activate : function(accordion) {
		if (this.animating) return false;
		
		this.effects = [];
	
		this.currentAccordion = $(accordion.next(0));
		this.currentAccordion.setStyle({display: 'block'});		
		
		this.currentAccordion.previous(0).addClassName(this.options.classNames.toggleActive);

		this.scaling = (this.options.direction == 'horizontal') ? {scaleX: true, scaleY: false} : {scaleX: false, scaleY: true};
		
		if (this.currentAccordion == this.showAccordion) {
		  this.deactivate();
		} else {
		  this._handleAccordion();
		}
	},

	deactivate : function() {
		var options = {
			duration: this.options.duration,
			scaleContent: false,
			queue: {
				position: 'end', 
				scope: 'accordionAnimation'
			},
			scaleMode: { 
				originalHeight: this.options.defaultSize.height ? this.options.defaultSize.height : this.currentAccordion.scrollHeight,
				originalWidth: this.options.defaultSize.width ? this.options.defaultSize.width : this.currentAccordion.scrollWidth
			},
			afterFinish: function() {
				this.showAccordion.setStyle({height: '', display: 'none'});				
				this.showAccordion = null;
				this.animating = false;
			}.bind(this)
		};
	    
	    Object.extend(options, this.scaling);

    	this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
    
		new Effect.Scale(this.showAccordion, 0, options);
	},

	_handleAccordion : function() {
		var options = {
			sync: true,
			scaleFrom: 0,
			scaleContent: false,
			scaleMode: { 
				originalHeight: this.options.defaultSize.height ? this.options.defaultSize.height : this.currentAccordion.scrollHeight,
				originalWidth: this.options.defaultSize.width ? this.options.defaultSize.width : this.currentAccordion.scrollWidth
			}
		};
		Object.extend(options, this.scaling);
		
		this.effects.push(new Effect.Scale(this.currentAccordion, 100, options));

		if (this.showAccordion) {
			this.showAccordion.previous(0).removeClassName(this.options.classNames.toggleActive);
			
			options = {
				sync: true,
				scaleContent: false
			};
			Object.extend(options, this.scaling);
			
			this.effects.push(new Effect.Scale(this.showAccordion, 0, options));				
		}
		
    	new Effect.Parallel(this.effects, {
			duration: this.options.duration, 
			queue: {position: 'end', scope: 'accordionAnimation'},
			beforeStart: function() {
				this.animating = true;
			}.bind(this),
			afterFinish: function() {
				if (this.showAccordion) {
					this.showAccordion.setStyle({display: 'none'});				
				}
				$(this.currentAccordion).setStyle({height: ''});
				this.showAccordion = this.currentAccordion;
				this.animating = false;
			}.bind(this)
		});
	}
});

Event.observe(window, 'load', function () {
	// Dropdown
	var menuHeaders = $('top-menu').firstDescendant().childElements();
	menuHeaders.each(function (li) {
			li.onmouseover = function () {li.addClassName('over')};
			li.onmouseout = function () {li.removeClassName('over')};
			li.firstDescendant().onclick = function () {return false;};
		}		
	)
	// Buttons
	var buttons = $$('input.button');
	buttons.each(function (b) {
		b.onmouseover = function () {b.className = 'button-over'};
		b.onmouseout = function () {b.className = 'button'};
	});
});

window.best.cacheImages(
	['/images/top-myaccount.jpg'],
	['/images/top-contactus.jpg'],
	['/images/top-livehelp.jpg'],
	['/images/english.jpg'],
	['/images/german.jpg'],
	['/images/spanish.jpg'],
	['/images/english-f2.jpg'],
	['/images/german-f2.jpg'],
	['/images/spanish-f2.jpg'],
	['/images/tm-header-f2.jpg'],
	['/images/button-f2.jpg'],
	['/images/arrow1.gif'],
	['/images/arrow2.gif']
)
