// Upload related 

var myUpload;



function handleFocus (element) {
		if( !element._original )
			element._original = element.value;
		if( element.value == element._original ) {
			element.value = "";
			document.Node.addClass( element, "acceptable");
		}
	}
function handleBlur (element) {
		if( !element.value ) {
			element.value = element._original;
			document.Node.removeClass( element, "acceptable");
		}
	}

function deleteFolder(id, br, us, ak)
{
	if (confirm('Είστε βέβαιοι για την διαγραφή;'))
		window.location='/view/'+ us + '?action=removeFolder&folderId='+ id +'&bcase='+ br +'&ak='+ak;
	else
		return false;
}

/* checks if one file is picked and submits form for approving */
function goApprove(form)
{
	c=0;
	for (i = 0; i < form.elements.length; i++)
	{
		e = form.elements[i];
		if (e.name == 'picked[]' && e.checked)
			c++;
	}

	if (c < 1)
	{
		alert('Δεν έχετε επιλέξει κανένα αρχείο.');
		return false;
	}
	else
	{
		form.action.value = 'approveFiles';
		form.submit();
	}
	return true;
}
/* checks if one file is picked and submits form for editing */
function goEdit(form)
{
	c=0;
	for (i = 0; i < form.elements.length; i++)
	{
		e = form.elements[i];
		if (e.name == 'picked[]' && e.checked)
			c++;
	}

	if (c > 1)
	{
		alert('Δεν μπορείτε να επεξεργαστείτε περισσότερα από 1 αρχεία ταυτόχρονα.');
		return false;
	}
	else if (c < 1)
	{
		alert('Δεν έχετε επιλέξει κανένα αρχείο.');
		return false;
	}
	else
	{
		form.action.value = 'redirToEdit';
		form.submit();
	}
	return true;
}
/* change action value and submits form */
function goDelete(form)
{
	c=0;
	for (i = 0; i < form.elements.length; i++)
	{
		e = form.elements[i];
		if (e.name == 'picked[]' && e.checked)
			c++;
	}

	if (c < 1)
	{
		alert('Δεν έχετε επιλέξει κανένα αρχείο.');
		return false;
	}
	else
	{
		if (confirm('Είστε βέβαιοι για την διαγραφή;'))
		{
			form.action.value = 'removeFiles';
			form.submit();
		}
	}
	return true;
}

/* pickem all */
function CheckAll(form, ch)
{
	var _color = ch.checked ? "#FFFFDD" : "";
	for (i = 0; i < form.elements.length; i++) {
		e = form.elements[i];
		if (e.name == 'picked[]')
		{
			e.checked = ch.checked;
			e.parentNode.parentNode.style.backgroundColor = _color;
		}
	}
	if (ch.checked)
	{
		$('butCont').style.display = "inline";
		$('butCont2').style.display = "inline";
	}
	else
	{
		document.Node.hide($('butCont'));
		document.Node.hide($('butCont2'));
	}
}

function VForm(form)
{
        var re =  new RegExp("^[a-z._0-9-]+\@[a-z._0-9-]+$", "i");
        if (!re.test(form.recipientEmail.value))
        {
                alert("Παρακαλούμε δώστε ένα έγκυρο email");
                form.recipientEmail.focus();
                return false;
        }

        if (!form.senderName.value)
        {
                alert("Παρακαλούμε δώστε το όνομά σας");
                form.senderName.focus();
                return false;
        }

        if (!form.senderEmail.value)
        {
                alert("Παρακαλούμε δώστε το email σας");
                form.senderEmail.focus();
                return false;
        }

	alert("Η αποστολή του email ήταν επιτυχής.\nΠατήστε [OK] για να μεταφερ8είτε πάλι στη σελίδα του αρχείου.");
        form.submit();
	return true;
}

function PrintPage()
{
	window.print();
	return false;
}

/* check create/edit folder form */
function CheckForm(form, checkTerms)
{
        if (!form.name.value)
        {
                alert("Παρακαλούμε δώστε όνομα");
                form.name.focus();
                return false;
        }

        if (checkTerms && !form.terms.checked)
        {
                alert("Πρέπει να αποδεχτείτε τους όρους χρήσης.");
                return false;
        }

        form.submit();
	return true;
}

