Slideshow.Collection = Slideshow.Fade.extend({			
	options: {
		dumpControls: function(slide) {
			
			var html = [], instance = 'Slideshow.instances[\''+this.identifier+'\']';
			html.push('<span id="slideshow-controls-previous" onmousedown="$E(event).stop();'+instance+'.previousSlide();">&laquo;</span>\n');
			html.push('<span id="slideshow-controls-play" onmousedown="$E(event).stop();'+instance+'.togglePlay(this)">&gt;</span>\n');
			html.push('<span id="slideshow-controls-next" onmousedown="$E(event).stop();'+instance+'.nextSlide()">&raquo;</span>');
			return html.join('');	
		},
		
		height: 300,
		autoPlay: false,
		leaveDelay: 800,
		enterDelay: 100,
		fitImg: true,
		interval: 4000,
		
		// Events
		onPlay: function(mode) 			{ $('slideshow-controls-play').addClass('paused');	},
		onStop: function(mode)		 	{ $('slideshow-controls-play').removeClass('paused');	},
		onLoadProgress: function(index) 			{ this.overlay.show();},		
		onChange: function(index, slide) 	{
			if(this.counter) {
				this.counter.setHTML( index + ' / ' + this.slides.length  + '');	
			}
		}
	},
	
	initialize : function(options) {
		
		//$('slideshow').setStyles({'width' : document.slides[0].width + 'px', 'height' : document.slides[0].height + 'px' });
		$('slideshow').setStyles({'width' : '600px', 'height' : document.slides[0].height + 'px' });
		
		this.setOptions(options);		
		
		return this.process(document.slides);
	},

	fetch: function() {
		new Ajax.RPC({}).send('media.GetCollection', this.collectionId, false, 1, 50, true).
		chain(this.process.bind(this));
		
		return this;
	},
	
	process: function(slides) {
		this.items = slides;
		
		this.slidesFromMedia= [];
		this.items.each(function(item, index) {
			this.slidesFromMedia.push($merge(item, {
				'img'	: item.img,
				'width'	: item.width,
				'height': item.height
			}));
		}, this);
				
		window.addEvent('DOMContentLoaded', this.loaded.bind(this) );
	},
	
	// To be called when DOM is ready
	// Practically replaces initialize
	loaded: function() {	
		$('slideshow').empty();
		// Call the initialize.parent to initialize
		
		this.initialize.parent.call(this, this.slidesFromMedia, $('slideshow'));	
		
		// this.overlay
		this.overlay  = $C('div', {
			'id'		: 'slideshow-overlay',
			'styles' 	: {
				'background' : 'url('+Core.path  + 'assets/css/slideshow/slideshow-collection-overlay.png)',
				'position'	 : 'absolute',
				'left'		: 0,
				'width' 	: '100%',
				'z-index'	: '9999999',
				'color'		: 'white',
				'padding'	: '10px 0',
				'margin'	: '10px 0 0 0'				
			}
		}).makeUnselectable();

		// this.controls
		
		this.controls = $C('div',{
			'id'		: 'slideshow-controls',
			'styles' 	: {
				'color'		: 'white',
				'z-index'	: '9999999'
			}
		}).
		setHTML(this.options.dumpControls()).
		makeUnselectable().
		injectIn(this.overlay);
		
		// this.counter
		this.counter= $C('div', {
			'id'		: 'slideshow-counter',
			'styles'	: {
				
			}
		}).
		setHTML('1 / '+this.slides.length).
		injectIn(this.overlay);
		
		// Handle spans
		this.controls.getElements('span').
		setOpacity(.5).
		addEvents({
			'mouseenter' : function() {
				this.setOpacity(.9);	
			},
			
			'mouseleave' : function() {
				this.setOpacity(.5);
			}
		});
		
		this.overlay.injectIn(this.element);
		this.overlay.hide().setBlockStyles();
		var bottom = -this.overlay.offsetHeight;
		this.overlay.restoreBlockStyles().setStyle('bottom', 0 );
		
	
		this.timerBounds 	= null;
		this.bound 			= {
			'mouseleave'	: function(event) {
				if(this.isPreloading) return this;

				$clear(this.timerBounds);
				this.timerBounds = this.controlsFx.start.bind(this.controlsFx, -this.overlay.offsetHeight).delay(this.options.leaveDelay);
			}.bind(this),
			
			'mouseenter'	: function(event) {
				if(this.isPreloading) return this;				
				$clear(this.timerBounds);
				this.timerBounds  = this.controlsFx.start.bind(this.controlsFx, 0).delay(this.options.enterDelay);
			}.bind(this)
		}
		
		// Not for now
		if(this.options.useWheel) {
			this.bound.mousewheel = function(event){
				if(this.isPreloading) {
					return this;								
				}
				event.stop();
				return this[(event.wheel < 0 ? 'next' : 'previous') + 'Slide']();
			}.bind(this)
		}

		
		this.controlsFx = new Fx.Style(this.overlay, 'bottom', {
			'duration'		: 700,
			'transition'	: Fx.Transitions.Quart.easeOut   
		});
		
	//	this.element.addEvents(this.bound);		
		
		PNGFix.fix(this.overlay);
	
		return this;				
	}

});

