/* 
 * Javascript support for pathfinder news
 * GP | Last updated 10/01/04
*/
var jsLoaded = true;
var previewWindow = 0;
windowLoaded = false;

/* AttacheHandlers  : Attaches onblur handlers to all text and textarea elements of forms and then trims them .*/
function AttachHandlers ()
{
	windowLoaded = true;
	var el , thisForm, formes = document.forms;

	for (var f = 0 ; (thisForm = formes[f]) ; f++)
	{
		/* Validate the form on submit */
		thisForm.onsubmit = function () 
		{
			return (ValidateForm(this));
		}
		
		/* Attache handlers to elements */
		for (var i = 0 ; (el = thisForm.elements[i]) ; i++)
		{
			switch (el.type)
			{
				case "text" :
				el.onblur = function () {this.value = this.value.trim();}
				/* Focus the recipients in mailform */
				if (thisForm.id == "mailForm" && el.id == "recipientEmail")
					el.focus();
				case "textarea" :
				el.onblur = function () {this.value = this.value.trim();}
				break;

				case "button" :
				if (thisForm.id == "commentsForm")
				el.onclick = ToggleComment
				break;

			}
			
			
		}
	}
}

/* This function validates all the forms in the document */
function ValidateForm (f)
{
	var el, elFirst, thisForm = f.id;
	var thisFormErrors = [];

	if (thisForm == 'poll') {
		new Ajax.RPC({
			'host': '10.5.5.49',
			'port': 9988,
			'api': 1
		}).send("link.PurgeCacheRepository", "Pathfinder Web", "userspecific:news", 'news.pathfinder.gr/[^/]*$');
	}
	
	if( f.id == "survey-promo-form" )
		return;
	for (var i = 0; (el = f.elements[i]) ;i++)
	{
		if (el.type == "text" || el.type == "textarea" || el.type == "checkbox" || el.type == "radio" || el.tagName == "SELECT" )
		{
			/* not filled */
			if (!IsValid(el)) 
			{
				if (!elFirst && el.type != "checkbox" && el.type != "radio") elFirst = el;
		
				switch (thisForm)
				{
					/* This is for the Polls */
					case "poll":
					thisFormErrors.push("Παρακαλώ ψηφίστε για να συνεχίσετε");
					break;

					/* This is for the comments */
					case "searchForm":
					thisFormErrors.push("Παρακαλώ δώστε στοιχεία για αναζήτηση");
					break;

					/* This is for the comments */
					case "commentsForm":
					switch (el.id)
					{	
						case "body":
						thisFormErrors.push ("Πρέπει να δώσετε σχόλιο για να συνεχίσετε");
						break;
							
						case "terms":
						thisFormErrors.push ("Πρέπει να διαβάσετε και να αποδεχτείτε τους Όρους Χρήσης του Pathfinder για να συνεχίσετε");
						break;	
					}
					break;

					/* This is for the alerts */
					case "alertsForm":
					switch (el.id)
					{
						case "alertTitle":
						thisFormErrors.push ("Πρέπει να επιλέξετε τίτλο για την ειδοποίηση.");
						break;

						case "kw":
						thisFormErrors.push ("Πρέπει να δώσετε τουλάχιστον μια λέξη κλειδί");
						break;
					}
					break;

					/* This is for the alerts */
					case "feedbackForm":
					switch (el.id)
					{
						case "feedbackLikes":
						thisFormErrors.push ("Παρακαλώ συμπληρώστε τι σας αρέσει στο Pathfinder News.");
						break;

						case "feedbackDisLikes":
						thisFormErrors.push ("Παρακαλώ συμπληρώστε τι δεν σας αρέσει στο Pathfinder News.");
						break;

						case "feedbackWish":
						thisFormErrors.push ("Παρακαλώ συμπληρώστε τι θα θέλατε να δείτε στο Pathfinder News.");
						break;
					}
					break;
	
					/* This is for the mail */
					case "mailForm":
					switch (el.id)
					{	
						case "recipientEmail":
						thisFormErrors.push ("Πρέπει να επιλέξετε παραλήπτη για να συνεχίσετε");
						break;

						case "senderEmail":
						thisFormErrors.push ("Πρέπει να δώσετε το e-mail σας για να συνεχίσετε");
						break;
					}
					break;

					/* This is for the stocks */
					case "stocksForm":
					thisFormErrors.push ("Παρακαλώ δώστε το όνομα ή το σύμβολο της μετοχής για να συνεχίσετε!");
					break;

					default :
					alert ("oops!");
					break;	
				}
			}	
			else if (f.id == "poll")
				return true;
			
		}

	}
	
	/* Bail out if errors | proceed if not */
	if (thisFormErrors.length > 0)
	{
		message = thisFormErrors.join("\n")
		/* Polls patch */
		if (f.id == "formIprobe")
		{
			message = thisFormErrors[0];
		}
		alert (message);
		if (elFirst) elFirst.focus();
		return false;
	}
	else 
	{
		/* 
		 * Messages | Sucessful postings  
 		*/
		if (f.id == "commentsForm")
		{
			
			/* Perform length checkup */
			if (f.body.value.length > 2200)
			{
				alert ("Το σχόλιο σας δεν μπορεί να υπερβαίνει τους 2.200 χαρακτήρες!");
				return false;
			}			
	
			/* Perform is_in_greek checkup */
			if( 1 ) {
				greek_words = f.body.value.match(/[αάΑ’βΒγΓδΔεέΕΈζΖηήΗΉθΘιίϊΙΊκΚλΛμΜνΝξΞοόΟΌπΠρΡσςΣτΤυύΎΥψφΨχΧωώΩΏ]+/g);
				if (greek_words != null)
				{
					if (greek_words.length >= 5) 
					{
						alert ("Ευχαριστούμε για τη συμμετοχή σας!\nΤο σχολίο σας θα εμφανιστεί στις σελίδες του Pathfinder αμέσως μόλις ελεγχθεί ότι είναι σύμφωνο προς τους Όρους Χρήσης από τη Συντακτική Ομάδα.");
						return true;
					}
				}
				alert ("Για να προχωρήσετε πρέπει το μήνυμά σας να είναι γραμμένο με Ελληνικούς χαρακτήρες και με περισσότερες από 5 ορθά γραμμένες λέξεις.");
				return false;
			}
		}
		if (f.id == "mailForm")
		{
			alert ("Επιτυχής αποστολή άρθρου!\nΠατήστε [ok] για να μεταφερθείτε πίσω στο άρθρο.");
		}
		if (f.id == "feedbackForm")
		{
			alert ("Ευχαριστούμε για τα σχόλια σας!\nΠατήστε [ok] για να μεταφερθείτε στην κεντρική σελίδα.");
		}
		
		else return true;
	}
}