function openTitleForm(id)
{
	document.Node.toggle($(id));
	var reg = /^title_(.*?)$/i;
	var ar = reg.exec(id);
	id = ar[1];

	/* toggle div with form */
	document.Node.toggle($('div_title_'+id));
	el = $("photo_title");
	el.value = photoTitle;
	el.select();
	el.focus();
}


function openDescrForm(id)
{
	document.Node.toggle($(id));
	var reg = /^descr_(.*?)$/i;
	var ar = reg.exec(id);
	id = ar[1];

	/* toggle div with form */
	document.Node.toggle($('div_descr_'+id));
	el = $("photo_descr");
	str = photoDescr;
	el.value = str.replace(/<br \/>/g, "\n");
	el.select();
	el.focus();
}

function toggleFavorite(id, el, isFolder) {
	bookmarked = !bookmarked;

	ajax = new Ajax.RPC({
		'onSuccess': function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {
				alert( res.faultString );
			}
			else
			{
				if (bookmarked) {
					with( el ) {
						title = "Προσθήκη στα αγαπημένα";
						src = "http://static.pathfinder.gr/Briefcases/img/star_on.gif";
					}
				} else {
					with( el ) {
						title = "Αφαίρεση από τα αγαπημένα";
						src = "http://static.pathfinder.gr/Briefcases/img/star_off.gif";
					}
				}	
			}
		}
	});
	ajax.send ("briefcases.SetFavorite", parseInt(userId), id, isFolder, bookmarked);
}


function prevFoto(id, args)
{
	var prev=0;
	var next=0;
	args = args.split(",");
	ajax = new Ajax.RPC({
		'onSuccess': function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {
				alert( res.faultString );
				return false;
			}
			else
			{
				prev = res['prev'];
				next = res['next'];

				if (next > 0)
					s = '<a href="'+ url +'/'+ next + '" title="Προηγούμενη φωτογραφία"><img src="/download/'+ next +'?thumb=1"  width="90" heigh="75" /></a>';
				else
					s = '<img src="http://static.pathfinder.gr/Briefcases/img/last_photo.gif"  width="90" heigh="75" />';
				nargs = args[0] +', '+ args[1] +', '+ next +', '+ args[3];
				s = s + '<a href="javascript:void(0)" class="next" onclick="nextFoto('+ next +', '+ nargs +')">more</a>';

				xy = Pos.get ($("move1"));
				var m1 = new Fx.combo( "move1", {
					duration: 	500,
					fx 	: {
						width 	:{
							from : $("move1").width,
							to : 0
							},
						height 	:{to: $("move1").height},
						fade 	:{to: 100},
						move 	:{
							toX: xy.x,
							toY: xy.y
							}
					},

					onComplete: 	function() {
						$("imgRight").innerHTML = s;
					}
				});

				xy = Pos.get ($("move2"));
				var m2 = new Fx.move( "move2", {
					duration: 	1000,
					toX: 		xy.x-100,
					toY: 		xy.y,
					onComplete: 	function() {
						$("imgRight").innerHTML = s;
					}
				});
			}
		}
	});

	ajax.send ("briefcases.GetSequence", args);

}

/* toggle background color of checked box-foto */
function toggleBox(el, i) {
	var _color = el.checked ? "#FFFFDD" : "";
	var _borderColor = el.checked ? "#B7B7B7" : "#CCCCCC";
	$('item'+i).childNodes[0].style.backgroundColor = _color;
	$('item'+i).style.borderColor = _borderColor;

	form = document.filesForm;
	var c = 0;
	for (i = 0; i < form.elements.length; i++) {
		e = form.elements[i];
		if (e.name == 'picked[]')
		{
			if (e.checked)
				c++;
		}
	}
	if (c)
	{
		$('butCont').style.display = "inline";
		$('butCont2').style.display = "inline";
	}
	else
	{
		document.Node.hide($('butCont'));
		document.Node.hide($('butCont2'));
	}
}


