/* mootools extend */
Element.implement({
	show: function() {
		if (this.hasClass('hidden')) {
			this.removeClass('hidden');
		} else {
			this.setStyle('display', '');
		}
		return this;
	},
	
	hide: function() {
		this.addClass('hidden');
		return this;
	}
});
	
function selectAllListItems(ctrl) {
  obj = document.getElementById("id"+ctrl);
  if (obj!=null)
    for (var i=0; i<obj.options.length; i++)
      obj.options[i].selected = true
}

function addSelectOption(lst, optionValue, optionText) {
  if (document.all)
  {
    var oOption = document.createElement("OPTION");
    lst.options.add(oOption);
    oOption.innerText = optionText;
    oOption.value = optionValue;
  }
  else
  {
    var oOption = new Option(optionText, optionValue, false, false);
    lst.options[lst.options.length]=oOption;
  } 	
}

// JS Calendar
var calendar = null; // remember the calendar object so that we reuse
// it and avoid creating another

// This function gets called when an end-user clicks on some date
function selected(cal, date) {
	cal.sel.value = date; // just update the value of the input field
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks the "Close" (X) button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
	cal.hide();			// hide the calendar

	// don't check mousedown on document anymore (used to be able to hide the
	// calendar when someone clicks outside it, see the showCalendar function).
	Calendar.removeEvent(document, "mousedown", checkCalendar);
}

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
function checkCalendar(ev) {
	var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
	for (; el != null; el = el.parentNode)
	// FIXME: allow end-user to click some link without closing the
	// calendar.  Good to see real-time stylesheet change :)
	if (el == calendar.element || el.tagName == "A") break;
	if (el == null) {
		// calls closeHandler which should hide the calendar.
		calendar.callCloseHandler(); Calendar.stopEvent(ev);
	}
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id) {
	var el = document.getElementById(id);
	if (calendar != null) {
		// we already have one created, so just update it.
		calendar.hide();		// hide the existing calendar
		calendar.parseDate(el.value); // set it to a new date
	} else {
		// first-time call, create the calendar
		var cal = new Calendar(true, null, selected, closeHandler);
		calendar = cal;		// remember the calendar in the global
		cal.setRange(1900, 2070);	// min/max year allowed
		calendar.create();		// create a popup calendar
	}
	calendar.sel = el;		// inform it about the input field in use

	calendar.showAtElement(el);	// show the calendar next to the input field

	// catch mousedown on the document
	Calendar.addEvent(document, "mousedown", checkCalendar);
	return false;
}

/**
* Pops up a new window in the middle of the screen
*/
function popupWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=0';
	win = window.open(mypage, myname, winprops);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

function popupGallery(mypage) {
	popupWindow(mypage, "wGallery", 600, 480, false);
}


// LTrim(string) : Returns a copy of a string without leading spaces.
function ltrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(0)) != -1) {
      var j=0, i = s.length;
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      s = s.substring(j, i);
   }
   return s;
}

//RTrim(string) : Returns a copy of a string without trailing spaces.
function rtrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;       // Get length of string
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }
   return s;
}