/* Prints an item (item == article or page) | todo : use dummy image to add counters */
function PrintIt(item)
{
	im = document.getElementById('bmpic');
	if (im)
	{
		im.src='/counter?printId='+item;
	}
	window.print();
}

/* Toggle comments form */
function ToggleComment ()
{
	var el = document.getElementById("commentsForm");
	var commentsLink = document.getElementById("commentsLink");
	status = commentsLink.style.display;
	switch (status)
	{
		case "inline":
		case "":
		commentsLink.style.display = "none";
		el.style.display = "block";
		el.body.focus();
		break;
			
		case "none":
		commentsLink.style.display = "inline";
		el.style.display = "none";
		break;
	}
}

/* Checked if a form element is valid */
function IsValid(w)
{
	/* optional [?] */
	re = /optional$/;
	if (re.test (w.id))  return true;

	valid = (w.type == "checkbox" || w.type == "radio" ? w.checked : w.value);
	
	if (!valid) valid = false;
	return valid;
}

/* Forward to weather city */
function GoWeather()
{
	
	thisCity = document.forms.weatherForm.city.value;

	if (thisCity == "/") 
		window.location = "http://weather.pathfinder.gr";
	else {
		thisUrl = "http://www.pathfinder.gr/rd/w/"+thisCity;
		window.location = thisUrl;
	}

	return false;
}


/* Forward to archived article */
function GoArchive()
{
	
	thisArticle = document.forms.formArchive.archive.value;
	if (!thisArticle) return false;
	
	thisUrl = "http://news.pathfinder.gr"+thisArticle;
	window.location = thisUrl;
}

/* Forward to opap game */
function GoOpap()
{
	
	thisGame = document.forms.opapForm.game.value;
	if (!thisGame) return false;
	
	thisUrl = "sports/opap/"+thisGame;
	window.location = thisUrl;
}

/* Shows the rating frame | avoids flashes*/
function RatingShow()
{
	document.getElementById("rating").style.visibility = "visible";
}

/* Adds an article to bookmarks */
function AddMy(artId)
{
	im = document.getElementById('bmpic');
	if (im)
	{
		im.src='/counter?id='+artId;
		alert ("Το άρθρο προστέθηκε στο MyNews!");
		im.style.display = "none";
		document.getElementById('saveIt').style.display = "none";
	}
	else
		alert("Not found");
}


/* Select all the items from a select box */                                                                      
function SelectAll(el)                                                                                      
{                                                                                                                 
        sel = document.getElementById(el);                                                                        
        for (i=0; i < sel.options.length; i++)                                                                    
                sel.options[i].selected = true;                                                                   
}       

/*
 * previewArticle()
 * 
 * Previews an article using xmlrpx
*/
function previewArticle( element , event ) {
	if(!windowLoaded) {
		return;
	}
	e = event;
	if( !e) e = window.event;
	
	// Sanity check - drop previous windows
	if ( previewWindow ) {
		previewWindow.hidden			= true;
		previewWindow.style.display 	= "none";
	}


	// Get the id based on articles href
	if( !element.id ) {
		h		= element.href; 
		mt		= h.match( /^.*\/(.*?)\.html$/i );
		if(mt) element.id	= mt[1];
		
		// Disable alt and title.
		element.title = element.alt = "";
	}
	
	// Construct the preview | if not present.
	if( !element.preview ) {
		div = $C("div").
		setClass("preview").
		injectIn(document.body);
		element.preview = div;
		makeTransparent( div, 96 );
	}	

	// Assign global vars to previewWindow
	previewWindow			= element.preview;
	previewWindow.element	= $(element);
	previewWindow.hidden	= false;


	// Attach the onmouseout here for less  clattering.
	element.onmouseout = element.onblur = function() {
		this.preview.hidden = true;
		if( !this.preview ) return;
		this.preview.style['display'] = "none";
		this.preview.hidden = true;
		if( this.preview.ts ) {
			this.preview.ts = $clear(this.preview.ts);
		}
		previewWindow = 0;
	}
	
	// Construct the thing here 
	if( !element.preview.loaded ) {
		element.preview.hidden = false;
		element._rpc = true;
		if(!element.timer) {
			element.timer = setTimeout( function() { previewConstruct(element);}, 700 );
		}
	} else {
	}
	 


	// If already present : just show it.
	if( element.preview.loaded || element._rpc ) {
		previewWindow			= element.preview;
		previewWindow.element		= element;
		previewWindow.ts		= setTimeout( "previewShow()", 800 );
	}
	
}


/*
 * previewConstruct()
 * 
 * Previews an article using xmlrpx
*/
function previewConstruct( _element )  {
	_element.timer = $clear(_element.timer);
	if( !previewWindow) return;
	if( previewWindow.hidden )	return;
	
	element = previewWindow.element;
	
	var id;
	if( element.id > 0 ) id = parseInt(element.id);
	else id = "" + element.id + "";
	_element._rpc = element.preview.article = new Ajax.RPC({
		'ttl'		: 1000,
		'mimeType'	: 'text/xml',
		'onSuccess' 	: function() {
			data = this.responseJSON;

			if( !data ) {
				this.abort();
				return;
			}
		
			var bd, m, imgSrc, html = "";
			
			// Render the first image.
			if (data['images'].length) {
				img 	= data['images'][0];
				imgSrc 	= img['thumb_url'];
				imgWidth = img['thumb_width'];
				imgHeight 	= img['thumb_height'];
			}

			if( imgSrc ) 
				html += "<img width=\""+imgWidth+"\" height=\""+imgHeight+"\" src=\""+imgSrc+"\" />\n";							
									
			if( ( headline = data["headline"] )  && headline.length > 20 ) {
				bd = headline;
			}
			else {
				var b = data["body"];
				b = b.replace( /\[IMAGE.*?\]/i, "" ) + "";
				m = b.match( /<p>(.{120,}?)<\/p>/mgi )
				if( m )
					bd = m[0];
				else
					bd  = b;
				bd = bd.replace( /<.?>/gi, "" );		
				bd = bd.replace (/[\n|\r]/gi, "" )
				m  = bd.match( /^(.{120,}?)[\.\!\s]/gi )

				/* GP : This needs an Opera fix */
				bd = m[0];
			}
			bd += "...";


			if( !( dtTs = data["update_ts"] ) )
				dtTs = data["ts"];
			dt = new Date( dtTs * 1000 );
			dt = dt.getDate() + "/" + ( dt.getMonth() + 1 ) + " " + dt.getHours() + ":" + dt.getMinutes()

			html += "<p>" + bd + "</p><p style=\"margin: 0px; padding-top: 5px;margin-top: 4px; border-top: 1px solid #eee;\">" + dt  + " <em>" + data["source"] +"</em></p>\n";	
			thisO.preview.innerHTML = html;
			thisO.preview.loaded = true;
			previewWindow = thisO.preview;
			previewWindow.element = thisO;
			previewWindow.loaded = true;
			
			if( !thisO.preview.hidden ) 
				previewShow();
		}
	});
	element.preview.article.send( "news.GetArticle", id, "descr");
	
	// Render the actual xml
	var thisO = element;
	
}	
	