var Social = {
	
	showUsers : function(articleId) {
		
		new Ajax.RPC({
			onSuccess : function(res)	{
				
				var response = res.responseJSON;
				
				if(response.faultCode)
					return;
					
				Social.renderUsers(response);
			}
		}).send("social.GetArticleShares", parseInt(articleId), 1);
	},
	
	renderUsers : function(usersArray) {
		
		if(!usersArray)
			return;
			
		if(usersArray.length <= 0)
			return;
			
        this.overlay = new Overlay('', {
                'duration'      : 400,
                'className'     : 'social'
        });

		var html = [];
		
		html.push('<div class="overlay-window" id="team-overlay-window">');
		html.push('<div class="overlay-content" id="team-overlay-content">');
		html.push('<div class="overlay">');
		html.push('<h3>Το άρθρο άρεσε στους χρήστες <span onclick="Social.overlay.close();"><img src="http://c.pstatic.gr/img/act/nob/x.gif" alt="close" /></span></h3>');
		html.push('<div id="user-shares" class="overlay-body">');
		html.push('<ul class="users clr">');
		
		usersArray.each(function(value, key) {
			
			html.push('<li class="clr ' + (key == 0 ? 'top' : '') + (key == usersArray.length - 1 ? ' bottom' : '') + '">\n');
			
			html.push('<a class="left" href="http://me.pathfinder.gr/' + this.username + '">');
			html.push('<img class="img" src="' + this.avatars['48'] + '"/>');
			html.push('</a>');
			
			html.push('<div class="info">\n');
			html.push('<h5><a href="http://me.pathfinder.gr/' + this.username + '">' + this.username + '</a></h5>');
			html.push('<p>' + this.first_name + ' ' + this.last_name + '</p>');
			html.push('</div>');
			
			html.push('</li>\n');
		});	
		
		html.push('</ul>');
		html.push('</div>');	
		html.push('<div class="overlay-footer">');
		html.push('<input type="button" onclick="Social.overlay.close();" value="Κλείσιμο" class="button" />');
		html.push('</div>');	
		html.push('</div>');
		html.push('</div>');		
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
	}
};

var Comments = {
	
	initialize : function() { 
	
		if(!$('comment-form'))
			return;
			
		$('comment-form').addEvent('submit', function(event) {
	
			if(!Comments.validate(this))
				event.preventDefault();
				
		});
	},

	validate : function(form) {

		thisBody = form.comment;
		
		form.submit.setProperty('disabled', 'disabled').setValue('Παρακαλώ περιμένετε...').addClass('button-disabled');
		
		if(thisBody.value.length < 1) {
			
			alert("Παρακαλώ πληκτρολογήστε πρώτα την άποψή σας");
			
			thisBody.blur();
			form.submit.setProperty('disabled', '').setValue('Αποστολή σχολίου').removeClass('button-disabled');
			
			return false;
		}
		
		if(!form.terms.checked) {
			
		        alert( "Πρέπει να αποδεχτείτε τους όρους Χρήσης του Pathfinder για να συνεχίσετε");
		        form.submit.setProperty('disabled', '').setValue('Αποστολή σχολίου').removeClass('button-disabled');
		        return false;
		}
		
		return true;
	}
};

