// js here
var Guestbooks = {
	
	/**
	 * Toggle a tab
	 *
	 * @param tab A tab to switch to
	 */
	toggleTab :function(tab, e ) {
		// Already here?
		if( tab.parentNode.className == "active") {
			tab.blur();
			return;
		}
			
		tab = $(tab); // The tab
			
		// We want your parentNode honey, not u
		tab = tab.parentNode;
		if (typeof e == "undefined")
			e = "tabs";
	
		// Gather all tabs
		// And then hide em all but the active one
		var allTabs = $T( "li", $(e));	
		
		$A(allTabs).forEachBind( function() { 
			
			var thisId = this.id.toString().replace( /tab-/, "" );
					
			document.Node.removeClass( this, "active")
			document.Node.hide( "box-" + thisId );
			if (typeof actTab != "undefined")
				actTab = thisId;
			
			// The active one
			if( this == tab ) {
				document.Node.addClass( this, "active" );
				
				var box = $("box-" + thisId );
				document.Node.show( box);
				
				// Focus on the first  element if applicable
				var inputs = $T( "input", $("box-" + thisId));	
				$A(inputs).forEachBind( function() { 
					if ( this.type == "text" )
					{
						this.focus();
						return;
					}
				});
				var tas = $T( "textarea", $("box-" + thisId));	
				if (tas.length)
					tas[0].focus();
			}
			
		});
	},

	toggleSide : function() {
		var s = $("side"), m = $("main");
		if( document.Node.isHidden(s)) {
			document.Node.show(s);
			m.style.marginRight = "220px";
		}
		else {
			document.Node.hide(s);
			m.style.marginRight = "0px";
		}
	},

	showHelp : function( node ) {
		// Switch source
		node.src = node.src.replace( /\-off.gif/, ".gif");	
		
		if( !node._tooltip ) {
			var _msg = node.title
			node.title = "";
			
			node._tooltip = $C("div");
			node._tooltip.className = "tooltip";
			Briefcase._posHelp( node );
		
			node._tooltip.innerHTML = _msg.replace( /\r\n/gi, "<br /><br />");
			
			
			document.body.appendChild(node._tooltip);
			document.Node.setOpacity( node._tooltip, 0 );
			
			document.Node.addClass( document.body, 'helphover');	
			node._fade = new Fx.fade( node._tooltip, {
									 duration: 200,
									 from: 0,
									 to: 97
									 }
									 );
		}
		else {
			document.Node.addClass( document.body, 'helphover');	
			Briefcase._posHelp( node );			
			node._fade.from		 =0;
			node._fade.to		= 97;
			node._fade.start();
		}
	},

	_posHelp : function(node) {
		var xy = Pos.get(node);
		var wid= self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
		pos = Pos.get(node);

		leftpos = xy.x + 20;
		toppos = xy.y - 15 ;
		if (xy.x + 400 > wid)
		{
			leftpos = wid - 440;
			toppos = pos.y + 15;
		}
		
		with(node._tooltip.style){
			position	= "absolute";
			left 		= leftpos + "px";
			top		= toppos + "px";
		}
	},
	hideHelp : function(node) {
		document.Node.removeClass( document.body, 'helphover');	
		node.src = node.src.replace( /.gif/, "-off.gif");
		if( node._tooltip ) {
			node._fade.from 	= 97;
			node._fade.to 		= 0;
			node._fade.start();
		}
	},
	/**
	 * Character counter on elements.
	 *
	 * @param element The element to check on
	 */
	handleCount : function (element, limit, fn) { 
		var l = element.value.length;
		if( l > limit ) {
			element.value = element.value.substr(0,limit);
		}
		fn( element.value.length, limit );
	},
	
	renderCount : function( count, limit ) {
		this.innerHTML = limit - count;	
	},

	/**
	 * Handle pale focusing
	 *
	 * @param element The element to check on
	 */
	handleInput   : function(node) {
		if( document.Node.hasClass (node, "pale")) {
			if( node.nodeName == "INPUT") {
				node._defaultValue = node.value;
				node.value = "";
			}
			document.Node.removeClass( node, "pale");
		}
		else {
			if( node.nodeName  == "INPUT" ) {
				if( node.value.trim() == "" || node.value ==  node._defaultValue ) {
					document.Node.addClass (node, "pale");
					node.value = node._defaultValue;
				}
			}
			else 
				document.Node.addClass (node, "pale");

		}	
	},

	handleSubmit : function( form ) {
		// Title check
		if( form.title.value.trim().length < 5 ) {
			alert( "Το μέγεθος του τίτλου θα πρέπει να ξεπερνάει τους 5 χαρακτήρες");
			form.title.focus();
			return false;
		}	

		if( form.title.value.trim().length > 60 ) {
			alert( "Το μέγεθος του τίτλου δεν πρέπει να ξεπερνάει τους 60 χαρακτήρες");
			form.title.focus();
			return false;
		}
		
		// Body check
		if (form.isText.value=='0')
		{
			s = myRTE.getContent().trim();
			s = s.replace( /&nbsp;/, "");
		}
		else
			s = form.pbody.value;

		if( s.length < 10 ) {
			alert( "Το μέγεθος του μηνύματος θα πρέπει να ξεπερνάει τους 10 χαρακτήρες");
			myRTE.focus();
			return false;			
		}
		
		doConfirm = false;
		return true;
	}
}