/* previewShow()
/* Show the preview */
function previewShow() {
	if( !previewWindow ) return;
	previewWindow.hidden = false;

	previewWindow.hidden = false;

	xy = previewWindow.element.getPosition();
	if ( !xy ) return;

	previewWindow.style['display'] = "block";

	if (self.innerWidth)
	{
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
		
	}
	else if (document.body)
	{
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}

	sTop = document.documentElement.scrollTop;
	sLeft = document.documentElement.scrollLeft;
	
		
	var thisY = xy.y + previewWindow.element.offsetHeight + 20 ;

	if( thisY  - sTop + previewWindow.offsetHeight  >  frameHeight  )  {
		thisY = thisY - previewWindow.offsetHeight - previewWindow.element.offsetHeight -20; 
	}
	
	
	var thisX = xy.x;
	if( thisX  - sLeft + previewWindow.offsetWidth  >  frameWidth  )  {
		thisX = frameWidth + sLeft - previewWindow.offsetWidth -20;
	}

	previewWindow.style.top  = thisY + "px";
	previewWindow.style.left = thisX + "px";
}



/**
 * makeTransparent
 *
 * Applies transparency to objects
 */

function makeTransparent ( obj, opacity ) {
	if ( !opacity ) opacity = 100;

  	if ( navigator.userAgent.indexOf( "Firefox" ) != -1 )
		if (opacity == 100) { opacity = 99.999; } // This is majorly retarded

	obj.style.filter = "alpha(opacity=" + opacity.toString() + ")"; //IE/Win
	obj.style.MozOpacity  = parseInt( opacity )/100;   // Older Mozilla+Firefox
	obj.style.KhtmlOpacity = parseInt( opacity )/100; // Safari 1.1 or lower, Konqueror
	obj.style.opacity  = parseInt( opacity )/100; // Safari 1.2, Firefox+Mozilla
	
} 

window.onload = AttachHandlers;

/* vote an answer via core ajax */
function AddReview(id, userId, good) {
	var cont = $('hl-'+ id);
	cont.innerHTML = "Αποστολή επιλογής...";

	if (!id || !userId) {
		alert('Missing some information');
		return false;
	}
	var ajax = new Ajax.RPC({
		onSuccess : function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {
				alert( res.faultString );
			}
			else
			{
				var tot = res['good'] + res['bad'];
				var s = '';
				if (res['good'])
					s = res['good'] + ' από ' + tot +' μέλη βρήκαν αυτό το σχόλιο αξιόλογο';

				if (res['good'] == 1)
					s = "1 μέλος βρήκε το σχόλιο αξιόλογο";

				if (s) {
					$('hl-sum-'+id).innerHTML = s;
					$('hl-sum-'+id).style.display = 'block';
				}
				if (good)
					cont.innerHTML = "Βρήκατε αξιόλογο αυτό το σχόλιο.";
				else
					cont.innerHTML = "Δεν βρήκατε αξιόλογο αυτό το σχόλιο.";
			}
		}
	});
	ajax.send( "comments.AddReview", parseInt(id), parseInt(userId), good);
}

d		= document;
b		= (d.documentElement  && d.documentElement.clientWidth) ?  d.documentElement : d.body
refActive	= null;
/*
 * renderReference()
 * Renders a reference
 */