// Trim(string) : Returns a copy of a string without leading or trailing spaces
function trim(str) {
   return rtrim(ltrim(str));
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;
	if(!d) d=document;
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n);
	return x;
}
function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments;
	document.MM_sr=new Array;
	for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;
	if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr;
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
	var d=document;
	if(d.images){
	if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
	for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

/**
* @param object A form element
* @param string The name of the element to find
*/
function getElementByName( f, name ) {
	if (f.elements) {
		for (i=0, n=f.elements.length; i < n; i++) {
			if (f.elements[i].name == name) {
				return f.elements[i];
			}
		}
	}
	return null;
}

function winObject()
{
  if (typeof(_winobject_prototype_called) == "undefined")
  {
    _winobject_prototype_called = true;
    winObject.prototype.addEvent = addEvent;
    winObject.prototype.removeEvent = removeEvent;
    winObject.prototype.close = close;
  }

	function addEvent(objObject, strEventName, fnHandler) { 
	  if (objObject.addEventListener) {
	    objObject.addEventListener(strEventName, fnHandler, false); 
	  }
	  else if (objObject.attachEvent) {
	    objObject.attachEvent('on' + strEventName, fnHandler); 
	  }
	}
	function removeEvent(objObject, strEventName, fnHandler) { 
	  if (objObject.addEventListener) {
	    objObject.removeEventListener(strEventName, fnHandler, false); 
	  }
	  else if (objObject.attachEvent) {
	    objObject.detachEvent('on' + strEventName, fnHandler); 
	  }
	}
	function close() {
		window.close();
	}
}

/* ##################### */
/* ## TRIM HANDLERS ## */
/* ##################### */
function Trim(Value, CharTrimOf){
    if(Value.length < 1) return"";
    Value = RTrim(Value);
    Value = LTrim(Value);
    
    return Value;
}

function RTrim(Value, CharTrimOf){
    var v_length = Value.length;
    var strTemp = "";
    
    if(v_length < 0) return"";

    var iTemp = v_length -1;
    
    while (iTemp > -1){
        if(Value.charAt(iTemp) != CharTrimOf){
            strTemp = Value.substring(0,iTemp +1);
            break;
        }
        iTemp = iTemp-1;
    }
    return strTemp;
}

function LTrim(Value, CharTrimOf){
    var v_length = Value.length;
    
    if(v_length < 1) return"";

    var strTemp = "";
    var iTemp = 0;

    while(iTemp < v_length){
        if(Value.charAt(iTemp) != CharTrimOf){
            strTemp = Value.substring(iTemp,v_length);
            break;
        }
        iTemp = iTemp + 1;
    }
    return strTemp;
}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

var enabletabpersistence=0;
var tabcontentIDs=new Object();

function expandcontent(linkobj){
	var ulid=linkobj.parentNode.parentNode.id;
	var ullist=document.getElementById(ulid).getElementsByTagName("li");
	for (var i=0; i<ullist.length; i++){
		ullist[i].className="";
		if (typeof tabcontentIDs[ulid][i]!="undefined")
			document.getElementById(tabcontentIDs[ulid][i]).style.display="none";
	}
	linkobj.parentNode.className="selected";
	document.getElementById(linkobj.getAttribute("rel")).style.display="block";
	saveselectedtabcontentid(ulid, linkobj.getAttribute("rel"));
}

function expandtab(tabcontentid, tabnumber){
	var thetab=document.getElementById(tabcontentid).getElementsByTagName("a")[tabnumber];
	if (thetab.getAttribute("rel"))
		expandcontent(thetab);
}

function savetabcontentids(ulid, relattribute){
	if (typeof tabcontentIDs[ulid]=="undefined")
		tabcontentIDs[ulid]=new Array();
	tabcontentIDs[ulid][tabcontentIDs[ulid].length]=relattribute;
}

function saveselectedtabcontentid(ulid, selectedtabid){
	if (enabletabpersistence==1)
		setCookie(ulid, selectedtabid);
}

function getullistlinkbyId(ulid, tabcontentid){
	var ullist=document.getElementById(ulid).getElementsByTagName("li");
	for (var i=0; i<ullist.length; i++){
		if (ullist[i].getElementsByTagName("a")[0].getAttribute("rel")==tabcontentid){
			return ullist[i].getElementsByTagName("a")[0];
			break;
		}
	}
}

function initializetabcontent(){
	for (var i=0; i<arguments.length; i++){
		if (enabletabpersistence==0 && getCookie(arguments[i])!="")
			setCookie(arguments[i], "");
		var clickedontab=getCookie(arguments[i]);
		var ulobj=document.getElementById(arguments[i]);
		var ulist=ulobj.getElementsByTagName("li");
		for (var x=0; x<ulist.length; x++){
			var ulistlink=ulist[x].getElementsByTagName("a")[0];
			if (ulistlink.getAttribute("rel")){
				savetabcontentids(arguments[i], ulistlink.getAttribute("rel"));
				ulistlink.onclick=function(){
					expandcontent(this);
					return false;
				};
				if (ulist[x].className=="selected" && clickedontab=="")
					expandcontent(ulistlink);
			}
		}
		if (clickedontab!=""){
			var culistlink=getullistlinkbyId(arguments[i], clickedontab);
			if (typeof culistlink!="undefined") {
				expandcontent(culistlink);
			} else {
				expandcontent(ulist[0].getElementsByTagName("a")[0]);
			}
		}
	}
}

function getChildById(o, id) {
	var c=o.childNodes;
	for (var i=0; i<c.length; i++) {
		if (c[i].id !== 'undefined' && c[i].id == id)
			return c[i];
		if (c[i].hasChildNodes()) {
			var e = getChildById(c[i], id);
			if (e !== null) return e;
		}
	}
	return null;
}

function formatDate(dt) {
	var y=Number(dt.substr(0,4));
	var m=Number(dt.substr(5,2));
	var d=Number(dt.substr(8,2));
	var h=dt.substr(11,5);
	return d+"/"+m+"/"+y+" "+h;
}

var IceSecurity = Class.create({
	_id: "",
	_sign: "",
	_vid: 0,
	_vsign: "",
	_vcode: "",
	_otype: 0,
	_oid: 0,
	_archived: 0,
	_o: "",
	_t: "",
	_page: null,
	_friends: [],
	_ping: false,
	_infoc: 0,
	
	initialize: function() {
		this._page = new IcePage(this);
	},
	
	initc: function(otype, oid, archived) {
		this._otype = otype;
		this._oid = oid;
		this._archived = archived;
	},
	
	init: function(o, t) {
		this._o=o;
		this._t=t;
		var p=this._page;
		try {pageTracker._trackPageview("/init-page");} catch (e) {}
		new Ajax.Request('/init-page', {
		  parameters: {'o': o, 't': t, 'otype': this._otype, 'oid': this._oid, 'archived': this._archived},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	p.update(data);
		  	p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα...') }
		  });
	},
	
	login: function(el) {
		var p=this._page;
		var pars=$H($('frmLogin').serialize(true));
		pars.update({'o':this._o, 't':this._t});
		this._page.setBusy();
		try {pageTracker._trackPageview("/login");} catch (e) {}
		new Ajax.Request('/login', {
		  parameters: pars.toObject(),
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	if (!Object.isUndefined(data.message) && data.message != '')
		  		alert(data.message);
		  	p.update(data);
		  	p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα κατά την σύνδεση.\nΠροσπαθήστε ξανά.') }
		  });
	},
	
	logout: function(el) {
		var p=this._page;
		this._page.setBusy();
		try {pageTracker._trackPageview("/logout");} catch (e) {}
		new Ajax.Request('/logout', {
		  parameters: {},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	p.update(data);
		  	p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα κατά την αποσύνδεση.\nΠροσπαθήστε ξανά.') }
		  });
	},
	
	getComments: function(page) {
		var p=this._page;
		p.setBusy2();
		try {pageTracker._trackPageview("/get-comments");} catch (e) {}
		new Ajax.Request('/get-comments', {
		  parameters: {'otype': this._otype, 'oid': this._oid, 'archived': this._archived, 'page': page},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
			p.setStats(data);
			p.setComments(data);
			p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα κατά την διαδικασία.\nΠροσπαθήστε ξανά.') }
		  });
	},
	
	getUserInfo: function(p, id) {
		if (!this._ping && this._infoc > 10) return;
		try {pageTracker._trackPageview("/user-info");} catch (e) {}
		new Ajax.Request('/user-info', {
		  parameters: {'uid':id, 'vcode':p._sec._vcode, 'ping':p._sec._ping?1:0},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	p.updateFriends(data);
		  	p.updateInfo(data);
		  	p.log(data);
		  },
		  onFailure: function(){}
		  });
		this._infoc++;
	},
	
	sendInvitation: function(uid, wid) {
		var p=this._page;
		p.setBusyDialog(wid);
		try {pageTracker._trackPageview("/send-invitation");} catch (e) {}
		new Ajax.Request('/send-invitation', {
		  parameters: {'uid':uid},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	p.updateDialog(wid, data);
			p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα κατά την διαδικασία.\nΠροσπαθήστε ξανά.') }
		  });
	},
	
	sendPM: function(uid, wid) {
		var f=$('pmForm');
		if (f.message.value.strip() == '') {
			alert('Θα πρέπει να συμπληρώσετε το μήνυμα.');
			return;
		}
		var p=this._page;
		var pars=$('pmForm').serialize(true);
		p.setBusyDialog(wid);
		try {pageTracker._trackPageview("/send-pm");} catch (e) {}
		new Ajax.Request('/send-pm', {
		  parameters: pars,
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	p.updateDialog(wid, data);
			p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα κατά την διαδικασία.\nΠροσπαθήστε ξανά.') }
		  });
	},
	
	acceptFriend: function(uid, fn) {
		var p=this._page;
		try {pageTracker._trackPageview("/accept-invitation");} catch (e) {}
		new Ajax.Request('/accept-invitation', {
		  parameters: {'uid':uid},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	fn(uid, data);
			p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα κατά την διαδικασία.\nΠροσπαθήστε ξανά.') }
		  });
	},
	
	rejectFriend: function(uid, fn) {
		var p=this._page;
		try {pageTracker._trackPageview("/reject-invitation");} catch (e) {}
		new Ajax.Request('/reject-invitation', {
		  parameters: {'uid':uid},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	fn(uid, data);
			p.log(data);
		  },
		  onFailure: function(){ alert('Πρόβλημα κατά την διαδικασία.\nΠροσπαθήστε ξανά.') }
		  });
	},
	
	startChat: function(uid) {
		var p=this._page;
		new Ajax.Request('/start-chat', {
		  parameters: {'uid':uid},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	if (!Object.isUndefined(data.id))
		  		popupWindow("/chat/?id="+data.id, "chat_"+data.id, 300, 300, '0');
		  	p.log(data);
		  },
		  onFailure: function(){}
		  });
	},
	
	postComment: function() {
		var p=this._page;
		if (!this.loggedOn()) return;
		var c=trim($("comment").value);
		if (c.length==0) return;
		$("post-button").disabled=true;
		new Ajax.Request('/post-comment', {
		  parameters: $('commentForm').serialize(true),
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
			p.setStats(data);
			p.setComments(data);
			p.log(data);
			$("post-button").disabled=false;
			$("comment").value='';
			setRating(0);
		  },
		  onFailure: function(){
		  	$("post-button").disabled=false;
		  }
		  });
	},
	
	deleteComment: function(id, ref) {
		var p=this._page;
		if (!this.loggedOn()) return;
		new Ajax.Request('/delete-comment', {
		  parameters: {'id':id, 'archived':this._archived},
		  onSuccess: function(transport,json) {
		  	var data = transport.responseText.evalJSON();
		  	if (!Object.isUndefined(ref)) {
		  		var u=window.location.href;
		  		window.location.href=u;
		  	} else {
				p.setStats(data);
				p.setComments(data);
				p.log(data);
		  	}
		  },
		  onFailure: function(){
		  }
		  });
	},
	
	registerUpdate: function(fn) {
		this._page.registerUpdate(fn);
	},
	
	setPing: function() {
		this._ping=true;
	},
	
	loggedOn: function() {
		return (this._id !== "");
	},
	
	isVisitor: function() {
		return (this._vid > 0);
	},
	
	id: function() {
		return this._id;
	},
	
	sign: function() {
		return (this._vid > 0) ? this._vsign : this._sign;
	}
});


