Ext.onReady(function() {

	Ext.namespace('SpamExperts');

	/**
	 * Carousel for latest news. Code adopted from Ext Core example
	 */
	SpamExperts.Carousel = Ext.extend(Ext.util.Observable, {
	    activeSlide: 0,
		els: {
			navNext: null,
			navPrev: null,
			slidesWrap: null
		},
		interval: 3,
		itemSelector: 'li',
		transitionDuration: 1,
		transitionEasing: 'easeOut',
		transitionType: 'carousel',
		wrap: false,

		constructor: function(elId, config) {
			config = config || {};
			Ext.apply(this, config);

			this.el = Ext.get(elId);
			this.slides = [];

			this.initMarkup();
			this.initEvents();

			if(this.carouselSize > 0) {
				this.refresh();
			}
		},

		initMarkup: function() {
			this.carouselSize = 0;

			// set the dimensions of the container
			this.slideWidth = this.els.slidesWrap.getWidth(true);
			this.slideHeight = this.els.slidesWrap.getHeight(true);

			this.el.select(this.itemSelector).each(function(item) {
				this.slides.push(item);
				item.setWidth(this.slideWidth + 'px').setHeight(this.slideHeight + 'px');
			}, this);
			this.carouselSize = this.slides.length;
			this.el.clip();
		},

		initEvents: function() {
			this.els.navPrev.on('click', function(ev) {
				ev.preventDefault();
				var target = ev.getTarget();
				target.blur();
				if (Ext.fly(target).hasClass('ux-carousel-nav-disabled')) {
					return;
				}
				this.prev();
			}, this);

			this.els.navNext.on('click', function(ev) {
				ev.preventDefault();
				var target = ev.getTarget();
				target.blur();
				if (Ext.fly(target).hasClass('ux-carousel-nav-disabled')) {
					return;
				}
				this.next();
			}, this);

		},

		prev: function() {
			this.setSlide(this.activeSlide - 1);
		},

		next: function() {
			this.setSlide(this.activeSlide + 1);
		},

		refresh: function() {
			this.carouselSize = this.slides.length;
			this.el.setWidth((this.slideWidth * this.carouselSize) + 'px');
			if (this.carouselSize > 0) {
				this.activeSlide = 0;
				this.setSlide(0, true);
			}
			return this;
		},

		setSlide: function(index, initial) {
			if (!this.wrap && !this.slides[index]) {
				return;
			}
			else if(this.wrap) {
				if (index < 0) {
					index = this.carouselSize-1;
				}
				else if (index > this.carouselSize-1) {
					index = 0;
				}
			}
			if(!this.slides[index]) {
				return;
			}

			var offset = index * this.slideWidth;
			if (!initial) {
				switch (this.transitionType) {
					case 'fade':
						this.slides[index].setOpacity(0);
						this.slides[this.activeSlide].stopFx(false).fadeOut({
							duration: this.transitionDuration / 2,
							callback: function(){
								this.el.setStyle('left', (-1 * offset) + 'px');
								this.slides[this.activeSlide].setOpacity(1);
								this.slides[index].fadeIn({
									duration: this.transitionDuration / 2
								});
							},
							scope: this
						})
						break;

					default:
						var xNew = (-1 * offset) + this.els.slidesWrap.getX();
						this.el.stopFx(false);
						this.el.shift({
							duration: this.transitionDuration,
							x: xNew,
							easing: this.transitionEasing
						});
						break;
				}
			}
			else {
				this.el.setStyle('left', '0');
			}

			this.activeSlide = index;
		}
	});

	/**
	 * Creates a rollover menu. Required config items:
	 *	- itemSelector
	 *	- menuElement
	 * 	- triggerElement
	 */
	SpamExperts.MenuRollover = Ext.extend(Ext.util.Observable, {
		originalHeight: null,
		overMenuItem: null,
		triggerElement: null,

		/**
		 * Creates an instance of this class.
		 *
		 * @param	object	config
		 * @return	void
		 */
		constructor: function() {
			// Initialize elements
			this.triggerElement = Ext.get('top-menu-items');

			// Initialize the menu
			var topMenuItems = this.triggerElement.select('li.top-menu-item');
			topMenuItems.each(function(item) {
				var itemId = item.getAttribute('id');
				var el = Ext.get(itemId);
				el.hover(this.menuOver, this.menuOut, this, { itemId: itemId });
				if (el.hasClass('top-menu-item-active')) {
					// Reposition and show the submenu for the active page
					var sub = item.select('div.top-menu-sub');
					sub.each(function(subEl) {
						subEl.setStyle('display', 'block');
						subEl.setX(topMenu.getX());
					});
				}
			}, this);
			
		},
		
		menuOver: function(event, element, options) {
			if (this.overMenuItem == null) {
				var topmenu = Ext.get('top-menu');
				this.originalHeight = topmenu.getHeight();
				topmenu.setHeight(350);
				// Top element
				var el = Ext.get(options.itemId);
				if (!el.hasClass('top-menu-item-active')) {
					el.addClass('top-menu-item-current');
					// Submenu
					el.select('div.top-menu-sub').each(function(item) {
						item.addClass('top-menu-sub-current');
					});
					// Top item hover
					el.select('a.top-menu-item-level-1').each(function(item) {
						item.addClass('top-menu-item-level-1-hover');
					});
	
					this.overMenuItem = el;
				}
			}
		},
		
		menuOut: function(event, element, options) {
			if (this.overMenuItem != null) {

				Ext.get('top-menu').setHeight(this.originalHeight);
				
				// Submenu
				var subMenu = this.overMenuItem.select('div.top-menu-sub').item(0);

				subMenu.removeClass('top-menu-sub-current');
				
				this.overMenuItem.removeClass('top-menu-item-current');
				
				// Top item hover
				this.overMenuItem.select('a.top-menu-item-level-1').each(function(item){
					item.removeClass('top-menu-item-level-1-hover');
				});
				this.overMenuItem = null;
			}
		}
	});


	function initLatestNews() {
		if (Ext.get('latest-news')) {
			new SpamExperts.Carousel('latest-news-list', {
				els: {
					navNext: Ext.get('latest-news-next'),
					navPrev: Ext.get('latest-news-prev'),
					slidesWrap: Ext.get('latest-news-list-carousel')
				}
			});
		}
	}
	
	function initLiveChat() {
	Ext.lib.Ajax.useDefaultXhrHeader = false;
	Ext.Ajax.request({
             	      url : '/livesupport/status.php',
                      method: 'GET',
			callback: function(opt,success,responseObj) {			
			    if (success) {
			    	if( responseObj.responseText.length < 50 )
			    	{
			    		document.getElementById('next-steps-live-chat').innerHTML = responseObj.responseText;
			    	}
                            }
                        }
           });	
	}
	

	function initBottomMenu() {
		var menu = Ext.get('bottom-menu');
		if (menu != null) {
			var items = menu.select('li');
			var prev = null, processed = false;
			items.each(function(item) {
				if (!processed) {
					if (prev != null) {
						if (item.hasClass('current')) {
							prev.addClass('previous');
							processed = true;
						}
						else if (item.hasClass('last-current')) {
							prev.addClass('previous-last');
							processed = true;
						}
					}
					prev = Ext.get(item.getAttribute('id'));
				}
			});
		}
	}

	SpamExperts.Popup = new Ext.extend(Ext.util.Observable, {
		isOver: false,
		popupEl: null,
		triggerEl: null,
		
		constructor: function(config) {
			this.triggerEl = Ext.get(config.triggerId);
			if (this.triggerEl) {
				this.popupEl = Ext.get(config.popupId);
				this.triggerEl.hover(this.showPopup, this.hidePopup, this);
			}
		},
		
		hidePopup: function(event, element) {
			if (this.isOver) {
				this.popupEl.setStyle('display', 'none');
				this.isOver = false;
			}
		},

		showPopup: function(event, element) {
			if (!this.isOver) {
				this.popupEl.setStyle('display', 'block');
				this.isOver = true;
			}
		}
		
	});

	function showBookmarks() {
		Ext.get('bookmark-links').setStyle('display', 'block');
	}

	function hideBookmarks() {
		Ext.get('bookmark-links').setStyle('display', 'none');
	}

	function initBookmarks() {
		var el = Ext.get('bookmark');
		if (el != null) {
			el.on('mouseover', showBookmarks);
			el.on('mouseout', hideBookmarks);
		}
	}

	function showLanguage() {
		Ext.get('language-popup').setStyle('display', 'block');
	}

	function hideLanguage() {
		Ext.get('language-popup').setStyle('display', 'none');
	}

	function initLanguage() {
		var el = Ext.get('language');
		if (el != null) {
			el.on('mouseover', showLanguage);
			el.on('mouseout', hideLanguage);
		}
	}

	function fixTopImage() {
		var el = Ext.get('subpage-image');
		if (el != null) {
			var image = el.child('img');
			if (image != null) {
				var src = image.getAttribute('src');
				el.setStyle('background-image', 'url(' + src + ')');
				image.setStyle('visibility', 'hidden');
			}
		}
	}

	// Main script block
	//initBookmarks();
	//initLanguage();
	initLiveChat();
	initLatestNews();
//	initMenu();
	new SpamExperts.MenuRollover();
	new SpamExperts.Popup({
		popupId: 'bookmark-links',
		triggerId: 'bookmark'
	});
	new SpamExperts.Popup({
		popupId: 'language-popup',
		triggerId: 'language'
	});
	
//	if (Ext.isIE) {
		// MSIE fires false mouseout when going over absolutly positioned elements
//		fixTopImage();
//	}
	initBottomMenu();
});