function renderReference ( p,id ) {
	p = $(p);
	p.blur();

	/* Remove the previous one | if open  */
	if (refActive && refActive != p) {
		refActive.reference.style.display = "none";
		refActive.reference.shadow.style.display = "none";
	}		
	
	/* Show it back if already rendered */
	if (p.reference) {
		posReference();
		p.reference.toggle();
		p.reference.shadow.toggle();		
		refActive = p;
		return;		
	}
	refActive = p;

	/* Construct the container */
	div = $C("div").
	setClass("reference").
	setProperty('id', 'drag').
	injectIn(document.body);
	
	/* Position the container */
	var xy = p.getCoordinates();
	div.style.left	= (xy.left + 10) + "px";
	div.style.top	= (xy.top + 15) + "px";	

	/* Render Loading msg */
	loading = $C("div").
	setClass("loading").
	setHTML("Loading... | Παρακαλώ περιμένετε...").
	injectIn(div);

	var ajax = new Ajax.RPC({
		'ttl'		: 120,
		'onError'	: function() {
		},
		'onSuccess'	: function() {
			data = this.responseJSON;
			if( data && data.faultCode ){
				loading.innerHTML = "Παρουσιάστηκε πρόβλημα κατά την κλήση!";
				self.setTimeout("div.style.display = 'none';",2000);
				return;
			}
			/* Remove all nodes for this div */
			div.innerHTML = "";

			/* Render the bar */
			bar = $C("div").
			setClass("bar").
			setHTML("Σχετικές πληροφορίες").
			injectIn(div);

			xBut = $C("a").
			setProperty("title", "κλείσιμο παραθύρου").
			injectIn(bar);

			// Make it draggable
			Node.disableSelect(div);
			var m = new Drag.Move( div, {
				handle		: $T("div", div)[0],
				container	: document.body,
				onStart	: function() { 
					$("shadow").style.zIndex = 1;
					div.style.zIndex = 99999;
				},
				
				onDrag 	: function(e) {
					var shadow = p.reference.shadow;
					if( !shadow ) return;
					shadow.style.left 	= this.element.style.left
					shadow.style.top 	= this.element.style.top ;
				}
			});

			/* Render the content */
			r_content = $C("div").
			setClass("content").
			injectIn(div);
									
			/* Construct the html */						
			html = "";

			/* Name */
			nameFirst	= data['name_first'];
			nameLast	= data['name_last'];
			if (nameFirst || nameLast)	{
				val		= nameFirst + " " + nameLast;
				val		= val.trim();
				html 	+= "<h1>"+val+"</h1>";
			}

				

			/* Render the tabs */
			html += "<div class=\"referenceTabs\">\n";
			html += "<ul>\n";
			html += "<li class=\"active\"><a href=\"javascript:void(0)\" onclick=\"referencePage( this, 1 );return false;\">αναζήτηση</a></li>\n";
			html += "<li><a href=\"javascript:void(0)\" onclick=\"referencePage( this, 2 );return false;\">βιογραφικό</a></li>\n";
			html += "</ul>\n";
			html += "</div>\n";
		

			/* Page : results */
			html += "<div id=\"referenceResults"+id+"\" class=\"referencePage\">Παρακαλώ περιμένετε...</div>\n";		

			ajaxSearch = new Ajax.RPC({
				'onSuccess': function () {
					var html = "";
					var res = this.responseJSON;
					if( !res)
						html += "No results here!";
						
					if (res['results'].length) {
						allResults = res["results"];
							
						html = "<ol>\n";
						var cnt = 0;
						for( var i = 0; ( thisResult = allResults[i] ); i++ ) {
							title = thisResult['title'];
							if( !title || title == "undefined" )
								continue;
								
							// 20.04.2005 : Skip related!
							//if( thisResult.parentNode.tagName == "related" ) continue;
					
							reg = new RegExp ( "("+query.trim()+")", "gmi" );
							title = title.replace( reg, "<strong>$1</strong>" );
							title = title.stripSlashes();

							html += "<li>\n";
							html += "<a href=\"" + thisResult['id'] + ".html\">" + title + "</a>-&nbsp;" + "&nbsp;<em>" + thisResult["source"] + "</em>\n";
							body = thisResult['body'] + "";
							body = body.stripSlashes();
							if( body && body != "undefined" ) {
								body = body.stripTags();
								body = body.replace( /\[IMAGE.*\]/i,"" );
								body = body.substring( 0, 80 ) + "...";
								html  +=  "<p>" + body +"</p>\n";
							}
							html += "</li>\n";

							cnt ++;
							if ( cnt > 9 ) 
								break;
						}
						html += "</ol>\n";
					}

					// No results 				
					if( cnt == 0 )
						html = "Παρουσιάστηκε ένα πρόβλημα κατά την αναζήτηση...";

					d.getElementById( "referenceResults"+id).innerHTML = html;
					return;
				}
			});

			query = "~" + nameLast.trim();
			ajaxSearch.send( "news.Search", query, "greece", true, 120, false, 1, 15, false);
			html += "</div>\n";

			/* Page : bio */
			html += "<div class=\"referencePage\" style=\"display: none;\">\n";
			
			
			/* The title * profession*/
			if (val = data['item_title']) {
				html += "<h2>";
				html += val.stripSlashes();
				html += "</h2>";
			}

			/* Profession */
			if (pro = data['profession'])
			{
				html += "<h3>";
				html +=  pro.stripSlashes();
				html += "</h3>";
			}

			/* Image */
			if (data['image']) {
				img 	= data['image'];
				imgSrc 	= "http://img.pathfinder.gr/CMAN/i/" + img['path'];
				imgWidth = img['width'];
				imgHeight = img['height'];

				html += "<blockquote";
				if (imgWidth) html += " style=\"width: "+imgWidth +"px\"";
				html += ">\n";
				html += "<img src=\""+imgSrc+"\" ";
				if (imgHeight)	{
					html += "height=\""+imgHeight+"\" width=\""+imgWidth+"\" ";
				}
				html += ">\n";
			
				imgTitle = img["title"];
				if( imgTitle ) {
					if (imgTitle != "" && imgTitle.length > 2) {
						html += "<p>"+imgTitle+"</p>\n";
					}
				}
				html += "</blockquote>\n";			

			}
					
			/* Birth */
			if (val = data['dob'])
			{
				if (valPlace = data['place'])
					val += " ("+valPlace+")";
				html += "<p><strong>Γεννήθηκε : </strong>"+val+"</p>";
			}

			/* Died */
			if (val = data['dod']) {
				if (val > 10) html += "<p><strong>Πέθανε :</strong>"+val+"</p>";
			}

			/* Studies */
			if (val = data['studies']) {
				val = val.stripSlashes();
				html += val.replace(/^\s*?<p>/i,"<p><strong>Σπουδές : </strong>\n");
			}
			
			/* Reference */
			if (val = data['bio']) {
				val = val.stripSlashes();
				html += val.replace(/^\s*?<p>/i,"<p><strong>Βίος : </strong>\n");
			}
			
			/* Profession */
			if (val = data['source']) {
				if (val == 1) {
					html += "<p>Πηγή : ";
					html +=  "ΑΠΕ";
					html += "</p>";
				}
			}

			/* Finish the page */
			html += "</div>\n";			


			/* Remove loading and set the html */
			loading.toggle();
			r_content.setHTML(html);
			
			/* Close the ref */	
			xBut.onclick = div.onkeydown =  function ( e ) {
				if (!e) e = window.event;
				kc = e.keyCode ? e.keyCode : e.charCode;
				
				el = this.parentNode.parentNode;
				if (kc > 0  && kc != 27) return; 
				else if (kc > 0 && kc == 27)
					el = this;
				el.shadow.style.display = "none";
				el.style.display = "none";
			}
			/* Shadow */
			shadow = $C("div");
			shadow.id = "shadow";

			shadow.style.left = div.style.left;
			shadow.style.top = div.style.top;
			shadow.style.width = div.offsetWidth + "px";
			shadow.style.height = div.offsetHeight + "px";
			shadow.className = "reference-shadow";
			shadow.style.filter = "alpha(opacity=70)";
			shadow.injectAfter(div);
			shadow.style.MozOpacity  = 0.7;
			
			/* Assign the elements to their parent */
			p.reference = div;
			p.reference.shadow = shadow;	
		}
	});

	ajax.send("cman.GetItem", 129, parseInt(id), 1, 0, 2, "iso-8859-7");

}
/*
 * posReference ()
 * Reposition the ref elements
 */
function posReference () {
	if (!refActive) {
		return;
	}
	xy = Pos.get(refActive);
	div = refActive.reference;
	if (div) {
		div.style.left	= (xy.x + 10) + "px";
		div.style.top	= (xy.y + 15) + "px";	
		
		div.shadow.style.left	= div.style.left;
		div.shadow.style.top	= div.style.top;
	}
}
/*
 * referencePage ()
 * Toggle Reference pages
 */
function referencePage( obj, page ) {
	var li = obj.parentNode;
	var ul = li.parentNode;
	var tabs = $(ul).getParent();
	c = tabs.parentNode;
	obj.blur();

	// Get all pages.
	allDivs = c.getElementsByTagName( "div" );
	allPages = new Array();
	var cnt = 0;
	for( var i = 0; ( thisPage = allDivs[i] ); i++ ) {
		if( thisPage.className == "referencePage" ) {
			allPages[cnt] = thisPage;	
			cnt ++;
			thisPage.style.display = "none";
		}
	}
	
	
	// Deactivate other tabs 
	allLi = ul.getElementsByTagName( "li" );
	for( var i = 0 ; ( thisLi = allLi[i] ); i++ ) {
		thisLi.className = "";
	}

	if( allPages[page-1] )
		allPages[page-1].style.display = "block";

	li.className = "active";
	obj.blur();
}