/* toggle background color of checked row */
function toggleRow(el, i) {
	var _color = el.checked ? "#FFFFDD" : "";
	el.parentNode.parentNode.style.backgroundColor = _color;

	form = document.filesForm;
	var c = 0;
	for (i = 0; i < form.elements.length; i++) {
		e = form.elements[i];
		if (e.name == 'picked[]')
		{
			if (e.checked)
				c++;
		}
	}
	if (c)
	{
		$('butCont').style.display = "inline";
		$('butCont2').style.display = "inline";
	}
	else
	{
		document.Node.hide($('butCont'));
		document.Node.hide($('butCont2'));
	}
}
function init() {
	Event.add ( "photo_title", "keypress", function (k) {
		if (k.key == 'esc') {
			document.Node.toggle($('div_title_'+ fileId));
			document.Node.toggle($('title_'+ fileId));
		}
	});

	Event.add ( "photo_descr", "keypress", function (k) {
		if (k.key == 'esc') {
			document.Node.toggle($('div_descr_'+ fileId));
			document.Node.toggle($('descr_'+ fileId));
		}
	});

	var myRater = new Rater ( $('rater-my'), {
		loginUrl	: loginUrl,
		section		: "briefcases",
		username	: login,
		id		: parseInt(fileId),
		expressions 	: [ "Η άποψη σας", "Κακή", "Μέτρια", "Καλή", "Πολύ καλή", "Εξαιρετική" ],
		'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(myScore);

	if (0 && isOwner)
	{
		Event.add( "title_"+fileId, "mouseover", function() {
			if (typeof tt != "undefined")
				clearTimeout(tt);
			this.style.background = "#FFFFD3";
		});
		Event.add( "title_"+fileId, "mouseout", function() {
			tt = setTimeout( function() { $("title_"+fileId).style.background = "#FFFFFF"}, 1000);
		});
		Event.add( "descr_"+fileId, "mouseover", function() {
			if (typeof dt != "undefined")
				clearTimeout(dt);
			this.style.background = "#FFFFD3";
		});
		Event.add( "descr_"+fileId, "mouseout", function() {
			dt = setTimeout( function() { $("descr_"+fileId).style.background = "#FFFFFF"}, 1000);
		});

	}
	if (typeof notes != "undefined") {
		for (i=0;i<notes.length;i++) {
			var n = notes[i];
			var html = n.content.trim().replace(/\r\n/gi, "<br />");
			html = html.replace(/\r/gi, "<br />");
			html = html.replace(/\n/gi, "<br />");

			new Img.Note('image', {
				selection: {
					left 	: n.x,
					top 	: n.y,
					right 	: (n.x + n.width),
					bottom 	: (n.y + n.height)
				},
				content : html,
				id 	: n.id,
				readOnly: n.readOnly
			});
		}
	}
}
function removeFile(id){
	$(id).remove();
	ai--;
	}
function addFiles() {
	ai++;
	node = $('files');
	_cond = $C('div');
	if (ai % 2 == 0)
		_cond.className = "odd";
	_cond.id = "file"+ai;
	_cond.setclass = "file";
	add = $C('label')
	add.setAttribute("for", "name"+ai);
	add.innerHTML = "Αρχείο:";
	_cond.appendChild(add);

	add = $C('input')
	add.type = "file";
	add.name = "bf_file[]";
	add.id = "name"+ai;
	_cond.appendChild(add);

	add= $C('a');
	add.href	="javascript:removeFile('file"+ai+"')";
	add.innerHTML = '<img src="/img/trash.gif" width="10" height="10" alt="delete"/> αφαίρεση';
	_cond.appendChild(add);
	
	_cond.innerHTML = _cond.innerHTML + "<br/>";

	add = $C('label')
	add.setAttribute("for", "desc"+ai);
	add.innerHTML = "Περιγραφή:";
	_cond.appendChild(add);

	add = $C('input')
	add.type = "text";
	add.name = "descr[]";
	add.className = "text";
	add.id = "desc"+ai;
	_cond.appendChild(add);

	node.appendChild(_cond);
	$('desc'+ai).focus();

	return false;
}

function PostPhotoTitle(id) {
	var bakTitle = photoTitle;
	photoTitle = $("photo_title").value;
	if (!photoTitle.length)
	{
		photoTitle = bakTitle;
		alert('Παρακαλούμε δώστε τίτλο.');
		$("photo_title").focus();
		return false;
	}

	var method = "briefcases.UpdateFile";

	var b = $("photo_title").value;
	$("photo_title").value = "Αποστολή...";

	ajax = new Ajax.RPC({
		//'host': '10.5.5.8', port: 30033,
		'onSuccess': function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {
				alert( res.faultString );
				photoTitle = bakTitle;
			}
			else
			{
				$("title_"+id).innerHTML = photoTitle;
				document.Node.toggle($( 'div_title_'+id ));
				document.Node.toggle($("title_"+id));
			}
		}
	});

	bcaseId = parseInt(bcaseId);
	userId = parseInt(userId);
	folderId = parseInt(folderId);
	//console.log ([method, bcaseId, folderId, id, userId, "'"+photoTitle+"'", "'"+photoDescr+"'"]);
	ajax.send (method, bcaseId, folderId, id, userId, photoTitle, photoDescr);
	$("photo_title").value = b;
	return false;
}

function PostPhotoDescr(id) {
	var bakDescr = photoDescr;
	photoDescr = $("photo_descr").value;
	if (!photoDescr.length)
	{
		photoDescr = bakDescr;
		alert('Παρακαλούμε δώστε περιγραφή.');
		$("photo_descr").focus();
		return false;
	}

	var method = "briefcases.UpdateFile";

	var b = $("photo_descr").value;
	$("photo_descr").value = "Αποστολή...";

	ajax = new Ajax.RPC({
		//'host': '10.5.5.8', port: 30033,
		'onSuccess': function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {
				alert( res.faultString );
				photoDescr = bakDescr;
			}
			else
			{
				str = photoDescr;
				str = str.replace(/\n/g, "<br \/>");
				$("descr_"+id).innerHTML = str;
				document.Node.toggle($( 'div_descr_'+id ));
				document.Node.toggle($("descr_"+id));
				$("descr_"+id).className = "fotoedit2";
			}
		}
	});
	bcaseId = parseInt(bcaseId);
	userId = parseInt(userId);
	folderId = parseInt(folderId);
	ajax.send (method, bcaseId, folderId, id, userId, "'"+photoTitle+"'", "'"+photoDescr+"'");
	$("photo_descr").value = b;
	return false;
}