function CheckPass(f, shortPass) {
	if( f.gbId.value.trim().length < 3 ) {
		alert(shortPass);
		f.gbId.focus();
		return false;
	}
	return true;
}

/* check if picked some checkboxes and submit form */
function deleteRecs(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(delMsg);
		return false;
	}
	else
	{
		if (confirm(delConfirm))
		{
			form.action.value = 'deleteRecs';
			form.submit();
		}
	}
	return true;
}

/* change row class depending and button label on checkbox */
function recCheck(ch, cl, form) {
	//ch.parentNode.parentNode.className = ch.checked ? "checked" : cl;

	c=0;
	for (i = 0; i < form.elements.length; i++)
	{
		e = form.elements[i];
		if (e.name == 'picked[]' && e.checked)
			c++;
	}
	f = '';
	if (form.name == "notApproved")
		f = "2";

	elname = 'buttonsCont'+f;
	del = 'doDelete'+f;
	appr = 'doApprove'+f;

	if (c)
	{
		$(elname).style.visibility = 'visible';
		$(del).value = butMsg+' ('+ c +')';
		if ($(appr))
			$(appr).value = butMsg2+' ('+ c +')';
	}
	else
		$(elname).style.visibility = 'hidden';
}


/* check all checboxes in the form */
function checkAll(form, el) {
	chall = !chall;
	var c = 0;
	for (var i = 0; i < form.elements.length; i++)
	{
		e = form.elements[i];
		if (e.type == 'checkbox')
		{
			e.checked = chall;
			c++;
		}
	}

	f = '';
	if (form.name == "notApproved")
		f = "2";
	elname = 'buttonsCont'+f;
	del = 'doDelete'+f;
	appr = 'doApprove'+f;

	if (!chall)
	{
		el.innerHTML = cAllStr;
		$(elname).style.visibility = 'hidden';
	}
	else
	{
		el.innerHTML = uncAllStr;
		$(elname).style.visibility = 'visible';
		$(del).value = butMsg+' ('+ c +')';
		if ($(appr))
			$(appr).value = butMsg2+' ('+ c +')';
	}
	return false;
}

/* check a form submit */
function checkForm(form) {
	if (form.subject.value.length < 2) {
		alert(subErr);
		$('subject').focus();
		return false;
	}
	if (form.body.value.length < 2) {
		alert(bodErr);
		$('body').focus();
		return false;
	}
	return true;
}
/* check a form submit */
function checkInfoForm(form) {
	if (form.fullname.value.length < 2) {
		alert(subErr);
		$('fullname').focus();
		return false;
	}
	if (form.email.value.length < 2) {
		alert(bodErr);
		$('email').focus();
		return false;
	}
	return true;
}
/*
Check a option Form
*/
function checkOptions (form ){
	if ( form.gbtitle.value.length < 3 ){
		alert(titleErr);
		$('gbtitle').focus();
		return false;
	}
	pages = parseInt(form.entries_per_page.value);
	if ( pages < 1  || (form.entries_per_page.length < 1)  ){
		alert(pagesErr);
		$('entries_per_page');
		return false;
	} 
	
	return true;
}