function rate(id, vote, w, user, ip) {
	$("rate"+vote).blur();

	/* do the necessery rpc calls */
	if (id && vote)
	{
		/* show loading to user */
		$("rateResult").innerHTML = '&nbsp;';
		$("rateResult").className = "loading";

		var ajax = new Ajax.RPC({
			onSuccess : function(req) {
				res = req.responseJSON;
				if( res && res.faultCode ) {
					alert( res.faultString );
				}
				else
				{
					for (i=1; i < 6; i++)
					{
						if (i == vote)
							$("rate"+vote).className = "active";
						else
							$("rate"+i).className = "";
					}
					$("rateResult").className = "";
					var s = '';
					var score = res['rating'] ? res['rating'] : res['tot_score'];
					var total = res['total_ratings'] ? res['total_ratings'] : res['tot_votes'];
					if (res['tot_score'])
						score = score / total;

					if (total > 0)
						s = "Μέσος Όρος: <strong>" + Math.round(score * 100) / 100 + "</strong> &nbsp;(";
					switch(total)
					{
						case 0:
							s = s + "Καμία ψήφος μέχρι τώρα";
						break;
						case 1:
							s = s + "1 ψήφος";
						break;
						default: 
							s = s + total + " ψήφοι";
						break;
					}
					s += ")";
					$("rateResult").innerHTML = s;
				}
			}
		});

		/* set methods and arguments */
		vote = parseInt(vote);
		id = parseInt(id);
		user = parseInt(user);
		switch (w)
		{
			case 'p':
				ajax.send( "news.RatePhoto", vote, user, id, ip);
			break;
			case 'g':
				ajax.send( "news.RateGeliografia", vote, user, id, ip);
			break;
			default:
				if (!user)
					user = ip;
				ajax.send( "aux.SetScore", 'pfnews', id, user, vote, true);
			break;
		}
	}
}

var Tabs = {
	current : 'popular',

	select 	: function(element) {
		
		var selected = element;
		
		element = $("tab-" + element);
	
		if("tab-" + this.current == element.id)
			return false;

		$('tab-'+this.current).removeClass('active');
		$('container-'+this.current).hide();
		
		this.current = selected;
		
		$('tab-'+this.current).addClass('active');
		$('container-'+this.current).show();
		return false;
	}
	
};

NewTabs	= {
	initialize : function() {
		if(!$('newsroom' )) {
			return false;
		}
		$$('#newsroom .tabs li span').makeUnselectable();
		
		// select proper tab
		if(location.hash)	{	
			
			var tab = location.hash.split('#')[1];
			
			if($('tab-' + tab))	{
				NewTabs.select($('tab-' + tab).getFirst());
			}
		}
	},
	
	select		: function(element) {
		var parent 		= $(element).getParent();
		
		var tab = parent.id.replace(/tab\-/, '');

		if(window.ie6) {
			element.blur();	
		}
		
		location.hash = '#' + tab;
		
		var container = $(parent).getParent();		
		
		// Gather and store all tabs
		container.tabs = container.tabs || container.getElements('li');
		container.tabs.each(function(tab) {
			var tabId, matches;
			
			// Check for tabID, bail out of not found
			if ( matches = this.id.toString().match( /tab-(.*?)$/) ) {
				tabId = matches[1];
			} else {
				return false;	
			}
			
			if(tab !== parent) {
				tab.removeClass('active');
				$('box-' + tabId).hide();
			} else {
				tab.addClass('active');
				$('box-' + tabId).show();
			}
		});
		
		return false;
	}
};