var PressImage = {
		
	initialize : function() {
		
		if(!$('newspaper-id'))
			return;
		
		var img 	= $('newspaper-id');
		var link 	= img.getParent();

		if(typeof link != 'undefined')
			this.image = new Zoomer.Image(img, { 'onClose' : function() { $(link).getElement('.zoomer-icon').setStyle('visibility', ''); } });
		else
			return;
		
		$(link).addEvent('click', function(event) {
			
			event.preventDefault();
			
			$(link).getElement('.zoomer-icon').setStyle('visibility', 'hidden');
			
			PressImage.image.open();
		});
	}
};

var Area = {
	
        initialize              : function() {
        	
                var elements = $$('textarea[rel]');
                
                elements.each(function(element, index) {
                	
                        var rel = element.getProperty('rel');
                        
                        element.$rules = rel.evalJSON();
                        
                        if(element.$rules && element.$rules['resize']) {
                        	
                                Area.resize.call(element);
                                element.addEvent('keyup', Area.resize.bind(element));
                        }
                        
                        this.setStyle('height', '3em');
                });
                
                
        },

        resize                  : function(event) {
        	
                var rows        = this.value.match(/\n/gi)  || [];
                
                rows            = rows.length + 3;
                var height      = rows.limit(this.$rules.resize.min, this.$rules.resize.max);
                
                if(!event || ['return', 'backspace', 'delete', 'v', 'x'].contains(event.key) )
                        this.style.height = (height + 1) +  'em';
        }
};

var PressScroller = {
	
	initialize : function() {
		
		if(!$('press-scroller'))
			return;
			
		this.elements = $$('#placeholder li');
		this.listWidth= this.elements.length * 99;
		
		this.scroller = new Fx.Scroll('placeholder', {
			
			'onComplete'	: function() {
				
				PressScroller.animating = false;
				
				var x = $('placeholder').getSize().scroll.x;
				
				if(x == 0) {
					
					$('scroller-prev').addClass('inactive');
					$('scroller-next').removeClass('inactive');
				
				} else if(x + 198 == PressScroller.listWidth) {
					
					$('scroller-next').addClass('inactive');
					$('scroller-prev').removeClass('inactive');
				
				} else {
					
					$('scroller-prev').removeClass('inactive');
					$('scroller-next').removeClass('inactive');
					
				}
			}
		});
				
		if($('scroller-prev'))
			$('scroller-prev').getElement('a').addEvent('click', function() { PressScroller.scroll(-1); });
	
		if($('scroller-next'))
			$('scroller-next').getElement('a').addEvent('click', function() { PressScroller.scroll(+1); });
	},
	
	scroll : function(direction) {
		
		if(this.animating)
			return;
		
		var size 	= $('placeholder').getSize();
		var x 		= parseInt(size.scroll.x);
		
		if(direction == 1 && x + 198 >= PressScroller.listWidth)
			return;
		
		this.animating = true;
		
		PressScroller.scroller.scrollTo( (direction == 1 ? x + 198 : x - 198), 0);
	}
};

var HomeCarousel = {
	
	stepInterval 	: 5000,
	index			: 0,
	items			: new Array(),

	initialize : function() {
		
		if(!$('carousel'))
			return;
		
		this.elements 	= $$('#carousel-thumbs li');
		this.max		= this.elements.length;
		this.stepTimer  = this.walk.periodical(this.stepInterval, this); 

		this.elements.each(function(element, index) {
			
			this.addEvent('mouseover', function() { 
		
				$clear(HomeCarousel.stepTimer);
				HomeCarousel.render(this, index); 
				HomeCarousel.stepTimer  = HomeCarousel.walk.periodical(HomeCarousel.stepInterval, HomeCarousel);
			});
		});
		
		this.items 		= $$('#carousel-current li');
		this.items.each(function() { HomeCarousel.items.push(this);	});

	},
	
	walk : function() {
		
		this.index = (this.index + 1 > this.max - 1 ? 0 : this.index + 1);
		
		return this.render(this.elements[this.index], this.index);
	},
	
	render : function(element, index) {
				
		this.elements.each(function() { this.removeClass('active'); });
				
		element.setClass('active');
		
		this.items.each(function() { this.removeClass('carousel-active'); });
		this.items[index].setClass('carousel-active');
		this.index 	= index;
	}
	
};

