
// rotating content container...requires prototype & scriptaculous
var protoaculous_included = (typeof Prototype != 'undefined' && typeof Scriptaculous != 'undefined');
if (protoaculous_included) {

	var rccCurrentlyAnimating = false;

	function rotatingContentContainerInit() {
		var contentDiv = $('contentCentre');
		if (!contentDiv) contentDiv = $('contentFull');
		if (!contentDiv) return;

		var rotatingContentContainers = $$('div.rotatingContentContainer');
		if (rotatingContentContainers) rotatingContentContainers.each(function(rCC) {
			if (rCC.hasClassName('multipleItemsDisplay'))
				new rotatingContentContainer_multipleItems(rCC);
			else if (!rCC.hasClassName('rotation_mode_none'))
				new rotatingContentContainer(rCC);
		});
	}

	function rememberTabInCookie(groupId, handleNum) {
		if(typeof Cookie != 'undefined') {
			var cookie = new Cookie('containerSelTab', null);

			var regex = new RegExp("g"+groupId+"-(\\d+)#");
			var val = cookie.getValue();
			var newVal = 'g'+groupId+'-'+handleNum+'#';
			if(val == null) { val = ''; }
			if(val.match('g'+groupId+'-(\\d+)#')) {
				val = val.replace(regex, newVal);
			} else {
				val += newVal;
			}
			cookie.setValue(val, false);
		}
	}

	rotatingContentContainer_multipleItems = Class.create({
		initialize: function(ele) {
			this.ele = ele;
			this.items = ele.select('.rotatingContentContainerListItem');
			if (this.items.length < 2) return;

			// assuming all items are equal in size and spacing to each other
			this.stepSize = this.items[1].positionedOffset().left - this.items[0].positionedOffset().left;
			this.itemsAtOnce = Math.round(this.ele.down('.rotatingContentContainerListWrapper').getWidth() / this.stepSize);

			this.elementContainer = this.ele.down('.rotatingContentContainerList');
			this.elementContainer.setStyle({width: this.stepSize * this.items.length + 'px'});

			this.changeOnMouseOver = this.ele.hasClassName('changeOnMouseOver');

			if (this.ele.down('.rotatingContentContainerHandles_buttons')) {
				if (this.ele.down('.buttonHandle_back')) {
					this.ele.down('.buttonHandle_back').setStyle({cursor: 'pointer'});
					Event.observe(this.ele.down('.buttonHandle_back'), (this.changeOnMouseOver ? 'mouseover' : 'click'), this.btnBackClick.bindAsEventListener(this));
				}
				if (this.ele.down('.buttonHandle_next')) {
					this.ele.down('.buttonHandle_next').setStyle({cursor: 'pointer'});
					Event.observe(this.ele.down('.buttonHandle_next'), (this.changeOnMouseOver ? 'mouseover' : 'click'), this.btnNextClick.bindAsEventListener(this));
				}
			}

			this.buttonEnableDisable();
		},

		btnBackClick: function() {
			if (this.elementContainer.positionedOffset().left >= this.items[0].positionedOffset().left) return;

			var xStep = Math.min(this.items[0].positionedOffset().left - this.elementContainer.positionedOffset().left, this.stepSize);
			new Effect.Move(this.elementContainer, {
                x: xStep,
                duration: 1,
                queue: {scope: 'rotatingContentContainer_multiple', limit: 1},
                afterFinish: this.buttonEnableDisable.bindAsEventListener(this)
            });
		},
		btnNextClick: function() {
			if (this.elementContainer.positionedOffset().left <= -this.stepSize * (this.items.length - this.itemsAtOnce)) return;

			var xStep = Math.min(this.stepSize * (this.items.length - this.itemsAtOnce) + this.elementContainer.positionedOffset().left, this.stepSize);
			new Effect.Move(this.elementContainer, {
                x: -xStep,
                duration: 1,
                queue: {scope: 'rotatingContentContainer_multiple', limit: 1},
                afterFinish: this.buttonEnableDisable.bindAsEventListener(this)
            });
		},
		buttonEnableDisable: function() {
			if (this.ele.down('.buttonHandle_back')) {
				if (this.elementContainer.positionedOffset().left >= this.items[0].positionedOffset().left)
					this.ele.down('.buttonHandle_back').addClassName('buttonHandle_disabled');
				else
					this.ele.down('.buttonHandle_back').removeClassName('buttonHandle_disabled');
			}
			if (this.ele.down('.buttonHandle_next')) {
				if (this.elementContainer.positionedOffset().left <= -this.stepSize * (this.items.length - this.itemsAtOnce))
					this.ele.down('.buttonHandle_next').addClassName('buttonHandle_disabled');
				else
					this.ele.down('.buttonHandle_next').removeClassName('buttonHandle_disabled');
			}
		}
	});

	rotatingContentContainer = Class.create({
		initialize: function(ele) {
			this.ele = ele;
			this.activeItem = 0;
			this.handleType = 'tabs';
			this.isAutoRotate = false;
			this.autoRotateSeconds = 5;  // default
			this.rememberTabInCookie = false;

			// check for config
			if (this.ele.className) {
				var classNames = this.ele.className.split(' ');
				for (var i = 0; i < classNames.length; ++i) {
					if (classNames[i].match(/^autoRotate$/))
						this.isAutoRotate = true;
					if (classNames[i].match(/^rememberSelectedTab_.+$/)) {
						this.rememberTabInCookie = true;
						this.groupId = classNames[i].gsub(/^rememberSelectedTab_(.+)/, '#{1}');
					}
					if (classNames[i].match(/^autoRotateSeconds_\d+$/))
						this.autoRotateSeconds = parseInt(classNames[i].gsub(/^autoRotateSeconds_(\d+)/, '#{1}'));
					if (classNames[i].match(/^animationType_.+$/))
						this.animationType = classNames[i].gsub(/^animationType_(.+)/, '#{1}');
					if (classNames[i].match(/^rccCollapsable$/)) {
						this.collapseHandle = this.ele.down('.rotatingContentContainerPreSection');
						this.collapseContent = this.ele.down('.rotatingContentContainerListWrapper');
						if (this.collapseHandle && this.collapseContent)
							this.isCollapsable = true;
					}
				}
			}
			if (this.ele.down('.rotatingContentContainerHandles_buttons')) this.handleType = 'buttons';

			// register periodic function to auto rotate content
			if (this.isAutoRotate)
				this.pe_autoRotate = new PeriodicalExecuter(this.showNext.bindAsEventListener(this), this.autoRotateSeconds);

			this.changeOnMouseOver = this.ele.hasClassName('changeOnMouseOver');

			// register click event on handles
			var t = this;
			if (this.ele.down('.rotatingContentContainerHandles_tabs')) {
				var tabs = ele.select('.tabHandle div');
				if (tabs) tabs.each(function(tab) {
					tab.setStyle({cursor: 'pointer'});
					Event.observe(tab, (this.changeOnMouseOver ? 'mouseover' : 'click'), t.tabClick.bindAsEventListener(t));
				});
			}
			if (this.ele.down('.rotatingContentContainerHandles_buttons')) {
				if (this.ele.down('.buttonHandle_back')) {
					this.ele.down('.buttonHandle_back').setStyle({cursor: 'pointer'});
					Event.observe(this.ele.down('.buttonHandle_back'), (this.changeOnMouseOver ? 'mouseover' : 'click'), this.btnBackClick.bindAsEventListener(this));
				}
				if (this.ele.down('.buttonHandle_next')) {
					this.ele.down('.buttonHandle_next').setStyle({cursor: 'pointer'});
					Event.observe(this.ele.down('.buttonHandle_next'), (this.changeOnMouseOver ? 'mouseover' : 'click'), this.btnNextClick.bindAsEventListener(this));
				}
			}
			if (this.isCollapsable) {
				if (this.collapseContent.hasClassName('listWrapperClosed')) {
					this.collapseContent.hide();
					this.collapseContent.removeClassName('listWrapperClosed');
				}
				this.collapseHandle.setStyle({cursor: 'pointer'});
				Event.observe(this.collapseHandle, (this.changeOnMouseOver ? 'mouseover' : 'click'), this.collapseHandleClick.bindAsEventListener(this));
			}

			// remove "special" workaround for initial display:none styling
			var items = ele.select('.rotatingContentContainerListItem');
			for (var i = 0; i < items.length; ++i) {
				if (items[i].hasClassName('defaultItem')) this.activeItem = i+1;
				if (!items[i].hasClassName('defaultItem') && items.length > 1) items[i].hide();
	        	items[i].removeClassName('rccListItemSpecial');

	        	// register close-buttons for RCCs with "slide" mode
	        	if (this.animationType == 'slide') {
	        		var closeItems = items[i].select('.closeItem');
	        		if (closeItems) closeItems.each(function(closeItem){
	        			closeItem.setStyle({cursor: 'pointer'});
	        			Event.observe(closeItem, 'click', t.activateClose.bindAsEventListener(t));
	        		});
	        	}
			}

			this.itemCount = items.length;
		},

		showNext: function() {
			// used by auto rotate to show next item
			this.btnNextClick();
		},

		tabClick: function(evt) {
			if (!evt) return;

			// manual click = stop autorotate
			if (this.pe_autoRotate) this.pe_autoRotate.stop();

			// which number has been clicked?
			var clickedHandle = Event.element(evt).up('.tabHandle');
			var handleNum;
			if (clickedHandle.className) {
				clickedHandle.className.split(" ").each(function(v){
					if (v.match(/^handle\d+$/))
						handleNum = parseInt(v.gsub(/^handle(\d+)/, '#{1}'));
				});
			}

			// save the clicked tab in a cookie
			if(this.rememberTabInCookie) {
				rememberTabInCookie(this.groupId, handleNum);
			}

			// only react to same item click for sliding animation (others can't be "closed")
			if (this.animationType != 'slide' && this.activeItem == handleNum) return;

			this.changeItems(handleNum);
		},
		btnBackClick: function(evt) {
			// manual click = stop autorotate
			if (this.pe_autoRotate) this.pe_autoRotate.stop();

			this.changeItems(this.activeItem > 1 ? this.activeItem - 1 : this.itemCount);
		},
		btnNextClick: function(evt) {
			// manual click = stop autorotate
			if (typeof evt == 'object' && this.pe_autoRotate) this.pe_autoRotate.stop();

			this.changeItems(this.activeItem < this.itemCount ? this.activeItem + 1 : 1);
		},
		activateClose: function(evt) {
			if (!evt) return;
			var itemToClose = Event.element(evt).up('.rotatingContentContainerListItem');
			var itemToCloseNr;
			itemToClose.className.split(' ').each(function(v){
				// close item # where close-item was clicked
				if (v.match(/^item\d+$/))
					itemToCloseNr = v.gsub(/^item(\d+)/, '#{1}');
			});

			this.changeItems(itemToCloseNr);
		},

		changeItems: function(newItem) {
			if (!newItem) return;
			if (this.animationType == 'slide' && rccCurrentlyAnimating) return;   // don't allow more than 1 slide animation (breaks CSS)

			if (this.ele.down('.handle' + this.activeItem))
				this.ele.down('.handle' + this.activeItem).removeClassName('handleActive');

        	var items = this.ele.select('.rotatingContentContainerListItem');
        	var activeItem = this.activeItem;
        	var animationType = this.animationType;
        	if (items) items.each(function(item) {
        		var classNames = item.className.split(' ');
        		for (var i = 0; i < classNames.length; ++i) {
        			if (activeItem != newItem && classNames[i].match(new RegExp('item' + newItem + '$'))) {
        				switch (animationType) {
        					case 'fade':
        						new Effect.Appear(item, {duration: 0.7, queue: { position: 'end', scope: 'item' + newItem}});
        					break;

        					case 'slide':
        						rccCurrentlyAnimating = true;
        						new Effect.BlindDown(item, {duration: 0.7, queue: { position: 'end', scope: 'item' + newItem}, afterFinish: function() { rccCurrentlyAnimating = false; }});
        					break;
        				}
        			}
	        		if (classNames[i].match(new RegExp('item' + activeItem + '$'))) {
	        			switch (animationType) {
    						case 'fade':
    							new Effect.Fade(item, {duration: 0.7, queue: { position: 'end', scope: 'item' + activeItem}});
    						break;

    						case 'slide':
    							rccCurrentlyAnimating = true;
    							new Effect.BlindUp(item, {duration: 0.7, queue: { position: 'end', scope: 'item' + activeItem}, afterFinish: function() { rccCurrentlyAnimating = false; }});
    						break;
	        			}
	        		}
        		}
        	});
        	this.activeItem = (this.activeItem == newItem) ? 0 : newItem;

	        if (this.ele.down('.handle' + this.activeItem))
	        	this.ele.down('.handle' + this.activeItem).addClassName('handleActive');
		},

		collapseHandleClick: function(evt) {
			if (this.collapseHandle.hasClassName('collapsableOpened')) {
				this.collapseHandle.removeClassName('collapsableOpened');
				this.collapseContent.setStyle({height: 'auto'});
				new Effect.BlindUp(this.collapseContent, {duration: 0.5});
			} else {
				this.collapseHandle.addClassName('collapsableOpened');
				this.collapseContent.setStyle({height: 'auto'});
				new Effect.BlindDown(this.collapseContent, {duration: 0.5});
			}
		}
	});


	Event.observe(window, 'load', rotatingContentContainerInit);
}