var ArticleTabs = {
	current : 'article',
	mapRendered : false,

	select 	: function(element, event) {
		if(event) {
			event = $E(event);
			event.stop();

		}
		if($(element).getParent().id == 'tab-map') {
			if(map && !this.mapRendered) {
				map += '<p style="font-size: 11px; color: #999">Μπορείτε να κάνετε zoom in / zoom out χρησιμοποιώντας το ποντίκι ή τα δύο αντίστοιχα εικονίδια αριστερά. Μετακινήστε το χάρτη χρησιμοποιώντας το σταυρό κατεύθυνσης. Αλλάξτε τρόπο απεικόνισης του χάρτη κάνοντας κλικ στις επιλογές στην κορυφή.</p>';
				$('container-map').setHTML(map);
				this.mapRendered = true;
			}
		}

		var selected = element;
		/*element = $("tab-" + element);*/
		
		if(element.toLowerCase) {
			element = $('tab-'+element).getElement('a');	
		}
		element = $(element);

		/*if("tab-" + this.current == element.id) {
			return false;	
		} */
		
		var id = element.getProperty('href').match(/#(.*?)$/i)[1];
	
		if(id && this.current === id) {
			return false;	
		} 	
	

		$('tab-'+this.current).removeClass('active');
		$('container-'+this.current).hide();
		
		this.current = id;
		
		$('tab-'+this.current).addClass('active');
		$('container-'+this.current).show();

	    var loc = location.href.toString();
		loc =loc.replace(/#.*?$/gi, '');
		       window.location.replace( loc + '#' + id);

		return false;
	}
	
};

function mediaSelect(el, id, title) {
	el = $(el);
	var i = 0, item;
	for (i = 0;i<imgs.length; i++) {
		item = imgs[i];
		if (id == item.id)
			break;
	}
	$T("td", el.getParent().getParent().getParent()).each(function(element) {
		element.removeClass("hi");
	});
	
	$('media-img-title').setHTML(title);

	el.getParent().setClass("hi");
	
	var mediaImage 		= $('media-image');
	mediaImage.src 		= item.src;
	mediaImage.width 	= item.width;
	mediaImage.height 	= item.height;

	return false;
}


Event.add( window, "DOMContentLoaded", function() {
	
	// added by Sugar, for this country thingy
	NewTabs.initialize(); 
	
	// if references there
	if($$('a.country-reference')[0] || $$('a.reference')[0])	{
		
		PopupCountry.initialize('a.country-reference');
		PopupLeader.initialize('a.reference');
	
		document.addEvent('keydown', function(event) {
			var popup = Popup.current;
			
			if(event.key === 'esc' && popup) {
				event.stop();
	
				popup.close();
			}	
		});
		
		if(!document.areas && $$('a.country-reference')[0])	{
			new Ajax.RPC({
				'ttl': 600
				}).
				send("cman.GetSections", 1256, 0).
				chain(function(req) { 
					document.areas = req.responseJSON;
				}.bind(this));	
		}
	}
	
	if($('country-lookup'))
	{
		var myRpc = new Ajax.RPC();
		var options = {
			'className'     : 'autocomplete',
			'autocomplete'  : false,
			'valueKey'      : 'title',
			
			'fetch'         : function( value ) {
				var sortedArray = [];
				
				document.countries.each(function() {
					if(new RegExp(value.toString(), 'i').test(this.title))
						sortedArray.push(this);
				});
				
				return sortedArray;
			},
			
			'format'        : function( obj ) {
				return ( obj.title);
			},
			
			'events'        : {
				'select' : function()   {
					document.location = 'countries/' + this.selected.section + '/' + this.selected.slug + '.html';
				}, 
				'loading' : function()  {
					this.element.addClass('loading');
				},
				'halt'  : function()    {
					this.element.removeClass('loading');
				}
			}
		}	
	}
	
	if( typeof AutoComplete != 'undefined')
		new AutoComplete($('country-lookup'), options);

	
	if(window.ie6) {
		$$('#globeContainer #globe a').each(PNGFix.fix);
	}

 	if($('tabs')) {
		var hash = location.hash.substr(1);
		if( $('tab-'+hash)) {
			ArticleTabs.select($('tab-'+hash).getFirst());
		}
	}

	if ($('rater-my'))
	{
		var myRater = new Rater( $("rater-my"), {
			loginUrl	: loginUrl,
			section		: "photoscope",
			username	: login,
			'ip' 		: ip,
			id		: id,
			'expressions'	: ['Η άποψη σας', 'Εντελώς αδιάφορη', 'Αδιάφορη', 'Ενδιαφέρουσα', 'Πολύ ενδιαφέρουσα', 'Εξαιρετική'],
			'renderExpressions'	: false,
			'save' 	: function () {
				this.loader = $C('img').
				setProperty('src', 'http://c.pathfinder.gr/img/icons/loading-circle.gif').
				setStyles({'position': 'absolute', 'text-align' : 'center', 'top' : 0, 'left' : 0}).
				injectIn(this.container);
				this.loader.show();
			}
		}).build(rate);
	}
	
	if($('media-img-container'))	{
		// construct thumbs array
		var _thumbTable = $T('tbody', $CN('photos-table')[0])[0];
		var _thumbCells = $T('td', _thumbTable);
		var thumbs = [];
		
		var i = 0;
		$T('img', _thumbTable).each(function() { thumbs[i] = this; i++; });
		
		// Construct the slideshow
		var _slideshow	= new Slideshow.Fade( imgs, $('media-img-container'), {		
			width 			: 480,
			height 			: 500,
			autoPlay		: false,
			'gravity' 		: 'n',
			
			onChange : function(index, slide) {
				var thumb 		= thumbs[index -1];
				var thumbPrev	= this.previous ? thumbs[this.previous.index -1] : thumbs[thumbs.length-1];
				var info 		= (imgs[index-1].location ? imgs[index-1].location + " - " : "") + imgs[index-1].date + (imgs[index-1].photoscope ? ' &nbsp;|&nbsp; <a href="' + imgs[index-1].photoscope +  '">η φωτογραφία στο φωτοσκόπιο &raquo;</a>' : '');
				var credit		= (imgs[index-1].author ? imgs[index-1].author + " - " : "") + imgs[index-1].source;
				
				$('media-img-title').innerHTML = imgs[index-1].caption;
				$('media-img-descr').innerHTML = imgs[index-1].descr.stripSlashes();
				$('media-img-info').innerHTML = info;
				$('media-img-tags').innerHTML = 'Tags: ' + imgs[index-1].tags;
				$('media-img-credit').innerHTML = credit;
					
				thumbPrev.getParent().getParent().removeClass('hi');
				thumb.getParent().getParent().addClass('hi');
			},
			
			onLoadComplete : function()	{
				$$('.slideshow').each(function() {
					this.addEvent('click', function() { _slideshow.nextSlide(); });
				});
			}
		});				

		_slideshow.gotoSlide(1);
			
		i = 1;	
		_thumbCells.each(function() {
			var links 	= $T('a', this);
			var cell	= this;
			
			links.each(function() {
				var index = i;
				this.addEvent('click', function() { 
					_slideshow.gotoSlide(index);
					return false; 
				});
			});
			i++;
		});
		
	}

	if ($('breaking-img')) {
		$('breaking-img').addEvent('click', function(){
			new Fx.Slide($('breaking')).slideOut();
			Cookie.set('nobreaking', '1', 3600); 
		});
	}

	/* pharmacies show by area id */
	if ($('area')) {
		$('area').addEvent('change', function(){
			var shown = 0;
			$$('.hospitals ol li').each(function(element) {
				var areaId = $('area').value;
				if (this.getElement('input').value == areaId || areaId == '0') {
					this.show();
					shown++;
				} else
					this.hide();
			})

			if (!shown) {
				$('hospitals').setHTML('<p>Δεν βρέθηκαν εφημερίες.</p>');
			}
		});
	}
});


var More = {
	isLoading 	: false,
	total 		: null,
	fetch 		: function() {
		if(this.isLoading) {
			return false;
		}
		$('more-articles').setClass('loading');
		
		// How many do we have now?
		this.total = $$('#more-cats li').length + 1;
		new Ajax.RPC({
			ttl : 400
		}).send('news.GetCategorySample', document.page, 0, 0, 0, 30, 0).
		chain(this.dump);
	},

	dump : function() {
		var articles = this.responseJSON.articles.splice(More.total +1, 20);
		var html = [];
		articles.each(function(article, index) {
			html.push('<li><a href="'+document.page+'/'+article.id+'.html" onmouseover="previewArticle(this, event)">'+article.title+'</a></li>');	
		});
		$('more-cats').innerHTML += html.join('\n');
		$('more-articles').remove();

	}
}



// Slideshow.Collection
// Slideshow.Collection
Slideshow.Collection = Slideshow.Fade.extend({			
	options: {
		articleImages : null,
		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('');	
		},

		autoPlay	: true,
		leaveDelay	: 800,
		enterDelay	: 100,
		fitImg		: false,
		interval	: 4000,
		height		: 0,
		
		// 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) 	{

			this.counter.setHTML( index + ' - ' + this.slides.length  + '');	
			this.author.setHTML( slide.author ? 'Φώτο: ' + slide.author : '');	
			
			console.log(this.metaElement);
			if(typeof this.metaElement != "undefined")
				this.metaElement.setHTML(slide.descr);
		}
	},
	
	initialize : function(collectionId, options) {
		this.setOptions(options);		
		this.collectionId = collectionId;
	
		if(this.options.height == 0)
			this.options.height = 280;

		var width = '';
		
		if(this.options.width == null)
			width = '100%';
		else
			width = this.options.width+'px';
		
		// Create a placeholder
		document.write('<div id="slideshow-' + $uniqueID(this) + '" style="width: ' + width + '; height: ' + this.options.height + 'px; margin-bottom: 10px; background: #fff;overflow: hidden; position: relative;"></div>');
		
		if(this.options.articleImages !== null)
			$('slideshow-' + $uniqueID(this)).setClass('img right');
			
		// Fetch stuff
		return this.fetch();
	},

	fetch: function() {
		
		if(this.options.articleImages !== null)
			this.process();
		else
			new Ajax.RPC({'ttl': 600}).send('media.GetCollection', this.collectionId, false, 1, 120, true).chain(this.process.bind(this));
		
		return this;
	},
	
	process: function(req) {
		console.log(req);
		if(req) {
			this.meta 	= req.responseJSON;
			this.items	= this.meta.items;
		}
		else
			this.items = this.options.articleImages;
			
		this.slidesFromMedia= [];
		this.items.each(function(item, index) {
			this.slidesFromMedia.push($merge(item, {
				'img'	: item.image,
				'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() {	
		// Call the initialize.parent to initialize
		Slideshow.Fade.prototype.initialize.call(this, this.slidesFromMedia, $('slideshow-'+$uniqueID(this)) );	
		
		// 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'	: '5px 0'				
			}
		}).makeUnselectable();


		// this.metaElement
		if( this.options.articleImages === null)
			this.metaElement= $C('div').
			injectIn(this.overlay).
			set({id : 'slideshow-meta'});
			
		// this.controls
		this.controls = $C('div',{
			'id'		: 'slideshow-controls',
			'styles' 	: {
				'position'	: 'relative',
				'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.controls);

		// this.author
		this.author= $C('div', {
			'id'		: 'slideshow-author',
			'styles'	: {
			}
		}).
		setHTML('').
		injectIn(this.controls);
			
		// 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 - 1;
		this.overlay.restoreBlockStyles().setStyle('bottom', bottom );

		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 -1).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);		
			
		return this;				
	}

});

Slideshow.Collection.Counter = Slideshow.Collection.extend({
	options: {
		start: 100,
		onChange 	: function(index, slide) {
			console.log(slide);
	//		this.metaElement.style.height = '5.2em';
			this.counter.setHTML('# ' + ((this.options.start || this.slides.length) - index + 1));	
			this.author.setHTML( slide.author);	
			this.metaElement.setHTML('<strong> ' + slide.title.replace(/^\d+\./, '') + '</strong><p>' + slide.descr  +'</p>');			
		}
	},
	
	initialize: function() {
		this.parent.apply(this, arguments);
		
		return this;
	}
															   
});


var Popup = new Class({ 
	options : {
		className	: 'reference-popup',
		offset		: {
			x	: 0,
			y	: 25
		}
	},
	
	initialize : function(element, options)	{
	
		// don't define it twice
		if(element.popup)	{
			return false;
		}
			
		this.element = $(element);
		
		// get c|man variables
		if(tmp = this.element.getProperty('rel'))	{
			tmp 		= this.element.getProperty('rel').evalJSON();
			this.id 		= tmp.id;
			this.sectionId 	= tmp.sectionId;	
		}
		
		this.setOptions(options);
		
		// construct container
		this.container = $C('div').setClass(this.options.className).injectIn().hide();
	
		// setup events for element
		this.element.addEvents({
			'click' : function(event) {
				Popup.event = event;
				element.popup.toggle(); 
			}
		});
		
		// content placeholder
		this.content = $C('div').setClass('reference').injectIn(this.container);
		
		// match element and popup
		this.element.popup = this;
		
		return this;
	},
	
	open : function()	{
		// don't do this twice
		if(this.isOpen)
			return this;	
	
		if(Popup.current)
			Popup.current.close();	
			
		this.fetch();
		
		this.isOpen 	= true;
		Popup.current	= this;
		
		this.container.show();
		
		return this.invokeEvent('open');
	},
	
	close : function()	{
		if(!this.isOpen) {
			return this;
		}	
		
		this.isOpen 	= false;		
		Popup.current 	= null;
		
		this.container.hide();
		
		return this.invokeEvent('close');
	},
	
	fetch : function()	{
		// don't do this twice
		if(this.isFetched)
			return this;		
			
		this.isFetched = true;
		
		return this.invokeEvent('fetch');
	},
	
	pos : function()	{
		var initialPos = Popup.event.target.getPosition();
	
		var pos		= {
			left	: initialPos.x + this.options.offset.x,
			top		: initialPos.y + this.options.offset.y
		}

		// Check window viewport
		if(this.container.isHidden()) {
			this.container.setBlockStyles();
		}
		if(pos.left + this.container.offsetWidth > window.getWidth() + window.getScrollTop()) {
			pos.left = window.getScrollLeft()  + window.getWidth() - this.container.offsetWidth;
		}
		if(pos.top + this.container.offsetHeight > window.getHeight() + window.getScrollTop()) {
			pos.top	= window.getScrollTop() + window.getHeight() - this.container.offsetHeight;
		}
	
		pos.top += 'px';
		pos.left += 'px';
		
		//alert(pos.left);
		this.container.restoreBlockStyles().setStyles(pos);
		
		//alert(this.container.style.left);
		
		return this;	
	},
	
	setContent : function(content)	{
		this.content.setHTML(content);
		this.container.setBlockStyles().setStyle('height', this.content.offsetHeight);
		this.pos();
		this.container.restoreBlockStyles();
				
		return this;
	},
	
	toggle		: function() {
		return this[this.isOpen ? 'close': 'open']();
	}
	
}).implement(new Options, new Events);

PopupCountry = Popup.extend({
	
	fetch : function() { 
		if(this.isFetched)
			return this;		
			
		this.isFetched = true;
		
		var self = this;
			
		this.ajax = new Ajax.RPC({
			'ttl'	: 120,
			'onLoading' : function()	{
				self.setContent('<p class="loader">loading</p>');
			}
		}).
		send("cman.GetItem", parseInt(this.sectionId), parseInt(this.id), 1, 0, 2, "iso-8859-7").
		chain(function(req) { 
			var r 		= req.responseJSON;
			var symbol;
			
			// search in areas to find out symbol
			document.areas.each(function() { 
				if(this.id == r.item_section_id)
					symbol = this.symbol;
			});
			
			// render local news
			new Ajax.RPC({
				onLoading : function()	{
					self.setContent('<p class="loader">loading</p>');
				},
				onSuccess : function()	{
					var articles	= $A(this.responseJSON);
					var html 		= [];
					
					html.push('<div class="bar">Σχετικές πληροφορίες <a title="κλείσιμο παραθύρου"></a></div>\n');
			
					html.push('<div class="content">');
					
					// render title & tabs
					html.push('<h1>' + r.item_title + '</h1>');
					html.push('<div class="referenceTabs clr"><ul><li class="active"><a href="javascript:void(0)" onclick="referencePage(this, 1); return false;">σχετικά</a></li><li><a href="javascript:void(0)" onclick="referencePage(this, 2); return false;">ειδήσεις</a></li></ul></div>');
					
					// render country info
					html.push('<div class="referencePage">');
					html.push('<a href="/countries/' + symbol + '/' + r.item_ref_id + '.html"><img src="http://pf.pstatic.gr/CMAN/i/' + r.flag.path + '" width="' + r.flag.width + '" height="' + r.flag.height + '" alt="' + r.item_title + ' flag" class="flag" /></a>');
					html.push('<p>' + r.intro + '</p>');
					html.push('<p class="more"><a href="/countries/' + symbol + '/' + r.item_ref_id + '.html">μάθετε περισσότερα &raquo;</a></p>');
					html.push('</div>');
					
					// render local news
					html.push('<div class="referencePage" style="display: none">');
			
					if(typeof articles === 'undefined' || articles.length == 0)	{
						html.push('<p>Δεν υπάρχουν σχετικά άρθρα.</p>');	
					}
					else if(this.responseJSON.faultCode)	{
						html.push('<p>Πρόβλημα κατά την ανάκτηση δεδομένων.</p>');
					}
					else	{
						html.push('<ol>');
						
						articles.each(function()	{
							html.push('<li>');
							html.push('<a href="' + this.id + '.html">' + this.title + '</a> - <em>' + this.source + '</em>');
							html.push('</li>');
						});
						
						html.push('</ol>');
					}
					
					html.push('</div>');
					html.push('</div>');
					
					self.setContent(html.join(''));
					
					// attach close events to x
					var closer = self.container.getElement('.bar a');
					if(closer)	{
						closer.addEvent('click', function() { this.close(); }.bind(self));
					}	
					
					// implement dragging
					new Drag(self.container, { handle : self.container.getElement('.bar')});
				}
			}).send("news.GetLatestNewsByCountry", parseInt(r['country-id']), 10);
		});
	}
});

PopupLeader = Popup.extend({
	
	fetch : function() {
		// don't do this twice
		if(this.isFetched)
			return this;
		
		var self = this;
	
		this.ajax = new Ajax.RPC({
			ttl 	: 120,
			onLoading : function()	{
				self.setContent('<p class="loader">loading</p>');
			}
		}).send("cman.GetItem", parseInt(this.sectionId), parseInt(this.id), 1, 0, 2, "iso-8859-7").
		chain(function(req) {
			var r = req.responseJSON;
			
			new Ajax.RPC({
				onLoading : function()	{
					self.setContent('<p class="loader">loading</p>');
				},
				onSuccess : function()	{
					var articles	= $A(this.responseJSON.results);
					var html 		= [];
					
					html.push('<div class="bar">Σχετικές πληροφορίες <a title="κλείσιμο παραθύρου"></a></div>\n');
			
					html.push('<div class="content">');
					
					// render title & tabs
					html.push('<h1>' + r.name_first + ' ' + r.name_last + '</h1>');
					html.push('<div class="referenceTabs clr"><ul><li class="active"><a href="javascript:void(0)" onclick="referencePage(this, 1); return false;">βιογραφικό</a></li> <li><a href="javascript:void(0)" onclick="referencePage(this, 2); return false;">ειδήσεις</a></li></ul></div>');
					
					// render biography
					html.push('<div class="referencePage">');
				
					if(r.item_title)
						html.push('<h2>' + r.item_title + '</h2>');
						
					if(r.profession)
						html.push('<h3>' + r.profession + '</h3>');
						
					if(img = r.image)	{
						html.push('<blockquote' + (img.width ? ' style="width: ' + img.width + 'px"' : '') + '>');
						html.push('<img src="http://pf.pstatic.gr/CMAN/i/' + img.path + '" width="' + img.width + '" height="' + img.height + '" />');
						
						if(img.title && img.title.length > 2)
							html.push('<p>' + img.title + '</p>');
							
						html.push('</blockquote>');
					}
					
					if(r.dob)
						html.push('<p><strong>Γεννήθηκε: </strong>' + r.dob + (r.place ? ' (' + r.place + ')' : '') + '</p>');
						
					if(r.dod && r.dod > 10)
						html.push('<p><strong>Πέθανε: </strong>' + r.dod + '</p>');	
						
					if(r.studies)	
						html.push(r.studies.replace(/^\s*?<p>/i, '<p><strong>Σπουδές: </strong>'));
					
					if(r.bio)
						html.push(r.bio.replace(/^\s*?<p>/i, '<p><strong>Βίος: </strong>'));	
						
					if(r.source && r.source == 1)
						html.push('<p>Πηγή: ΑΠΕ</p>');
						
					html.push('</div>');		
						
					// render related news
					html.push('<div class="referencePage" style="display: none">');
			
					if(typeof articles === 'undefined' || articles.length == 0)	{
						html.push('<p>Δεν υπάρχουν σχετικά άρθρα.</p>');	
					}
					else if(this.responseJSON.faultCode)	{
						html.push('<p>Πρόβλημα κατά την ανάκτηση δεδομένων.</p>');
					}
					else	{
						html.push('<ol>');
						
						articles.each(function()	{
							html.push('<li>');
							html.push('<a href="' + this.id + '.html">' + this.title + '</a> - <em>' + this.source + '</em>');
							html.push('<p>' + this.body.substring(0, 80) + '...</p>');
							html.push('</li>');
						});
						
						html.push('</ol>');
					}
					
					html.push('</div>');	
						
					html.push('</div>');
					html.push('</div>');
					
					self.setContent(html.join(''));
					
					// attach close events to x
					var closer = self.container.getElement('.bar a');
					if(closer)	{
						closer.addEvent('click', function() { this.close(); }.bind(self));
					}	
					
					// implement dragging
					new Drag(self.container, { handle : self.container.getElement('.bar')});
				}
			}).send("news.Search", "~" + r.name_last.trim(), "greece", true, 120, false, 1, 10, false);
		});
		
		this.isFetched = true;
		
		return this.invokeEvent('fetch');
	}
});	

PopupCountry.initialize = function(selector, options) {
	$$(selector.push ? selector.join(',') : selector).each(function(element) {
		new PopupCountry(element, options);
	});
};

PopupLeader.initialize = function(selector, options) {
	$$(selector.push ? selector.join(',') : selector).each(function(element) {
		new PopupLeader(element, options);
	});
};