var IcePage = Class.create({
	_sec: null,
	_timer: null,
	_updateCallbacks: [],
	
	initialize: function(sec) {
		this._sec = sec;
	},
	
	update: function(data) {
		id = data['uid'];
		if (id !== null) {
			this._sec._id = id;
			this._sec._vcode = data.vcode;
			if (id === "") {
				$("login-wait").hide();
				$("ice-ok-login").hide();
				$("ice-no-login").show();
				showCommentForm(false);
				if (this._timer != null) {
					this._timer.stop();
					this._timer=null;
					this._sec._infoc=0;
				}
			} else { // logged on
				$("login-wait").hide();
				$("ice-no-login").hide();
				$("ice-ok-login").show();
				$("ice-username").innerHTML=data['username'];
				$("ice-avatar").src=data['avatar'];
				$("ice-sign-avatar").src=data['sign_avatar'];
				
				if (!Object.isUndefined(data.mmenu)) {
					var u=$('member-menu');
					data.mmenu.each(function(e) {
						var l=document.createElement('li');
						l.innerHTML=e;
						u.appendChild(l);
					});
				}
				
				if (!Object.isUndefined(data.stardome)) {
					var d=$('comments-extra');
					if (d != null) {
						d.innerHTML=data.stardome;
						d.show();
					}
				}
				
				showCommentForm(true);
				if (this._timer == null) {
					var p=this;
					this._timer = new PeriodicalExecuter( function(pe) { p._sec.getUserInfo(p, data.id) }, 60);
				}
			}
		}
		//this.updateInfo(data);
		//this.updateFriends(data);
		this.setStats(data);
		this.setComments(data);
		if (typeof _pageUpdate === 'function')
			_pageUpdate(data);
		for (var i=0; i<this._updateCallbacks.length; i++)
			this._updateCallbacks[i](data);
	},
	
	updateInfo: function(data) {
		// inbox
		if (data.invitations > 0) {
			$('invitations').innerHTML="Έχεις <b>"+data.invitations+"</b> νέες <a href='/my-invitations/'>προσκλήσεις</a>";
			$('invitations').show();
		} else {
			$('invitations').hide();
		}
		// pm
		if (data.pms > 0) {
			$('pms').innerHTML="Έχεις <b>"+data.pms+"</b> νέα <a href='/my-messages/'>μηνύματα</a>";
			$('pms').show();
		} else {
			$('pms').hide();
		}
	},
	
	setStats: function(data) {
		var st=data['stats'];
		if (typeof st === 'undefined') {
			return;
		}
		$('ctotal').innerHTML=st.comments;
		$('rtotal').innerHTML=this.getRatingHTML(st.rating);
		if (st.comments > st.limit) {
			try { $('call').show() } catch (e) {};
			if (st.pages > 1) {
				var h='<div align="center">';
				if (st.page > 1)
					h+='<a href="#" onclick="_sec.getComments('+(st['page']-1)+'); return false;">&laquo; προηγούμενα '+st['limit']+' σχόλια</a>';
				if (st.page < st.pages)
					h+='&nbsp;&nbsp;<a href="#" onclick="_sec.getComments('+(st['page']+1)+'); return false;">επόμενα '+st['limit']+' σχόλια &raquo;</a>';
				h+='</div>';
				$('cpages').innerHTML=h;
				$('cpages').show();
			}
		}
	},
	
	clearComments: function() {
		var cul = $("commentsposted");
		var c = cul.childNodes;
		while (c.length > 1) {
			var ch=c[c.length-1];
			cul.removeChild(ch);
		}
	},
	
	setComments: function(data) {
		var w=$('c-wait');
		if (w !== null)
			w.hide();
		var vComments=data['comments'];
		if (typeof vComments !== 'undefined') {
			var cli = $("comment-prototype");
			var cul = $("commentsposted");
			var c = cul.childNodes;
			while (c.length > 1) {
				var ch=c[c.length-1];
				cul.removeChild(ch);
			}
			for (var i=0, len=vComments.length; i<len; i++) {
				var tli=cli.cloneNode(true);
				tli.removeAttribute("id");
				tli.setAttribute("class", "block");
				var a = getChildById(tli, "c-author");
				a.innerHTML=vComments[i].username;
				a.href += vComments[i].username;
				if (vComments[i].username == 'Stardonna' ||
					vComments[i].username == 'Stardhomme') {
					Element.addClassName(a, 'member-stardome');
				}
				getChildById(tli, "c-comment").innerHTML=vComments[i].comment;
				if (vComments[i].username == 'gpano' ||
					vComments[i].username == 'Stardonna' ||
					vComments[i].username == 'Stardhomme') {
					var e=getChildById(tli, "c-comment");
					Element.addClassName(e, 'gpano');
				} else if (typeof _commentFix === 'function') {
					_commentFix(data, vComments[i], tli);
				}
				getChildById(tli, "c-date").innerHTML=formatDate(vComments[i].date);
				var d = getChildById(tli, "c-delete");
				d.id = "com_"+vComments[i].id+"_"+vComments[i].userid;
				var a = getChildById(d, "c-delete-a");
				a.href="javascript:_sec.deleteComment("+vComments[i].id+");";
				var im=getChildById(tli, "c-avatar");
				im.src="/templates/ice_site/images/sav_"+vComments[i].sign+".gif";
				cul.appendChild(tli);
				var f=getChildById(tli, "c-friend");
				f.id="invite_"+vComments[i].userid;
				var a=Element.firstDescendant(f);
				a.href="javascript:showInvite(this, '"+vComments[i].username+"', '"+vComments[i].userid+"');";
				var f=getChildById(tli, "c-pm");
				f.id="pm_"+vComments[i].userid+"_"+vComments[i].id;
				var a=Element.firstDescendant(f);
				a.href="javascript:showPM(this, '"+vComments[i].username+"', '"+vComments[i].userid+"');";
				if (vComments[i].rating > 0) {
					var r=getChildById(tli, "c-rating");
					r.innerHTML = this.getRatingHTML(vComments[i].rating);
					Element.show(r);
				}
			}
		}
		this.updateFields(data);
		var p = $("post-button");
		if (p !== null)
			p.disabled=false;
	},
	
	updateFields: function(data) {
		var e=document.getElementsByTagName('DIV');
		for (var i=0, len=e.length; i<len; i++) {
			if (typeof(e[i].id) != 'undefined' && e[i].id != '') {
				if (e[i].id.substr(0,4) == 'com_') {
					var p=e[i].id.split('_');
					if (p.length == 3 && p[2] == this._sec.id()) {
						e[i].style.display='';
					} else {
						e[i].style.display='none';
					}
				}
				if (e[i].id.substr(0,7) == 'invite_') {
					var p=e[i].id.split('_');
					if (p.length == 2 && this.isFriend(p[1],data)) {
						e[i].style.display = 'none';
					}
				}
			}
		}
	},
	
	updateFriends: function(data) {
		var f=data['friends'];
		if (typeof f === 'undefined') {
			return;
		}
		$('friends').innerHTML="";
		var u=document.createElement("ul");
		for (var i=0, len=f.length; i<len; ++i) {
			this._sec._friends.push(f[i].userid);
			var l=document.createElement("li");
			var im=document.createElement("img");
			im.src="/templates/ice_site/images/sav"+(f[i].online?"o":"")+"_"+f[i].sign+".gif";
			im.border="0";
			im.className="none";
			l.appendChild(im);
			var un=document.createElement("a");
			un.href="/profile/"+f[i].username;
			un.target="_blank";
			un.innerHTML=f[i].username;
			un.className="padl5";
			l.appendChild(un);
			var a=document.createElement("a");
			a.href="javascript:showPM(this, '"+f[i].username+"', '"+f[i].userid+"');";
			a.className="padl5";
			var im=document.createElement("img");
			im.src="/templates/ice_site/images/pm.gif";
			im.border="0";
			im.className="none";
			a.appendChild(im);
			l.appendChild(a);
			/*if (f[i].online) {
				var img="chat.gif";
				for (j=0; j<data.chats.length; ++j) {
					if (data.chats[j].userid == f[i].userid) {
						img="chat2.gif";
						break;
					}
				}
				var a=document.createElement("a");
				a.href="javascript:_sec.startChat('"+f[i].userid+"');";
				a.className="padl5";
				var im=document.createElement("img");
				im.src="/templates/ice_site/images/"+img;
				im.border="0";
				im.className="none";
				a.appendChild(im);
				l.appendChild(a);
			}*/
			u.appendChild(l);
		}
		$('friends').appendChild(u);
	},
	
	updateDialog: function(wid, data) {
		Windows.getWindow(wid).setHTMLContent('<br/><center>'+data.message+'</center><br/><div align="center"><input type="button" class="dialog_button" value="Κλείσιμο" onclick="Windows.close(\''+wid+'\', event);"/></div>');
	},
	
	setBusy: function() {
		$("ice-ok-login").hide();
		$("ice-no-login").hide();
		$("login-wait").show();
	},
	
	setBusy2: function() {
		this.clearComments();
		$("c-wait").show();
		$("cpages").hide();
	},
	
	setBusyDialog: function(wid) {
		var w=Windows.getWindow(wid);
		w.setHTMLContent('<br/><div align="center"><b>παρακαλώ περιμένετε...</b></div>');
	},
	
	showBusyDialog: function() {
		win = new Window({className: "bluelighting", title: "", width:250, height:100, destroyOnClose: true, recenterAuto:true, resizable:false, draggable:false, minimizable:false, maximizable:false}); 
		win.getContent().update('<br/><div align="center"><b>παρακαλώ περιμένετε...</b></div>'); 
		win.showCenter(true);
		return win.getId();
	},
	
	closeDialog: function(wid) {
		Windows.close(wid,null);
	},
	
	getRatingHTML: function(r) {
		var h="";
		for (i=1; i<=r; i++)
			h+='<img src="/templates/ice_site/images/star_rf.gif" border="0"/>';
		for (i=r; i<6; i++)
			h+='<img src="/templates/ice_site/images/star_re.gif" border="0"/>';
		h+='<br class="clearboth"/>';
		return h;
	},
	
	registerUpdate: function(fn) {
		this._updateCallbacks.push(fn);
	},
	
	isFriend: function(id, data) {
		if (id == this._sec.id())
			return true;
		for (var i=0, len=this._sec._friends.length; i<len; ++i)
			if (this._sec._friends[i] == id)
				return true;
		return false;
	},

	log: function(data){
		var l=$('log');
		var lo=data['log'];
		if (l !== null && typeof lo !== 'undefined') {
			h="";
			l.setStyle({overflowY:'auto', left:'278px', width:'728px', height:'90px', 'backgroundColor':'#ffffff', 'zIndex':'99999'});
			for (var i=0; i<lo.length; ++i) {
				h+=lo[i]+"<br/>";
			}
			l.innerHTML=h;
		}
	}
	
});