var Tabs = {
	
	initialize : function() {
		
		this.tabContainers = $$('.main-tabs');
		
		if(this.tabContainers.length == 0)
			return;
			
		this.tabs = this.tabContainers[0].getElements('li');
		
		this.tabs.addEvent('click', function() {
			
			if(this.hasClass('active'))
				return;
				
			Tabs.tabs.each(function() { 
			
				this.removeClass('active'); 
				
				var id = this.getProperty('id').replace("tab-", "box-");
				
				if($(id))
					$(id).hide();
			});
			
			this.addClass('active');
			var id = this.getProperty('id').replace("tab-", "box-");
			
			if($(id))
				$(id).show();
		});
	}	
};

var Team = {
	
	initialize : function() {
		
        this.overlay = new Overlay('', {
                'duration'      : 400,
                'className'     : 'team'
        });
				
		if($('roster'))
			$('roster').addEvent('click', function() { Team.renderOverlay(this.id, teamRoster); });
			
		if($('last_games'))
			$('last_games').addEvent('click', function() { Team.renderOverlay(this.id, previousGames); });
		
		if($('next_games'))
			$('next_games').addEvent('click', function() { Team.renderOverlay(this.id, nextGames); });
	},
	
	renderOverlay : function(id, data) {
		
		var html = [];

		html.push('<div class="overlay-window" id="team-overlay-window">');
		html.push('<div class="overlay-content" id="team-overlay-content">');
		html.push('<div class="overlay">');
		html.push('<h3>' + (id == "roster" ? 'Roster ομάδας' : (id == 'last_games' ? 'Προηγούμενες αγωνιστικές' : 'Επόμενες αγωνιστικές' )) + ' <span onclick="Team.overlay.close();"><img src="http://c.pstatic.gr/img/act/nob/x.gif" alt="close" /></span></h3>');
		html.push('<div class="overlay-body">');
		
		html.push(data);
		
		html.push('</div>');
		html.push('<div class="overlay-footer">');
		html.push('<input type="button" onclick="Team.overlay.close();" value="Κλείσιμο" class="button" />');
		html.push('</div>');
								
		html.push('</div>');		
		html.push('</div>');
				
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
	}
};

var Menu = {

	initialize : function() {
		
		if(!window.ie)
			return;
			
		if(!$('menu'))
			return;
			
		this.popups = $$('.popup');
		
		this.popups.each(function() {
			
			var parent = $(this).getParent();
			
			parent.addEvent('mouseover', function() {
				
				var popup = $(this).getElement('.popup');
				var arrow = $(this).getElement('.arrow');
				
				$(arrow).addClass('arrow-hover');
				$(popup).show();
			});
			
			parent.addEvent('mouseout', function() {
				
				var popup = $(this).getElement('.popup');
				var arrow = $(this).getElement('.arrow');
				
				$(arrow).removeClass('arrow-hover');
				$(popup).hide();
			});
		});
	}
};