/* save an element using ajax rpc. all required method-parameters are inside rpc variable */
function ajaxSave(node, rpc, container, descr, n) {
	ajax = new Ajax.RPC({
		'onSuccess' : function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {
				alert( res.faultString );
			}
			else
			{
				document.Node.hide( container._container);
				container.innerHTML = title;
				container.style.display = "block";
				if( container._sum)
					container._sum.style.display = "block";				
			}
		}
	});

	title = node.value;

	method = rpc[0];
	rpc.shift();
	params = rpc.join( ",") + ", '"+ title + "', "+ "'"+ descr +"'";

	eval("ajax.send('"+ method + "', "+ params + ")");
	//ajax.send(method, rpc);

	return false;
}

/* creates input elements for saving inline */
function editInLine(node, id, descr, title, n) {
	node = $(node);
	if ( !node) 
		return false;

	bcaseId = parseInt(bcaseId);
	folderId = parseInt(folderId);
	userId = parseInt(userId);
	var rpc = ['briefcases.UpdateFile', bcaseId, folderId, id, userId];
	node.style.display = "none";
	if( !node._container) {
		// the container
		node._container = $C("span");

		//node.parentNode.appendChild( node._container);
		node.parentNode.insertBefore(node._container, node);
		node._container.style.display = "none";
	
		
		// the input
		node._input = $C("input");
		node._input.style.width = "10em";
		node._container.appendChild(node._input);
		// Event handler 
		Event.add( node._input, "keydown", function(e) {
			if( e.key == 'esc' ) {
				document.Node.hide( node._container);
				node.style.display = "block";
				if( node._sum)
					node._sum.style.display = "block";				
				Event.stop(e);
			}
			if( e.key == 'return' ) {
				ajaxSave(node._input, rpc, node, descr, n);
				Event.stop(e);
			}
		}
		);
		
		// ok
		node._butOk	= $C("button");
		node._butOk.innerHTML = "OK";
		node._butOk.title = "OK";
		node._container.appendChild(node._butOk);
		document.Node.addClass( node._butOk, "submit bold");

		node._container.appendChild( $CT(" - ή  -"));

		// cancel
		node._butCancel	= $C("button");
		node._butCancel.innerHTML = "x";
		node._butCancel.title = "x";
		node._container.appendChild(node._butCancel);
		document.Node.addClass( node._butCancel, "submit");
		
		node._sum = $T("em",node.parentNode)[0];


		node._butOk.onclick = function() {
			ajaxSave(node._input, rpc, node, descr, n);
			return false;
		}

		node._butCancel.onclick = function() {
			document.Node.hide( node._container);
			node.style.display = "block";
			if( node._sum)
				node._sum.style.display = "block";				
			return false;
		}
	}


	// Attach the value;
	node._input.value = node._input._defaultValue = title;

	node._container.style.display = "block";
	if( node._sum)
		node._sum.style.display = "none";	

	node._input.focus();
	node._input.select();

	return false;
}

