/**
 * Javascript-Functions - rt-gruppe.de
 * (c) CLICKSPORTS DIGITAL SOLUTIONS
 * http://www.clicksports.de
 * 
 * $Rev: 1111 $
 * $Author: cs $
 * $Date: 2010-02-17 19:35:52 +0100 (Mi, 17 Feb 2010) $
 */

document.observe("dom:loaded", function() {

	createExternalLinks();
	createJumpMenu('jumpable');
	$$('input.clearonfocus').each(function(f) { new emptyFormField(f); });

	new ProtoFish('navigation', 2000, 'hover', false, true, false);
	showMapToolTips();
});

window.onerror = function() { return true; }

/**
 * Create a jumpmenu for selects
 * 
 * @param {string} className
 */
function createJumpMenu(className) {
	
	// Get all elements and assing an new eventlistener on them
	$$('select.' + className).each(function(jumpmenu) {
		
		Event.observe(jumpmenu, 'change', function(e) {
			
			jump_value = Event.element(e).value;

			if(jump_value != "") {

				location = jump_value;
			}
		});
	});
}

/**
 * Create a new teaser file
 * 
 * @param {Element} elm Root element
 * @param {Object} articles Teaser objects as json representation
 */
var ClicksportsTeaser = Class.create({

	opt: {
		path: 'files/',
		interval: 10,
		duration: 4
	},

	/**
	 * @constructor
	 * @return {Object} ClicksportsTeaser
	 */
	initialize: function(elm, articles) {
		
		if(
			!(this.elm = $(elm)) ||
			!(this.wrapper = $(elm).down('div')) ||
			!(this.txtwrapper = $(elm).down('div div'))
		) return false;
		
		// Init needed stuff
		this.articles = articles;

		this.counter = 0;
		this.initDom().initListeners().initInterval();

		return this;
	},
	
	/**
	 * Initialize needed dom nodes
	 * 
	 * @return {Object} ClicksportsTeaser
	 */
	initDom: function() {
		
		this.prevBtn = new Element('span', { 'id': 'teaser-prev' }).hide();
		this.nextBtn = new Element('span', { 'id': 'teaser-next' }).hide();
		
		this.elm.insert(this.prevBtn).insert(this.nextBtn);
		
		return this;
	},
	
	/**
	 * Initialize dom listeners
	 * 
	 * @return {Object} ClicksportsTeaser
	 */
	initListeners: function() {
		
		this.elm.observe('mouseout', this.hideButtons.bind(this));
		this.elm.observe('mouseover', this.showButtons.bind(this));

		this.prevBtn.observe('click', this.showPrevious.bindAsEventListener(this));
		this.nextBtn.observe('click', this.showNext.bindAsEventListener(this));

		this.txtwrapper.observe('click', this.getArticle.bind(this)).setStyle({ 'cursor': 'pointer' });

		// Unload stuff because of memory leaking
		window.onbeforeunload = function() { this.stopInterval(); }.bind(this);

		return this;
	},
	
	/**
	 * Hide buttons
	 * 
	 * @param {Object} e Event
	 * @return {Object} ClicksportsTeaser
	 */
	hideButtons: function(e) {
		
		this.initInterval();
		[this.prevBtn, this.nextBtn].invoke('hide');
		return this;
	},

	/**
	 * Show buttons
	 * 
	 * @param {Object} e Event
	 * @return {Object} ClicksportsTeaser
	 */
	showButtons: function(e) {
		
		this.stopInterval();
		[this.prevBtn, this.nextBtn].invoke('show');
		return this;
	},
	
	/**
	 * Initialize the interval
	 * 
	 * @return {Object} ClicksportsTeaser
	 */
	initInterval: function() {
		
		if(this.interval !== undefined) this.stopInterval();
		this.interval = new PeriodicalExecuter(function() { this.showNext(); }.bind(this), this.opt.interval);
		
		return this;
	},
	
	/**
	 * Remove the interval
	 * 
	 * @return {Object} ClicksportsTeaser
	 */
	stopInterval: function() {
		
		if(this.interval !== undefined) this.interval.stop();
		return this;
	},
	
	/**
	 * Get next available record 
	 * 
	 * @return this
	 */
	next: function() {
		
		this.lastcounter = this.counter;
		if(this.counter == this.articles.length-1) this.counter = 0;
		else this.counter++;
		return this;		
	},
	
	/**
	 * Get previous available record
	 * 
	 * @return this
	 */
	previous: function() {

		this.lastcounter = this.counter;
		if (this.counter == 0) this.counter = (this.articles.length - 1);
		else this.counter--;
		return this;
	},
	
	/**
	 * Show the previous image
	 * 
	 * @param {Object} e
	 * @return this
	 */
	showPrevious: function(e) { this.previous().updateTeaser(); return this; },

	/**
	 * Show the next image
	 * 
	 * @param {Object} e
	 * @return this
	 */
	showNext: function(e) { this.next().updateTeaser(); return this; },
	
	/**
	 * Update the teaser with text and images
	 * 
	 * @return this
	 */
	updateTeaser: function() {
		
		var activeArticle = this.articles[this.counter];

		// Get the old image
		var oldImages = this.wrapper.select('img');
		var oldImage = oldImages[0];

		// Get the new image
		var image = new Element('img');
		var src = activeArticle.img;
		image.writeAttribute({ 'src': this.opt.path + src }).hide();
		this.wrapper.insert(image);

		var dim = this.txtwrapper.getDimensions();
		var height = dim.height;

		// Transform images and switch text.
		// Note that we need to use two different aproaches, as IE can not handle transparency changes with png32
		if(!Prototype.Browser.IE) {

			new Effect.Parallel([
				
				new Effect.Morph(this.txtwrapper, { sync: true, style: 'bottom: -' + height + 'px' }),
				new Effect.Fade(this.txtwrapper, { sync: true }),
				new Effect.Fade(oldImage, { sync: true }),
				new Effect.Appear(image, { sync: true })
			], {
				duration: this.opt.duration,
				afterFinish: function() {
					
					// Move textwrapper so we can move it back in
					var dim = this.txtwrapper.getDimensions();
					this.txtwrapper.setStyle({ 'bottom': '-' + dim.height + 'px' });
					
					// Remove the old image (only if it exists)
					if($(oldImage) !== null) oldImage.remove();
					
					// Write new content to our div
					text = '<h1>' + activeArticle.title + '</h1>';
					text += '<h2>' + activeArticle.desc + '</h2>';
					this.txtwrapper.update(text);
	
					new Effect.Parallel([
						new Effect.Morph(this.txtwrapper, { sync: true, style: 'bottom: 0px' }),
						new Effect.Appear(this.txtwrapper, { sync: true })				
					], {
						duration: 3
					});
	
	
				}.bind(this)
			});
		} else {

			new Effect.Parallel([
				
				new Effect.Morph(this.txtwrapper, { sync: true, style: 'bottom: -' + height + 'px' }),
				new Effect.Fade(oldImage, { sync: true }),
				new Effect.Appear(image, { sync: true })
			], {
				duration: this.opt.duration,
				afterFinish: function() {
					
					// Move textwrapper so we can move it back in
					var dim = this.txtwrapper.getDimensions();
					this.txtwrapper.setStyle({ 'bottom': '-' + dim.height + 'px' });
					
					// Remove the old image (only if it exists)
					if($(oldImage) !== null) oldImage.remove();
					
					// Write new content to our div
					text = '<h1>' + activeArticle.title + '</h1>';
					text += '<h2>' + activeArticle.desc + '</h2>';
					this.txtwrapper.update(text);
	
					new Effect.Morph(this.txtwrapper, { style: 'bottom: 0px', duration: 3 });
				}.bind(this)
			});
		}

		return this;
	},
	
	/**
	 * Linkt to the active article
	 * 
	 * @param {Object} e Event
	 * @return this
	 */
	getArticle: function(e) {
		
		var activeArticle = this.articles[this.counter];
		if(activeArticle === undefined) return false;
		
		document.location.href=activeArticle.link;
		
		return this;
	}
});