var Mundial = {

	initialize : function() {
		
		if(typeof teamsJ == 'undefined')
			return;
			
		this.teamsJ 	= JSON.parse(teamsJ);
		
        this.overlay = new Overlay('', {
                'duration'      : 400,
                'className'     : 'team'
        });
		
		
		var elements = $('wrapper-outer').getElements('a[rel^="mteam-"]').addEvent('click', function() {
		
			var rel = $(this).getProperty('rel');
			var split = rel.split(/\-/);
		
			Mundial.renderOverlay(split[1]);
		});
	},
	
	renderOverlay : function(teamId) {

		var html 			= [];
		var team			= this.teamsJ[teamId];
				
		var cman_image_url = "http://pf.pstatic.gr/CMAN/i/";
		
		html.push('<div class="overlay-window" id="team-overlay-window">');
		html.push('<div class="overlay-content" id="team-overlay-content">');
		html.push('<div class="overlay">');
		html.push('<h3>' + team.title + ' - Όμιλος ' + team.group.toUpperCase() + ' <span onclick="Mundial.overlay.close();"><img src="http://c.pstatic.gr/img/act/nob/x.gif" alt="close" /></span></h3>');
		html.push('<div class="overlay-body">');

		html.push('<img class="img" src="' + cman_image_url + team.image + '" style="float:left;margin:0 20px 20px 0;"/>');	
		html.push('<div id="team-body"></div>');

		html.push('</div>');
		html.push('<div class="overlay-footer">');
		html.push('<input type="button" onclick="Mundial.overlay.close();" value="Κλείσιμο" class="button" />');
		html.push('</div>');
							
		html.push('</div>');		
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		
		$('team-body').setHTML(team.body);
	}
};

var MundialSide = {

	initialize : function() {
		
		if(!$('mundial-side'))
			return;
			
		$('mundial-side').getElements('[id^=tab-mundial-]').addEvent('click', function() {
			
			var rel = this.getProperty('id').split('tab-mundial-');

			MundialSide.showBox(rel[1]);
		});
	},
	
	showBox : function(id) {
		
		$('mundial-side').getElements('[id^=box-mundial-]').each(function() { this.hide(); });
		$('mundial-side').getElements('[id^=tab-mundial-]').each(function() { this.removeClass('active'); });
		
		$('box-mundial-' + id).show();
		$('tab-mundial-' + id).addClass('active');
	}
};

var TwitterBox = {
	
	first			: true,
	stepInterval 	: 10000,
	since			: '',
	
	initialize : function() {
		
		if(!$('twitter-box'))
			return;
			
		this.fetch();
		
		this.stepTimer  = this.fetch.periodical(this.stepInterval, this);
		
		$('twitter-fetcher').getElement('.tooltip-trigger').addEvent('mouseenter', function() { $(this).addClass('hover'); });
		$('twitter-fetcher').getElement('.tooltip-trigger').addEvent('mouseleave', function() { $(this).removeClass('hover'); });
	},
	
	fetch : function() {
		
		new Ajax('get', {

			onSuccess : function(req)	{

				var res = req.responseJSON;
				
				if(res.results.count == 0 && TwitterBox.first) {
					
					clearInterval(TwitterBox.stepTimer);
					return;
				}
				
				TwitterBox.render(res.results);
				TwitterBox.first = false;
				TwitterBox.since = res.max_id;
			},
			
			url             : '/tools/twitter.php',
			parameters		: { 'since' : this.since }
			
		}).send();
		
	},
	
	render : function(items) {

		items.each(function() {

			var html = [];
			
			html.push('<div class="author">');
			html.push('<a target="twitter" href="http://twitter.com/' + this.from_user + '"><img class="img" src="' + this.profile_image_url + '" width="36" height="36"/></a> ');
			html.push('</div>')
			
			html.push('<div class="tweet">');
			html.push('<a target="twitter" href="http://twitter.com/' + this.from_user + '">' + this.from_user + '</a>: ' + this.text);
			html.push('</div>');
			
			var li 	= $C('li', { 'id' : 'tweet-' + this.id , 'class' : 'clr' }).setHTML(html.join(''));
			
			if(!TwitterBox.first) {
				
				var effect = $(li).effects({duration: 1000, transition: Fx.Transitions.Sine.easeInOut});
		
				effect.start({'background-color': ['#ffc', '#fff'] });
			}
		
			if(!$('tweet-' + TwitterBox.since))
				li.injectIn($('twitter-box'));
			else
				li.injectBefore($('tweet-' + TwitterBox.since));
		});
	}
};