var TransferBcase = {
	
	initialize: function() {
		
		if (!$('do-transfer'))
			return;
			
		this.element            = $('transfer-status');
		this.loading            = false;
		this.timer              = 0;
		this.interval           = 1000;
		this.rpc                = new Ajax('post', {
			
			onSuccess : function(result)	{
				
				TransferBcase.loading = false;
				var res               = this.responseJSON;

				if(!res)
					return;

				var total             = res['total'], done = res['done'], failed = res['failed'];

				if (!total || !done)
					return;

				var percent           = (done * 100) / total;
				var html              = percent.round(2) + ' % ('+ done + ' / '+ total +')';
				
				if (failed)
					html += ' ('+ failed +' αποτυχίες';
					
				TransferBcase.element.setHTML(html);

				if (done + failed == total) {
					
					clearInterval(TransferBcase.timer);
					alert('Η μεταφορά των φωτογραφιών ολοκληρώθηκε με επιτυχία.');
					window.location      = 'http://me.pathfinder.gr/'+ window.User.username +'/photos';
				}
			},
			url             : '/tools/socialMethods.php',
			parameters		: {
				'action'	: 'transferBcase',
				'ak'		: window.User.ak
			}
		});

		$('do-transfer').addEvent('click', function() {
			
			if (confirm("Η μεταφορά των άλμπουμ θα μεταφέρει όλες τις φωτογραφίες και μπορεί να διαρκέσει μερικά δευτερόλεπτα.\n\nΕίστε σίγουροι ότι θέλετε να συνεχίσετε;")) {
				
				$('do-transfer').hide();
				TransferBcase.element.setHTML('0%');
				TransferBcase.load();
				TransferBcase.timer = setInterval(TransferBcase.load.bind(TransferBcase), TransferBcase.interval);
			}
		});
	},

	load: function() {
		
		if (this.loading)
			return;
			
		this.loading = true;
		
		this.rpc.send();
	}
};


Event.add( window, "DOMContentLoaded", function() {

	TransferBcase.initialize();

	var myTable = $("gallery");
	var rows = $T("tr", myTable);

	rows.forEachBind( function() {
			var _items = $CN( "item-content", this );
			var _max = 0;
			_items.forEachBind( function() { 
				_max = this.offsetHeight > _max ? this.offsetHeight : _max;
				}
			);
			_items.forEachBind( function() {
				this.style.height = _max + "px";
				}
			);
		}
	);

	// uploader textarea set height, background on focus-blur
	$T('textarea').each(function() {
		if (this.name == 'descriptions[]') {
			this.addEvent('focus', function() {
				this.setStyle('height', '80px');
				this.setStyle('background-color', '#FFFFCC');
			});
			this.addEvent('blur', function() {
				this.setStyle('height', '20px');
				this.setStyle('background-color', '#FFFFFF');
			});
		}
	});

	// uploader input set background on focus-blur
	$T('input').each(function() {
		if (this.name == 'titles[]') {
			this.addEvent('focus', function() {
				this.setStyle('background-color', '#FFFFCC');
			});
			this.addEvent('blur', function() {
				this.setStyle('background-color', '#FFFFFF');
			});
		}
	});
});