/* check a field */
function checkFieldsForm(form) {

	if (form.entryname.value.length < 2) {
		alert(nameErr);
		$('entryname').focus();
		return false;
	}
	if (form.description.value.length < 2) {
		alert(subErr);
		$('description').focus();
		return false;
	}

	if (form.type.value == "dropdownlist" || form.type.value =="radiolist" ){
		if (form.list.value.length >= 0 && form.list.value.length < 3){
			alert(dropDownError);
			return false;
		}
	}
	if(form.width.value.length == 0)	{
		alert(widthErr);
		$('width').focus();
		return false;
	}
	
	if(form.height.value.length == 0)	{
		alert(heightErr);
		$('height').focus();
		return false;
	}
	
	
	return true;
} 

/* allow only numbers */
function onlyNumbers(e) {
	var key, keychar;
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;

	keychar = String.fromCharCode(key);
	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
		return true;

	// numbers
	else if ((("0123456789").indexOf(keychar) > -1) || keychar == "-")
		return true;

	return false;

}
/* check pass on form submit */
function checkPassForm(form) {
	if (form.password.value.length < 2) {
		alert(subErr);
		$('password').focus();
		return false;
	}
	if(form.send_thankyou_mail.checked == "1" && (form.thankyou_sub.value.length < 2 || form.thankyou_data.value.length < 2))	{
		alert(emailErr);
		$('thankyou_sub').focus();
		return false;
	}
	
	return true;
}

/* check if picked some checkboxes and submit form */
function approveRecs(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(delMsg);
		return false;
	}
	else
	{
		form.action.value = 'approveRecs';
		form.submit();
	}
	return true;
}
/* forms page checker */
function checkCustomCode(form) {
	if (form.use_custom_code.checked && form.form_entry.value.trim().length < 2)
	{
		alert(err);
		if (actTab != "mn1")
			Guestbooks.toggleTab($('amn1'));

		$('form_entry').focus();
		return false;
	}
	return true;
}

/* toggle mail text fields */
function toggleFields(el, w) {
	if (w == 1) {
		$('thankyou_data').disabled = !el.checked;
		$('thankyou_sub').disabled = !el.checked;
		
		if(!el.checked)	{
			$('thankyou_data').className = "disabled";
			$('thankyou_sub').className = "text disabled";
		}
		else if (el.checked)	{
			$('thankyou_sub').focus();
			$('thankyou_sub').className = "text";
			$('thankyou_data').className = "";
		}
	} else if (w == 2) {
		$('form_entry').disabled = !el.checked;
		$('form_entry').className = "disabled";
		
		if (el.checked)	{
			$('form_entry').focus();
			$('form_entry').className = "";
		}
	}
}