/*
function IcePage() {
	var _tokens = null;
	var _pageQuery = "";
	
	this.init = function(pq, t) {
		_pageQuery = pq;
		var q = getPageQuery("task=status");
		iceAjax.call("/ice.php", q, onAjaxCompleteJs, t);
	};
	
	this.updateStats = function(c, tokens) {
		_tokens = tokens;
		setCommentsCount(c);
	};
	
	this.setComments = function(vComments) {
		var cli = top.document.getElementById("comment-prototype");
		var cul = top.document.getElementById("commentsposted");
		var c = cul.childNodes;
		while (c.length > 1) {
			var ch=c[c.length-1];
			cul.removeChild(ch);
		}
		for (var i=0; i<vComments.length; i++) {
			var tli=cli.cloneNode(true);
			tli.removeAttribute("id");
			tli.setAttribute("class", "block");
			var a = getChildById(tli, "c-author");
			a.innerHTML=vComments[i].author;
			a.href += vComments[i].author_id;
			getChildById(tli, "c-comment").innerHTML=vComments[i].comment;
			getChildById(tli, "c-date").innerHTML=formatDate(vComments[i].date);
			var d = getChildById(tli, "c-delete");
			d.id = "com_"+vComments[i].id+"_"+vComments[i].author_id;
			var a = getChildById(d, "c-delete-a");
			a.href="javascript:page.deleteComment("+vComments[i].id+");";
			cul.appendChild(tli);
		}
		showCommentsDelete();
		top.document.getElementById("post-button").disabled=false;
	};
	
	this.postComment = function() {
		if (!sec.loggedOn()) return;
		var c=trim(top.document.getElementById("comment").value);
		if (c.length==0) return;
		top.document.getElementById("comment").value="";
		top.document.getElementById("post-button").disabled=true;
		var q = getPageQuery("task=post_comment&comment="+c);
		iceAjax.call("/ice.php", q, onAjaxCompleteJs, _tokens[0]);
	};
	
	this.deleteComment = function(id) {
		if (!sec.loggedOn()) return;
		if (!confirm("Θέλετε να διαγράψετε το σχόλιό σας;")) return;
		var q = getPageQuery("task=delete_comment&id="+id);
		iceAjax.call("/ice.php", q, onAjaxCompleteJs, _tokens[1]);
	}
	
	this.query = function() {
		return _pageQuery;
	};
	
	// callbacks
}

function IceComment(id, author, author_id, date, comment) {
	this.id=id;
	this.author=author;
	this.author_id=author_id;
	this.date=date;
	this.comment=comment;
}

function CarVersion() {
	this.id=null;
	this.name=null;
	this.d1=null;
	this.d2=null;
	this.d3=null;
	
	this.d4=null;
	this.d5=null;
	this.d6=null;
	this.d7=null;
	this.d8=null;
	this.d9=null;
	this.d10=null;
	this.d11=null;
	
	this.d12=null;
	this.d13=null;
	this.d14=null;
	this.d15=null;
	this.d16=null;
	this.d17=null;
	this.d18=null;
	
	this.d19=null;
	this.d20=null;
	this.d21=null;
	this.d22=null;
	this.d23=null;
	this.d24=null;
	this.d25=null;
	this.d26=null;
	this.d27=null;
}*/