var Live = {
	initialize : function() {
		if (!$('live-events'))
			return;
		var elements = $('live-events').getElements('a').addEvent('click', function(event) {
			event.stop();
			var id = $(this).getProperty('id'), sel = 0;
			if (id) {
				sel = id.replace('event-', '');
				window.open(event.target.href, 'live-event', 'width=800,height=620,resizable=no,scrollbars=no,menubar=no,status=no,location=0');
			}
		});
	}
};

var	GameResults = {
	
	container	: 'game-results',		// Where to render the results to.
	interval	: 1000 * 60,			// 60 secs,
	lastUpdate	: null,					// Last updated - refresh
	dt			: (new Date().toYMD().split('-')).join(''),
	games		: {
		'live'		: [],
		'incoming'	: [],
		'archived'	: []
	},
	showIncoming : true,
	archived	:	{
		'608' 	: 'Διακόπηκε',
		'609' 	: 'Ακυρώθηκε',
		'1008' 	: 'Τελείωσε',
		'1009' 	: 'Τελείωσε - Ακυρώθηκε'
	},
		
	initialize 	: function(dt, showIncoming) {

		// Draw a beacon here.
		document.write('<div id="'+this.container+'"></div>');
		window.addEvent('DOMContentLoaded', this.refresh.bind(this));
		
		this.stepTimer  = this.refresh.periodical(this.interval, this);

		this.RPC = new Ajax.RPC({
			'ttl'		: 30,
			'onSuccess' : this.process.bind(this)
		});
		
		if(arguments.length > 0){
			
			if(arguments[0] && arguments[0].trim()!='') {
				this.dt = arguments[0];
			}
			if(arguments[1]) {
				this.showIncoming = arguments[1];
			}
		}
		
		return this;	
	},

	refresh		: function() {
		
		this.RPC.send('cman.GetItems', 2936, 1, '*', 'dt:asc', 0, 10, 'utf-8', false, false, -1, 'dt = ' + this.dt);
		
		return this;	
	},


	process		: function(xhr) {
		var res = xhr.responseJSON, games;
		
		// Initialize GameResults.games
		this.games = { 'live' : [], 'incoming' : [], 'archived' : [] };
		
		if(!res || res.faultCode) {
			// TODO: pick a better escape route.
			return false;
		}
		
		// Assign to games.
		games = $A(res.results);
		
		// 1. Check if any games are on
		// if not, bail out - nothing to do here.
		if(games.length === 0) {
			return false;
		}

		if($('live-events').isHidden()){
			$('live-events').show();
		}
		// 2. Separate games (live // incoming)
		games.each(function(game, index) {
			// TODO: Check if the game is running or not ..(archieved field?)
			
			var key = GameResults.getStatus(game);
			
			this.games[key].push(game);
		}, this);
	
		if(this.games['live'].length > 1)
			this.sortLiveGames(this.games['live']);
		
		return this.render();
	},

	render		: function() {
		var container 	= $(this.container);
		var html		= [];
		var time		= ''; 
		// Draw stuff
		for(var key in this.games) {
			
			if(!this.showIncoming && (key==="incoming" || key==="archived")) {
				break;
			}
			if(this.games[key].length) {
				html.push('<h3>' + (key === 'live' ? '<strong>Live</strong> αποτελέσματα' : (key==="incoming"? 'Αργότερα': 'Ολοκληρωμένοι αγώνες')) +'</h3');
				html.push('<table cellspacing="0" cellpadding="0" border="0" summary="results data">');
				
				// Header
				html.push('<thead><tr>');
				html.push('<td cell="cell-time">'+(key === 'live' ? 'Λεπτό' : (key=='incoming' ? 'Έναρξη' : 'Κατάσταση')) +'</td>');	
				html.push('<th>Αγώνας</th>');
				(key === 'live' || key=== 'archived') && html.push('<td class="cell-score">Σκορ</td>');
				html.push('</tr</thead>')
				
				// Body
				html.push('<tbody>');
				this.games[key].each(function(game, index) {
					//  onclick="GameResults.open('+game.item_id+')"
					html.push('<tr>');
					
					var status = GameResults.getStatus(game);
					
					if(status == 'incoming') {
						var timeStr = game.date.replace(game.dt, '');
						var timeAr = [
							timeStr.substring(0,2),
							timeStr.substring(2,4),
							timeStr.substring(4)
						];
						
						time = timeAr.join(':');
					}
					else {
						time = status === 'live' ? game.minute :  GameResults.archived[game.status];
					}
					html.push('<td class="cell-time">' + time + (status=='live' ? '\'' : '') + '</td>');
					html.push('<th><a href="http://sports.dev.pathfinder.gr/live.php?id='+game.item_id+'"');
					
					if(status=="incoming") {
						html.push(' class="noExternal"');
					} else {
						html.push(' onclick="GameResults.open(this.href, event)"');
					}
					
					html.push('> '+this.getTeam(1, game) + ' - ' + this.getTeam(2, game) + '</a></th>');
					
					(key == 'live' || key=='archived') && html.push('<td class="cell-score">' + game.skor1 +' - '+ game.skor2 +'</td>');
					html.push('</tr>');			
				}, this);
				html.push('</tbody>');
				
				html.push('</table>');
			}
		}

		// Dump to container
		container.setHTML(html.join(''));
	},

	// TODO: clean up this mess
	getTeam		: function(index, game) {
		var _class = 'loose';
		if(game['skor' + index ] > game['skor' + (index == 1 ? 2 : 1) ]) {
			_class = 'win'
		}
		if( game['skor' + index ] == game['skor' + (index == 1 ? 2 : 1) ]) {
			_class = 'draw';
		}
		return '<span class="'+_class+'">' + game['team' + index] + '</span>';

	},

	open		: function(url, event) {
		if(event) {
			$E(event).stop();
		}
		var props = 'width=800,height=620,resizable=no,scrollbars=no,menubar=no,status=no,location=0';
		
		window.open(url, 'results', props);
	},
	
	//sort live game based on the minute of the last event happend
	sortLiveGames	: function(liveGames){
		this.games['live'].sort(function(game1, game2) {
			var events1 = game1.data.unserialize(), events2 = game2.data.unserialize();
			return parseInt(events2[0].minute || 0) - parseInt(events1[0].minute || 0);			
		});	
	},
	
	getStatus	: function(game){
		var key = 'live';
		var status = parseInt(game.status);
		if(status > 600) {
			key = 'archived';
		} else if (status == 1) {
			key = 'incoming';
		}
		
		return key;
	}
};