function toggleCPicker ( node, e, theme ) {
	var xy = Pos.get(node);
	if ($('customTh'))
		$('customTh').checked = true;
	if (!node.cpicker ) {
		var coords = node.getCoordinates();

		node.cpicker = new CPicker ({
			color 	: "#"+ node.value,
			theme	: theme,
			//onClose : function()  { node.cpicker = null ; },
			onChange : function() { 
				var c = this.color.rgbToHex();

				node.value = c.replace(/#/g,'').toUpperCase();
				node.style.color = new Color(this.color).invert().hex;
				node.style.backgroundColor = c;
			}
		}).open(null, {'position': { 'top': coords.top, 'left': coords.left + coords.width}});
	}
	else 
		node.cpicker.toggle();
		
	//Event.stop(e);
}
// RowSorter Class
RowSorter			 = Core.newClass();

RowSorter.prototype	 = {
	drag 		: null,	

	// GetOrder();
	getOrder : function() { 
		return this.drag.getOrder();
	},
		
	init : function( tableNode, args ) {
		Object.extend( this, args );
	
		tableNode = $(tableNode);
		var $object 	= this;
		this.drag = new Drag( tableNode, {
			
			initialized : null,
			clone		: null,
			
			offsets		: [],
			prevOffset  : null,
			curOffset	: null,

			cont		: tableNode,			
			contOParent	: null,
			order		: null,
			gbId		: null,
			orderPrev	: null,
			
			// CalcOffsets - offsetTops
			calcOffsets : function() {
				var $obj 		= this;
				this.offsets 	= []; // Init the array
				var cnt 		= 0;
				$T(this.node.nodeName.toLowerCase(), this.tBody).forEachBind( function() {
						document.Node.disableSelect(this);
						// Assign the pos here
						if ($object.order && !this.sorterPos )
							this.sorterPos = $object.order[cnt++];
						var ar = [ this, this.offsetTop];
						$obj.offsets.push( ar );
					}
				);			
			},
			
			getOrder	: function() { 
				if( this.order )
					this.orderPrev = this.order;
					
				var $obj	 	= this;
				this.order 		= [];
				var _db = "";
				
				$T(this._defNode.nodeName.toLowerCase(), this.cont).forEachBind( function() {	
					if (this.sorterPos)
						$obj.order.push( this.sorterPos);
				});	
			
				return this.order;
			},
			
			// Get the previous node
			getB4		: function( offset ) {
				// Calculate the node height - if not done already	
				if( !this.nodeHeight)
					this.nodeHeight = this.node.offsetHeight;
				$obj = this;
				
				// Get the applicable elements
				// Return the previous, last or first element depending on the offsetTop.
				var ret =  this.offsets.filter( function(el) {  return el[1] - $obj.nodeHeight/2 <= offset } );
				if( ret.last())  {
					if ( offset >  $obj.nodeHeight + ret.last()[1] ) {
						return -1;				
					}
					else
						return (ret.last());	
				}
				else {
					return (this.offsets[0] );
				}
					
			},
			
			onDragStart : function() {
			
				// TODO: Change the holder here
				if( !this.contOParent ) {
					this.contOParent = this.cont.parentNode;
					this.cont.parentNode.style.position = "relative";
				}
					
			
				this.curOffset = null;
				this.prevOffset = null;
				
				// Assign the scope to the tr		
				var t = Event.target(this.e);
				if( t.nodeName != "TR" )
					t = t.parentNode;
				
				if( t.nodeName != "TR" )
					return -1;
			
				if( t.parentNode.nodeName != "TBODY" )
					return -1;

				this.node = this.root = t;	
				
				// Get the tbody
				if( this.cont )
					this.tBody = $T("tbody", this.cont)[0];
				
				// Calculate the offsets
				this.calcOffsets();
			
				// Register the node we started from	
				this._defNode 				= this.node;
				this._defNode.className 	= "sorter-source"; 
				// And clone it too...
				this.clone 					= this.node.cloneNode(true);
		
				// Get its position		
				var xy = Pos.getOffset(this.node);
				
				// Now we need a temp table to host the cloned node
				var _tempTable 			= $C("table");
				var _tempTB 			= $C("tbody");
				_tempTable.cellSpacing = _tempTable.cellPadding = 0;
					
				_tempTable.appendChild(_tempTB);
				_tempTB.appendChild(this.clone);
		
				
				// Append it	
				this.contOParent.appendChild( _tempTable);
				
				document.Node.disableSelect(_tempTable);
				// Assign the drag node to the temp table and make it absolute positioned with the 
				// xy of the source node
				this.node = this.root 		= _tempTable;
				this.node.style.position 	= "absolute";
				this.node.zIndex			= 9999;
				this.node.style.left 		= xy.x + "px";
				this.node.style.top 		= xy.y + "px";
		
				// Attach the drag class
				this.node.className = "sorter-drag";
				// And give it some opacity
				document.Node.setOpacity( this.node, 50);
			},
			
			onDragEnd	: function() {
			
				this.node.className = "";
				if( this.curOffset ) {
					document.Node.removeClass( this.curOffset, "sorter-prev");
				}
				
		
				if( this.curOffset && this.curOffset != this._defNode)  {					
					document.Node.remove(this._defNode);
					_tb = $T("tbody", this.cont)[0];
					
					if( this.curOffset != -1 ) {
							 //alert( "e");
							 lala = _tb.insertBefore( this.clone, this.curOffset );
							 document.Node.removeClass( this.clone, "sorter-source");
							 this.clone.sorterPos = this._defNode.sorterPos;
					}
					else {
						_tb.appendChild( this.clone);
						document.Node.removeClass( this.clone, "sorter-source");
						this.clone.sorterPos = this._defNode.sorterPos;
					}
				}
				else {
					document.Node.removeClass( this._defNode, "sorter-source");
				}
				document.Node.remove(this.node);
				
			
				// Cleanup classes from the table
				$T(this._defNode.nodeName.toLowerCase(), this.cont).forEachBind( function() {	
					document.Node.removeClass(this,  "sorter-prev");
				});	
				
				// Call the save function
				if( isFunction( $object.onSave) )
					$object.onSave();	
					
						
		
			},	
				
			onDrag 	: function() {
				if( this.prevOffset) {
					document.Node.removeClass( this.prevOffset, "sorter-prev" );
				}
			
				//alert( this.prevOffset.previousSibling.nodeName);	
				this.prevOffset = this.curOffset;			
				if( this.node.offsetTop ) {
					var _ret  = this.getB4( this.node.offsetTop);
					if( _ret && _ret != -1)
						this.curOffset = _ret[0];
					else
						this.curOffset = -1;
					}
				if( this.curOffset && this.curOffset != -1) {
					document.Node.addClass( this.curOffset, "sorter-prev");
				}		
			}
		});	
		
		return this;	
	// end init	
	}
}


// Inline code
RowSorter.prototype.onSave = function() {
	var order = this.getOrder();
	var prevOrder = this.drag.orderPrev;
	if( prevOrder ) {
		if( order.join(",") == prevOrder.join(",") ) {
			return false;
		}	
	}
	params = this.gbId +", array("+ order +")";
	args = params.split(",");
	Ajax.rpc ("guestbooks.SetFieldsOrder", args, {
		onSuccess: function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {
				alert( res.faultString );
			}
			else
			{
				//alert('success');
			}
		}
	});

}
/* preview some html */
function previewHtml() {
	var code = $('code').value;
	$('previewIt').innerHTML = code;
	return false;
}