function checkReturn(e, el) {
    if (e.keyCode == 13)
		if ($("username").value != '')
	    	_sec.login(el);
}

var LoginElement = Class.create({
	_id: null,
	_elem: null,
	_label: null,
	_value: null,
	
	initialize: function(cid, ftype) {
		this._id=ftype;
		this._value=(ftype=='username')?'ψευδώνυμο':'συνθηματικό';
		var e=document.createElement("input");
		Element.writeAttribute(e, {'type':(ftype=='username')?'text':'password', 'id':ftype, 'name':(ftype=='username')?ftype:'passwd', 'size':12, 'maxlength':40});

		Element.addClassName(e, 'inputbox');
		Element.setStyle(e, {'display':'none'});
		e.title=(ftype=='username')?'Γράψε το ψευδώνυμό σου':'Γράψε το συνθηματικό σου';
		Event.observe(e, 'blur', this.checkBlur.bindAsEventListener(this));
		Event.observe(e, 'keydown', this.checkKey.bindAsEventListener(this));
		this._elem=e;
		$(cid).appendChild(e);
		var lbl=document.createElement('input');
		Element.writeAttribute(lbl, {'type':'text', 'id':ftype+"_label", 'size':12, 'value':this._value});
		Element.addClassName(lbl, 'inputbox disabled');
		lbl.title=(ftype=='username')?'Γράψε το ψευδώνυμό σου':'Γράψε το συνθηματικό σου';
		Event.observe(lbl, 'focus', this.checkFocus.bindAsEventListener(this));
		$(cid).appendChild(lbl);
	},
	
	checkFocus: function(event) {
		$(this._id+'_label').hide();
		$(this._id).show();
		$(this._id).focus();
	},
	
	checkBlur: function(event) {
		var v=$(this._id).value.strip();
		if (v == '') {
			$(this._id).value='';
			$(this._id).hide();
			$(this._id+'_label').show();
		}
	},
	
	checkKey: function(event) {
    	if (event.keyCode == 13)
			if ($("username").value != '')
	    		_sec.login(Event.element(event));
	}
});