/**
 * Show tooltips for maps
 */
function showMapToolTips() {
	
	if($('location_map') === null) return;
	
	var elms = $('location_map').select('li');
	elms.each(function(l) {
		
		var ele = l.down('span');
		var text = ele.innerHTML;
		ele.update();
		
		new Tip(l, text);
	});
}

/**
 * Create external links for all elements on the page with rel set
 */
function createExternalLinks() {

	$$('a').each(function(l) { if(l.rel == 'external') l.writeAttribute({ 'target': '_blank' }); });
}

/**
 * Class to autoempty fields
 *
 * @see function::init
 * @param {Object} elm
 */
var emptyFormField = Class.create({
	
	initialize: function(elm) {

		this.elm = $(elm);
		this.oldValue = this.elm.value;
		
		this.elm.observe('click', function(e) {
			val = Event.element(e);
			if(val.value == this.oldValue) val.value='';
		}.bindAsEventListener(this));

		elm.observe('blur', function(e) {
			val = Event.element(e);
			if(val.value.length == 0) val.value=this.oldValue;
		}.bindAsEventListener(this));
	}
});

/**
 * Old way to autoempty
 * 
 * @see {Object} emptyFormField
 * @deprecated
 */
/*init = function (){
if ($$('.clearonfocus')){
	$$('.clearonfocus').map( function(element){
		element.observe('click', function(event){
			
			var element = Event.element(event);
			element.removeClassName('clearonfocus');
			element.writeAttribute('value', '');
			});
		});
	}
}
Event.observe(window, 'load', init, false);*/