function toggleEntry( i, el, tab)	{
	
	if($('preview-'+tab+'-'+i).style.display == "none")	{
		$('preview-'+tab+'-'+i).style.display = "block";
		$('content-'+tab+'-'+i).style.display = "none";
		$('more-'+tab+'-'+i).style.display = "none";
		el.innerHTML = less;
	}
	else	{ 
		$('preview-'+tab+'-'+i).style.display = "none";
		$('content-'+tab+'-'+i).style.display = "block";
		$('more-'+tab+'-'+i).style.display = "block";
		el.innerHTML = more;
	}
}

function toggle(el)	{
	if(el.style.display == "none")
		el.style.display = "block";
	else
		el.style.display = "none";
}

Event.add( window, "DOMContentLoaded", function() {
	_allMsgs = $CN("msg-container");
	_allMsgs.forEachBind( function() {
		new Fx.Styles( this, { duration: 8000,
			onComplete      : function(){
				new Fx.Slide ( this.element, {duration: 1800 }).hide();
			}
		}).start({'opacity' : [0]});
	});

	var pagesAjax = new Ajax.RPC({
		'onSuccess' : function(q) {
			var res = q.responseJSON;
			if (res && res.faultCode)
				alert(res.faultString);
		}
	});

	var t = new Sorter('#fields tbody', 'tr', 'td,th', {
		'anyKnobElement' : false,
		'onChange' : function (el) {
			var order = [];
			this.getElements().each(function(element) {
				order.push(element.getProperty('id').replace(/_/g, '').toInt());
			});
			pagesAjax.send("guestbooks.SetFieldsOrder", parseInt(gbId), order);
		},
		'getDragger': function() {
			return $C('div').
			setStyles({
				'background': '#ccc',
				'width'	: '600px'
			}).
			setHTML(this.start.element.cells[0].getText());
		}
	});
});