/*
function getPageQuery(q) {
	if (page.query() != '')
		q += "&"+page.query();
	return q;
}

function onAjaxCompleteJs() {
	var r = iceAjax.getText();
	try { eval(r); } catch (e) {alert(e);};
}

function onAjaxComplete() {
	var r = iceAjax.getText();
	alert(r);
}

function setCommentsCount(n) {
	var i=1;
	while (true) {
		var e=top.document.getElementById("ice-comments"+i);
		if (e === null)
			break;
		e.innerHTML=n;
		i++;
	}
}*/

function showCommentForm(b) {
	var e = $("ice-comment-form");
	if (e !== null) e.style.display=(b ? 'block' : 'none');
	e = $("ice-comment-login");
	if (e !== null) e.style.display=(b ? 'none' : 'block');
}

/*function showCommentsDelete() {
	var e=document.getElementsByTagName('DIV');
	for (var i=0; i<e.length; i++) {
		if (typeof(e[i].id) != 'undefined' && e[i].id != '') {
			if (e[i].id.substr(0,4) == 'com_') {
				var p=e[i].id.split('_');
				if (p.length == 3 && p[2] == sec.id()) {
					e[i].style.display='';
				} else {
					e[i].style.display='none';
				}
			}
		}
	}
}*/

function getElementY(e) {
	var r=0;
	while(e!=null) {
		r+=e.offsetTop;
		e=e.offsetParent;
	}
	return r;
}