function doBookmark(urlFormat) {
	var location = document.location.href;
	var title = document.title;
	if (arguments.length == 1 || arguments[1]) {
		location = escape(document.location.href);
		title = escape(document.title);
	}
	var url = String.format(urlFormat, location, title);
	window.open(url, 'bookmark');
}

function bookmarkThisPage(link) {
	switch (link.id) {
		case 'delicious':
			doBookmark('http://del.icio.us/post?url={0}&title={1}');
			break;
		case 'digg':
			doBookmark('http://digg.com/submit?url={0}&title={1}');
			break;
		case 'facebook':
			doBookmark('http://facebook.com/share.php?u={0}&t={1}');
			break;
		case 'newsvine':
			doBookmark('http://newsvine.com/_wine/save/popoff=0&url={0}&title={1}');
			break;
		case 'reddit':
			doBookmark('http://reddit.com/submit?url={0}&title={1}');
			break;
		case 'stumbleupon':
			doBookmark('http://stumbleupon.com/submit?url={0}&title={1}');
			break;
		case 'technorati':
			doBookmark('http://technorati.com/faves?add={0}&title={1}');
			break;
		case 'twitter':
			doBookmark('http://twitter.com/home?status={0} {1}', false);
			break;
		case 'yahoo-buzz':
			doBookmark('http://buzz.yahoo.com/submit/?submitUrl={0}&submitHeadline={1}');
			break;
	}
}