Img.Note	= Img.extend({
	'options' 	: {
		snapToClick 	: false,
		center 		: false,
		ratio 		: null,
		knobWidth	: 6,
		knobHeight	: 6,
		selection 	: {
			left 		: 10,
			top 		: 10,
			bottom 		: 50,
			right 		: 50
		},
		minSize	: {
			width	: 30,
			height	: 30
		},
		id 		: 0,
		readOnly 	: false
	},

	initialize 	: function() {
		if (this.anotherEditing()) {
			return false;
		}
		this.parent.apply(this,arguments);

		this.status = 'normal';
		if (!this.options.id) {
			this.options.content = 'Προσθέστε σημείωση';
			this.status = 'compose';
		}

		this.boundWrapperMore = new Abstract({
			'mouseover'	: this.toggle.bind(this),
			'mouseout'	: this.toggle.bind(this)
		});

		var self = this;
		this.ajaxDel = new Ajax.RPC({
			'events' : {
				'success': function() {
					var res = this.responseJSON;
					if (res && res.faultCode) {
						alert( res.faultSrting);
						return false;
					} else {
						self.closeForm();
						self.kill();
					}
					self.toggleLoader(false);
				}
			}
		});

		this.ajaxSave = new Ajax.RPC({
		//'host': '10.5.5.8', port: 30033,
			'events' : {
				'success': function() {
					var res = this.responseJSON;
					if (res && res.faultCode) {
						alert( res.faultSrting);
						return false;
					} else {
						self.options.id 	= parseInt(this.responseText);
						self.options.content 	= self.textarea.value.trim();

						var html = self.textarea.value.trim().replace(/\r\n/gi, "<br />");
						html = html.replace(/\r/gi, "<br />");
						html = html.replace(/\n/gi, "<br />");
						self.text.setHTML(html);
					}
					self.toggleLoader(false);
					self.closeForm();
				}
			}
		});
		this.constructor.current = this;

		if (this.options.readOnly) {
			this.status 		= 'normal';
			this.options.resizable 	= false;
			this.options.movable 	= false;
			this.options.draggable 	= false;
		}


		return this;

	},

	build 	: function() {
		this.parent.apply(this,arguments);

		this.selector.hide();
		this.selector.className = 'selector';
		this.selector.setStyle('border', '1px solid #fff');
		this.overlay.setStyle('opacity', 0.2);

		this.text = $C('div', {
			'styles' : {
				'position'	: 'absolute',
				'top'		: (this.selection.top + this.selection.getHeight() + 10) + 'px',
				'left'		: this.selection.left + 'px',
				'text-align'	: 'left',
				'clear'		: 'both',
				'padding'	: '5px',
				'display'	: 'none',
				'background'	: '#FFFFD3',
				'line-height'	: 'normal',
				'white-space'	: 'nowrap',
				'z-index'	: '10',
				'-moz-border-radius': '5px',
				'_height'	: '1%'
			}
		}).
		setHTML(this.options.content).
		injectIn(this.wrapper);
		this.text.className = 'text-note';

		var pos = this.element.getPosition();
		this.elementPos = {
			'x'	: pos.x,
			'y'	: pos.y
		};

		if (!this.options.readOnly) {
			this.selector.addEvent('mouseup', this.edit.bind(this));
			this.text.addEvent('mouseup', this.edit.bind(this));
		}

		$A(this.knobs).each(Element.hide);
		$A(this.marquees).each(Element.hide);
		this.orSelection = $merge(this.selection);

		this.disableKeys();
		if (this.status == 'compose')
			this.edit();

		return this.invokeEvent('buildNote');
	},

	mousedown : function(event) {
		this.parent.apply(this,arguments);
		this.constructor.current = this;

		if (this.options.readOnly)
			return this;

		// if dragging stop other events
		if (event.target.isWithin(this.selector)) {
			for (var i = 0;i < this.constructor.instances.length; i++) {
				var t = this.constructor.instances[i];
				if (t != this)
					t.stop();
			}
		}
	},
	mousemove	: function(event) {
		this.parent.apply(this,arguments);
		this.mousePos = event.client;
	},

	start 	: function() {
		this.parent.apply(this,arguments);

		each(this.boundWrapperMore, function(fn, type){
			this.wrapper.addEvent( type, fn);
		}, this);
	},

	stop 	: function() {
		this.parent.apply(this,arguments);

		each(this.boundWrapperMore, function(fn, type){
			this.wrapper.removeEvent( type, fn);
		}, this);		
	},

	disableKeys 	: function() {
		each(this.boundDoc, function(fn, type){
			if (/key.*?/.test(type))
				document.removeEvent( type, fn);
		});
	},
	enableKeys 	: function() {
		each(this.boundDoc, function(fn, type){
			if (/key.*?/.test(type))
				document.addEvent( type, fn);
		});
	},

	// show / highlight / hide selector, text
	toggle 		: function(event) {
		for (var i = 0;i < this.constructor.instances.length; i++) {
			var t = this.constructor.instances[i];
			if ((t.dragger && t.dragger.isDragging) || t.isMoving || (t.status == 'edit' || t.status == 'compose'))
				return;
		}

		// TODO optimize
		if (event.type == "mouseover") {
			if (event.target == this.overlay || event.target == this.selector) {
				if (!this.options.readOnly)
					this.selector.setStyle('border-color', 'yellow');
				this.text.show();
			} else if (event.target == this.element) {
				this.selector.show();
			} else if (event.target == this.text) {
				this.cEnter = true;
			}
		}

		if (event.type == "mouseout") {
			var inEl = false;
			if (event.relatedTarget == this.element || (event.relatedTarget && (event.relatedTarget.className == 'img-overlay' || event.relatedTarget.className == 'text-note' || event.relatedTarget.className == 'selector')))
				inEl = true;

			if (event.target == this.overlay) {
				this.selector.setStyle('border-color', '#fff');
				this.checkEnter.delay(300, this);

			} else if (event.target == this.element && !this.cEnter && !inEl) {
				this.selector.hide();
			} else if (event.target == this.text) {
				this.selector.setStyle('border-color', '#fff');
				this.cEnter = false;
				this.text.hide();
			}
		}
		return this;
	},

	checkEnter 	: function() {
		if (!this.cEnter) {
			this.selector.setStyle('border-color', '#fff');
			this.text.hide();
		}
	},

	edit 		: function() {
		if (this.status == 'edit' || this.anotherEditing())
			return this;

		this.constructor.current = this;
		// hide other selectors
		for (var i = 0;i < this.constructor.instances.length; i++) {
			var t = this.constructor.instances[i];
			if (t != this)
				t.selector.hide();
		}

		// if not dragging stop events
		if (!this.dragger.isDragging) {
			for (var i = 0;i < this.constructor.instances.length; i++) {
				var t = this.constructor.instances[i];
				if (t != this) {
					t.stop();
				}
			}
		}

		if (this.status != 'edit') {
			$A(this.knobs).each(Element.show);
			$A(this.marquees).each(Element.show);
		}
		if (this.status != 'compose')
			this.status = "edit";

		this.selector.setStyle('border', 'none');
		this.text.hide();
		if (!this.form)
			this.buildForm();

		if (this.status == 'compose') {
			this.selector.show();
		}
		this.enableKeys();

		return this;
	},

	buildForm 	: function() {
		this.form = $C('form').
		setStyles({
			'position' 	: 'absolute',
			'top'		: (this.selection.top + this.selection.getHeight() + 10) + 'px',
			'left'		: this.selection.left + 'px',
			'margin'	: 0,
			'clear'		: 'both',
			'width' 	: '18em',
			'z-index'	: 50
		}).injectAfter(this.selector);

		var self = this, v = this.options.content;
		var t = $C('textarea').
		setStyles({
			'display'	: 'block',
			'margin-bottom'	: '5px',
			'padding'	: '5px',
			'border'	: 'none',
			'background'	: '#FFFFD3',
			'width'		: '18em',
			'height'	: '5em',
			'-moz-border-radius': '4%',
			'overflow'	: 'auto'
		}).
		setHTML(this.options.content.trim().replace(/<br \/>/gi, "\r\n")).
		addEvent('keypress', function(e) {
			if (e.key == 'esc')
				self.closeForm();
		}).
		injectIn(this.form);

		t.select();
		t.focus();
		this.textarea = t;

		var ok = $C('button').
		setStyles({
			'color'		: 'white',
			'background'	: '#0063DC',
			'color'		: 'white'
		}).
		setHTML(' OK ').
		addEvent('click', this.save.bind(this)).
		injectIn(this.form).
		setProperty('type', 'button');

		this.form.appendChild( $CT( " " ));

		var ca = $C('button').
		setHTML('\'Ακυρο').
		addEvent('click', this.closeForm.bind(this)).
		injectIn(this.form).
		setProperty('type', 'button');


		if (this.options.id) {
			this.form.appendChild( $CT( " " ));

			var de = $C('button').
			setHTML('Διαγραφή').
			addEvent('click', this.delNote.bind(this)).
			injectIn(this.form).
			setProperty('type', 'button');
		}

		return this;

	},
	anotherEditing : function() {
		if (this.constructor.instances)
		for (var i = 0;i < this.constructor.instances.length; i++) {
			var t = this.constructor.instances[i];

			if ((t.status == 'edit' || t.status == 'compose') && t != this) {
				return true;
			}
		}

		return false;

	},
	render 	: function(event) {
		// if another note is editing, then do not drag/render this
		if (this.anotherEditing())
			return this;

		this.parent.apply(this,arguments);

		if (this.dragger.isDragging) {
			this.text.setStyles({
				'top'		: (this.selection.top + this.selection.getHeight() + 10) + 'px',
				'left'		: this.selection.left + 'px'
			});
			if (this.status == 'edit' || this.status == 'compose') {
				this.form.setStyles({
					'top'		: (this.selection.top + this.selection.getHeight() + 10) + 'px',
					'left'		: this.selection.left + 'px'
				});
			}
		} else if (this.form && (this.status == 'edit' || this.status == 'compose')) {
			this.form.setStyles({
				'top'		: (this.selection.top + this.selection.getHeight() + 10) + 'px',
				'left'		: this.selection.left + 'px'
			});
		}

		return this;
	},

	closeForm 	: function() {
		this.status = "normal";
		// hide marquees, knobs, keypress events
		$A(this.knobs).each(Element.hide);
		$A(this.marquees).each(Element.hide);
		
		this.selector.setStyle('border', '1px solid #fff');
		this.setSelection(this.orSelection);
		this.text.setStyles({
			'top'		: (this.selection.top + this.selection.getHeight() + 10) + 'px',
			'left'		: this.selection.left + 'px'
		});

		// start events
		for (var i = 0;i < this.constructor.instances.length; i++) {
			var t = this.constructor.instances[i];
			if (t != this)
				t.start();
		}

		// check if mouse is outside of element hide all selectors
		if (this.mousePos && (this.mousePos.x > this.elementPos.x + this.elementSize.width || this.mousePos.y > this.elementPos.y + this.elementSize.height)) {
			this.constructor.instances.each(function(t) { t.selector.hide(); });
		}
		this.form.remove();
		this.form = null;

		this.disableKeys();
		if (!this.options.id) {
			this.kill();
			return false;
		}

		return this;
	},

	save 	: function() {
		this.orSelection = $merge(this.selection);
		
		this.toggleLoader(true);
		bcaseId = parseInt(bcaseId);
		fileId = parseInt(fileId);
		userId = parseInt(userId);
		if (this.options.id)
			this.ajaxSave.send('briefcases.ModifyNote', this.options.id, bcaseId, fileId, userId, this.selection.left, this.selection.top, this.selection.getWidth(), this.selection.getHeight(), "'"+this.textarea.value.trim()+"'");
		else
			this.ajaxSave.send('briefcases.AddNote', bcaseId, fileId, userId, this.selection.left, this.selection.top, this.selection.getWidth(), this.selection.getHeight(), "'"+this.textarea.value.trim()+"'");
	},

	toggleLoader 	: function(show) {
		if (!this.loader) {
			this.loader = $C("div").
			setStyles({
				'width' 	: '100px',
				'height' 	: '60px',
				'top' 		: '50%',
				'left' 		: '50%',
				'border' 	: '2px solid #f6f6f6',
				'margin-top' 	: '-50px',
				'margin-left' 	: '-30px',
				'background' 	: '#fff url(\'http://c.pathfinder.gr/img/icons/loading-circle.gif\') no-repeat center center',
				'z-index' 	: '999',
				'position' 	: 'absolute'
			}).
			injectAfter(this.element);
		}

		if (show)
			this.loader.show();
		else
			this.loader.hide();
	},

	delNote 		: function() {
		if (confirm('Είστε σίγουροι για την διαγραφή;')) {
			this.toggleLoader(true);
			this.ajaxDel.send('briefcases.DelNote', this.options.id, parseInt(userId), parseInt(bcaseId));
		}
	}
});
function ValidateForm(form) {
	var tot = form.total_files.value;

	for (var i =1; i <= tot; i++) {
		if (!$('title-'+ i).value.trim().length) {
			alert('Παρκαλούμε δώστε τίτλο σε όλα τα αρχεία');
			$('title-'+ i).focus();
			return false;
		}
	}

	return true;
}