function getElementX(e) {
	var r=0;
	while(e!=null) {
		r+=e.offsetLeft;
		e=e.offsetParent;
	}
	return r;
}

function fixUrl(el) {

	if (_sec.loggedOn() || _sec.isVisitor())
		el.href+=_sec.sign()+"/";
	//else if (_sec.isVisitor())
	//	el.href+=_sec.sign()+"/";
}

function writePostsWidget(id) {
   	var so = new SWFObject("http://www.stardome.gr/widgets/sd_posts.swf?v=1.0", "_sd_posts", "150", "302", "9");
	so.addParam("quality", "high");
   	so.addParam("wmode", "transparent");
   	so.addParam("allowscriptaccess", "always");
   	so.useExpressInstall("/media/expressinstall.swf");
   	so.write(id);
}

function writeCommentsWidget(id) {
   	var so = new SWFObject("http://www.stardome.gr/widgets/sd_comments.swf?v=1.0", "_sd_posts", "150", "302", "9");
	so.addParam("quality", "high");
   	so.addParam("wmode", "transparent");
   	so.addParam("allowscriptaccess", "always");
	so.write(id);
}

function writeStarsWidget(id) {
   	var so = new SWFObject("http://www.stardome.gr/widgets/stars.swf?v=1.0", "_sd_stars", "810", "30", "9");
	so.addParam("quality", "high");
   	so.addParam("wmode", "transparent");
   	so.addParam("allowscriptaccess", "always");
   	so.write(id);
}


var visible_tooltip=null;

function tooltip_show(icon_link) {
	var tooltip=Element.previous(icon_link);//.previousSibling;
	tooltip.show();
	tooltip.setStyle({zIndex:1});
	if(tooltip.hasClassName('loaded_tooltip')) {
		visible_tooltip=tooltip;
		return;
	}
	var w=tooltip.firstDescendant().getWidth();
	var h=tooltip.firstDescendant().getHeight();
	tooltip.setStyle( {
		width:w+"px", 
	 	left:-((w-20)/2)+"px",
	 	top:-(h+20)+"px"
	});
	tooltip.addClassName('loaded_tooltip');
	visible_tooltip=tooltip;
}