var EventsSummary = {
	
	initialize : function(){
		
		if(!$('events-summary'))
			return;
		
			
		$$('#events-summary li').addEvent('click', function(){
			
			var id = this.getProperty('id');

			EventsSummary.filterEvents(id);
		});
	},
	
	filterEvents : function(id){
		//console.log(id);
		//console.log($('tr[rel^="'+id+'"]'));
		//console.log($$('#events-body table tr[rel^=events-]'));
		//console.log($$('.zebra tr[rel]'))
		
	   //if(id=="events-all") {
			
			$$('.zebra tr[rel]').each(function(){
				this.hide();
			});
				
		$$('.zebra tr[rel="'+id+'"]').each(function(){ 
		 
		         //console.log(this);
		         this.show();
		 });
		
		//else{
		//	console.log($$('tr[rel^="'+id+'"]'));
	   //}
		}
};

var BottomRollover = {

    'threshold' : 20,   //percent
    'hidden'    : true,
    'animating' : false,
    'closed'    : false,
    'boxSize'   : {
        'width' : 400,
        'height': 120
    },
    'closeBoxSize'   : {
        'width' : 30,
        'height': 120
    },

    initialize : function() {

        //Screw you IE6
        if(window.ie6)
            return;

        if(typeof nextArticle == 'undefined')
            return;

        //Get next article info
        this.info = JSON.parse(nextArticle);

        //Build the boxes
        this.build();

        //Determine if article box is closed based on Cookie
        this.closed = (Cookie.get('rollover-article') == "true");

        //Add the scroll event
        if(!window.hasEvent('scroll'))
            window.addEvent('scroll', this.scroll.bind(this));
    },

    build : function() {

        var html = [];

        this.info.url = 'http://clk.pathfinder.gr/sports/bottom/http://sports.pathfinder.gr' + this.info.url;

        html.push('<h5>Διάβασε ακόμη από την κατηγορία \"' + this.info.category + '\"<a title="Κλείσιμο" href="javascript:void(0);" onclick="BottomRollover.toggle(\'close\');">&times;</a></h5>');
        html.push('<div onclick="window.location = \'' + this.info.url  + '\';" class="info ' + (this.info.image ? 'has-image' : '') + '">');

        if(this.info.image)
            html.push('<a href="' + this.info.url + '"><img alt=\"' + this.info.title + '\" src=\"' + this.info.image + '\"/></a>');

        html.push('<p><a href="'+ this.info.url + '">' + this.info.title + '</a></p>');
        html.push('<p class="sub"><a href="'+ this.info.url + '">Διάβασε περισσότερα &raquo;</a></p>');
        html.push('</div>');

        this.element = $C('div').setStyles({
            'position'  : 'fixed',
            'right'     : '-' + (this.boxSize.width + 4) + 'px',
            'bottom'    : '0',
            'width'     : this.boxSize.width + 'px',
            'height'    : this.boxSize.height + 'px'
        }).setClass('rollover-article').setHTML(html.join('')).injectIn(document.body);

        html = [];
        html.push('<a class="rollover-article-open" href="javascript:void(0);" onclick="BottomRollover.toggle(\'open\');">');
        html.push('<img src="http://x.pstatic.gr/so/n/Common/img/misc/rollopen.png" width="30" height="122"/>');
        html.push('</a>');

        this.closedElement = $C('div').setStyles({
            'position'  : 'fixed',
            'right'     : '-' + (this.closeBoxSize.width + 4) + 'px',
            'bottom'    : '0',
            'width'     : this.closeBoxSize.width + 'px',
            'height'    : this.closeBoxSize.height + 'px'
        }).setClass('rollover-article').setHTML(html.join('')).injectIn(document.body);
    },

    toggle      : function(mode){

        if(mode=='open'){

            this.closed = false;
            this.show(BottomRollover.element, this.boxSize.width);
            this.hide(BottomRollover.closedElement, this.closeBoxSize.width);

            Cookie.set('rollover-article', this.closed);
            
        } else{

            this.close();
            this.closed = true;

            Cookie.set('rollover-article', this.closed);
        }
    },

    close : function() {

        this.hide(this.element, this.boxSize.width);
        this.show(this.closedElement, this.closeBoxSize.width);
    },

    scroll : function() {

        var maxHeight           = document.body.scrollHeight;
        var currentScroll       = window.getBody().scrollTop + window.getHeight();

        if(currentScroll >= maxHeight - (this.threshold / 100 * maxHeight) && this.hidden) {

            if(this.closed)
                this.show(this.closedElement, this.closeBoxSize.width);
            else
                this.show(this.element, this.boxSize.width);

            this.hidden = false;

        } else if(currentScroll < maxHeight - (this.threshold / 100 * maxHeight) && !this.hidden) {

            if(this.closed)
                this.hide(this.closedElement, this.closeBoxSize.width);
            else
                this.hide(this.element, this.boxSize.width);

            this.hidden = true;
        }
    },

    show : function(element, boxWidth) {

        this.animating = true;

        new Fx.Style(element, 'right', {
            'duration'  : 200,
            'onComplete': function() { BottomRollover.animating = false; }
        }).start('-' + boxWidth, '0');
    },

    hide : function(element, boxWidth) {

        this.animating = true;

        new Fx.Style(element, 'right', {
            'duration'  : 200,
            'onComplete': function() { BottomRollover.animating = false; }
        }).start('0', '-' + (boxWidth + 4));
    }
};

window.addEvent("DOMContentLoaded", function() {
	
	if(window.ie6)
		PNGFix.fix('span.icon img');
	
	[TwitterBox, MundialSide, Mundial, HomeCarousel, Menu, PressScroller, Team, Tabs, Area, Comments, PressImage, EventsSummary, BottomRollover].each(function() { this.initialize(); });
});