function tooltip_hide(icon_link) {
	var tooltip=icon_link.previousSibling;
	tooltip.hide();
}

function setRating(v) {
	$('rating').value=v;
	for (var i=1; i<=v; ++i)
		$('r'+i).src="/templates/ice_site/images/star_rf.gif";
	for (var i=v+1; i<=6; ++i)
		$('r'+i).src="/templates/ice_site/images/star_re.gif";
}

function showInvite(e, uname, uid) {
	if (!_sec.loggedOn()) {
		alert("Θα πρέπει να είσαι μέλος για να προσκαλέσεις φίλους.");
		return;
	}
	win = new Window({className: "bluelighting", title: "Πρόσκληση", width:250, height:100, destroyOnClose: true, recenterAuto:true, resizable:false, draggable:false, minimizable:false, maximizable:false}); 
	win.getContent().update("<br/><center>Το μέλος <b>"+uname+"</b> θα λάβει πρόσκληση για να γίνει φίλος/φίλη σου.</center><br/><div align='center'><input type='button' class='button' value='Αποστολή' onclick='_sec.sendInvitation(\""+uid+"\", \""+win.getId()+"\");'/>&nbsp;<input type='button' class='button' value='&#902;κυρο' onclick='Windows.close(\""+win.getId()+"\",event);'/></div>"); 
	win.showCenter(true);
}

function showPM(e, uname, uid, rid) {
	if (!_sec.loggedOn()) {
		alert("Θα πρέπει να είσαι μέλος για να στείλεις προσωπικό μήνυμα.");
		return;
	}
	var rh="";
	if (typeof rid !== 'undefined')
		rh = "<input type='hidden' name='rid' value='"+rid+"'/>";
	win = new Window({className: "bluelighting", title: "Προσωπικό μήνυμα", width:300, height:200, destroyOnClose: true, recenterAuto:true, resizable:false, draggable:false, minimizable:false, maximizable:false, onload:function() {$('pmForm')['subject'].focus();} }); 
	win.getContent().update("<br/><center>Στείλε ένα προσωπικό μήνυμα στο μέλος <b>"+uname+"</b>.</center><br/><form id='pmForm'><input type='hidden' name='uid' value='"+uid+"'/>"+rh+"<div>Θέμα:</div><input type='text' name='subject' size='40'/><br/><div>Μήνυμα:</div><textarea name='message' cols='40' rows='4'></textarea>  </form><br/> <div align='center'><input type='button' class='button' value='Αποστολή' onclick='_sec.sendPM(\""+uid+"\", \""+win.getId()+"\");'/>&nbsp;<input type='button' class='button' value='&#902;κυρο' onclick='Windows.close(\""+win.getId()+"\",event);'/></div>"); 
	win.showCenter(true);
	
	//var e=$('pmForm')['subject'];//Form.Element.focus('subject');
	//alert("field="+e);
}

function iceMail() {
	var h=escape(window.location.href);
	var t=document.title;
	popupWindow('/mail/?h='+h+'&t='+t, 'mailwin', 400, 230, '1');
}

function icePrint() {
	var h=window.location.href;
	var a=h.split('/');
	h=a[0]+"//"+a[2]+"/print/";
	for (i=3; i<a.length; ++i)
		if (trim(a[i]) != '')
			h+=a[i]+"/";
	if (h.endsWith('.html/')) {
		h=h.substring(0,h.length-1);
	}
	popupWindow(h, 'printwin', 660, 460, '1');
}

var IceMenu = new Class({
	initialize: function() {
		this.timers = [];
		$('mainlevel-topleft').getElements('li a').each(function(e, i) {
			this.timers[i+1] = null;
			e.addEvent('mouseenter', function() {
				$clear(this.timers[i+1]);
				this.show(e, i+1);
			}.bind(this));
			e.addEvent('mouseleave', function() {
				this.hide(e, i+1);
			}.bind(this));
			
			var s = $('submenu-'+(i+1));
			if (s != null) {
				s.addEvent('mouseenter', function() {
					$clear(this.timers[i+1]);
				}.bind(this));
				s.addEvent('mouseleave', function() {
					this.hide(e, i+1);
				}.bind(this));
			}
		}.bind(this));
	},
	
	show: function(el, i) {
		var s = $('submenu-'+i);
		if (s != null) {
			var p = el.getPosition();
			s.setStyles({'left':(p.x-5), 'top':(p.y+22)}).show();
		}
	},
	
	hide: function(el, i) {
		var s = $('submenu-'+i);
		if (s != null) {
			this.timers[i] = this.hide2.delay(300, this, i);
		}
	},
	
	hide2: function(i) {
		$('submenu-'+i).hide();
		this.timers[i] = null;
	}
	
});

function showGallery(gid, pid) {
	var url='/gallery/'+gid;
	if ($defined(pid)) url += '/'+pid;
	popupWindow(url, 'galleryMaxim', 600, 400);
}

function showImage(id) {
	var url='/picture/'+id;
	popupWindow(url, 'galleryMaxim', 600, 400);
}


var _sec=new IceSecurity();