Event.onDOMReady(function() {
	// handle empty search requests
	if (defined($("search-form")) && defined($("q"))) {
		Event.observe(
			$("search-form"), 
			"submit",  
			function(event) { 
				if (!$F("q").strip()) 
					Event.stop(event);
			},  
			false
		);
	}

	// focus first search field
	if (defined($("q-all")))
		document.getElementById("q-all").focus();

	// contact form
	if (defined($("contact"))) {
		Event.observe(
			$("contact"), 
			"submit",  
			function(event) { 
				if (	!$F("name").strip()  	||
					!($F("phone").strip() 	|| $F("email").strip()) || 
					!$F("subject").strip() 	||
					!$F("comments").strip() ||
					!$F("captcha").strip()){ 
						var path = document.location.toString().split("/");
						var msg = "";
						if (defined(path[3])) {
							if (path[3] == "el" || path[3].indexOf(".html") != -1)
								msg = "Παρακαλώ, συμπληρώστε τα υποχρεωτικά πεδία";
							else
								msg = "Please, fill in the required fields";
						}

						alert(msg);
						Event.stop(event);
				}	
			},  
			false
		);
	}

	// agenda new event form
	if (defined($("agenda-add-event"))) {
		Event.observe(
			$("agenda-add-event"), 
			"submit",  
			function(event) { 
				var allTextareas = $A(document.getElementsByTagName("textarea"));
				var errors 	 = [];
				var isContentEmpty = 1;

				allTextareas.each(function(t) {
					if (t.id.indexOf("content_") != -1) {
						id = t.id.replace(/content_/, '');	
						lang = $("tab_lang_"+id).firstChild.innerHTML;

						if ($F("title_"+id).strip() && $F("content_"+id).strip()) {
							isContentEmpty = 0
						} else if ($F("title_"+id).strip() && !$F("content_"+id).strip()) {
							errors.push("Συμπληρώστε περιεχόμενο για την γλώσσα \'" + lang + "\'");
							isContentEmpty = 0;
						} else if (!$F("title_"+id).strip() && $F("content_"+id).strip()) {
							errors.push("Συμπληρώστε τίτλο για την γλώσσα \'" + lang + "\'");
							isContentEmpty = 0;
						}
					}
				});
				
				if (isContentEmpty)
					errors.push("Συμπληρώστε τίτλο και περιεχόμενο");
				if (!$F("organizer_id").strip())
					errors.push("Συμπληρώστε διοργανωτή");
				if (!$F("contact_phone").strip())
					errors.push("Συμπληρώστε τηλέφωνο επικοινωνίας");
				if (!$F("date_from").strip())
					errors.push("Συμπληρώστε ημερομηνία έναρξης");
				if (!$F("date_to").strip())
					errors.push("Συμπληρώστε ημερομηνία λήξης");

				if (errors.length) {
					alert(errors.join('\n'));
					Event.stop(event);
				}
			},  
			false
		);
	}

	if (defined($("dep_id"))) {
		Event.observe(
			$("dep_id"), 
			"change",  
			loadDepartmentInfo,
			false
		);
	}

	if (defined($("nav"))) {
	       	if ($("nav").offsetHeight < $("content").offsetHeight)
			$("nav").style.height = ($("content").offsetHeight - 2) + "px";
	}

	if (defined($("new-request"))) {
		Event.observe(
			$("new-request"), 
			"submit",  
			function(event) {
				var errors = [];
				$("subject").value = $F("subject").strip();
				$("descr").value = $F("descr").strip();

				if (!$F("reply_type_id"))
					errors.push("Συμπληρώστε τρόπο απάντησης");
				if (!$F("subject"))
					errors.push("Συμπληρώστε θέμα");
				if (!$F("descr"))
					errors.push("Συμπληρώστε περιγραφή");
				
				if (errors.length) {
					alert(errors.join('\n'));
					Event.stop(event);
				}
			},
			false
		);
	}	

	var galleries = $$("table.gallery", "div.gallery");
	if (galleries.length) {
		galleries.each(function(gallery) {
			var images = $A(gallery.getElementsByTagName("img"));
			images.each(function(img) {
				if (!Element.hasClassName($(img), "no-link")) {
					var lightboxLink = document.createElement("a");
					lightboxLink.setAttribute("rel", "lightbox");

					if ($(img).getAttribute("title"))
						lightboxLink.setAttribute("title", $(img).getAttribute("title"));
					else if ($(img).getAttribute("alt"))
						lightboxLink.setAttribute("title", $(img).getAttribute("alt"));
					else 
						lightboxLink.setAttribute("title", " ");

					lightboxLink.href = $(img).src.replace(/(_t|_n)\./, '.');
					$(img).parentNode.insertBefore(lightboxLink, $(img));
					lightboxLink.appendChild($(img));
				}	
			});
		});
	}


	if (defined($("insert-user"))) {
		Event.observe($("lname"),  "keyup", function() { this.value = this.value.toUpperCase(); }, false);
		Event.observe($("fname"),  "keyup", function() { this.value = this.value.toUpperCase(); }, false);
		Event.observe($("id_card_number"), "keyup", function() { this.value = this.value.toUpperCase(); }, false);
		Event.observe($("city"),   "keyup", function() { this.value = this.value.toUpperCase(); }, false);
		Event.observe($("address"),"keyup", function() { this.value = this.value.toUpperCase(); }, false);
		Event.observe($("area"),   "keyup", function() { this.value = this.value.toUpperCase(); }, false);
		Event.observe
		(
			$("username"), 
			"keyup", 
			function() {
				$("username").value = $("username").value.toLowerCase().replace(/[^a-z0-9._\-]+/, '');
								
				if (!$F("username").strip()) {
					$("username_exists").innerHTML = "";	
					return;
				}

				var url = "ajax.php";
				var params = "ajaxAction=usernameExists&username=" + $F("username").strip();
				var req = new Ajax.Request(
					url,
					{
						method: 'post',
						parameters: params,
						onComplete: function(req) {
							if (parseInt(req.responseText)) {
								with ($("username_exists")) {
									className = "check error";
									innerHTML = "Το όνομα χρήστη χρησιμοποιείται.";
								}
								$("submit").disabled = "disabled";
								$("submit").style.backgroundColor = "#ccc";
							} else {
								with ($("username_exists")) {
									className = "check correct";
									innerHTML = "Το όνομα χρήστη δε χρησιμοποιείται.";
								}	
								$("submit").disabled = "";
								$("submit").style.backgroundColor = "#fff";
							}
						},
						onFailure: function() {
							alert("An error occured. Please, try again later.");
						}
					}
				);

			},
			false
		);

		Event.observe
		(
			$("email"), 
			"keyup", 
			function() {
				$("email").value = $("email").value.toLowerCase().replace(/[^a-z0-9@\._\-]+/, '');
								
				if (!$F("email")) {
					$("email_exists").innerHTML = "";	
					return;
				}

				var url = "ajax.php";
				var params = "ajaxAction=emailExists&email=" + $F("email");
				var req = new Ajax.Request(
					url,
					{
						method: 'post',
						parameters: params,
						onComplete: function(req) {
							if (parseInt(req.responseText)) {
								with ($("email_exists")) {
									className = "check error";
									innerHTML = "Το email χρησιμοποιείται.";
								}
								$("submit").disabled = "disabled";
								$("submit").style.backgroundColor = "#ccc";
							} else {
								with ($("email_exists")) {
									className = "check correct";
									innerHTML = "Το email δε χρησιμοποιείται.";
								}	
								$("submit").disabled = "";
								$("submit").style.backgroundColor = "#fff";
							}
						},
						onFailure: function() {
							alert("An error occured. Please, try again later.");
						}
					}
				);

			},
			false
		);


		Event.observe
		(
			$("mobile"), 
			"keyup", 
			function() {
				$("mobile").value = $("mobile").value.toLowerCase().replace(/[^0-9\+]+/, '');
								
				if (!$F("mobile")) {
					$("mobile_exists").innerHTML = "";	
					return;
				}

				var url = "ajax.php";
				var params = "ajaxAction=mobileExists&mobile=" + $F("mobile");
				var req = new Ajax.Request(
					url,
					{
						method: 'post',
						parameters: params,
						onComplete: function(req) {
							if (parseInt(req.responseText)) {
								with ($("mobile_exists")) {
									className = "check error";
									innerHTML = "Το κινητό χρησιμοποιείται.";
								}
								$("submit").disabled = "disabled";
								$("submit").style.backgroundColor = "#ccc";
							} else {
								with ($("mobile_exists")) {
									className = "check correct";
									innerHTML = "Το κινητό δε χρησιμοποιείται.";
								}	
								$("submit").disabled = "";
								$("submit").style.backgroundColor = "#fff";
							}
						},
						onFailure: function() {
							alert("An error occured. Please, try again later.");
						}
					}
				);

			},
			false
		);


	}

});

loadDepartmentInfo = function() {
	var depId = $F("dep_id");
	if (!depId)
		return;
	
	var url = "/ajax.php";
	var params = "ajaxAction=loadDepartmentInfo&depId=" + depId;
	var req = new Ajax.Request(
		url,
		{
			method: 'post',
			parameters: params,
			onComplete: function(req) {
				var r = fromJSON(req.responseText);
				$("_department").innerHTML = r.TITLE || "";
				$("_competence").innerHTML = r.DESCR || "";
				$("_phone").innerHTML 	   = r.PHONE || "";
				$("_fax").innerHTML 	   = r.FAX   || "";
				$("_email").innerHTML 	   = r.EMAIL || "";
			},
			onFailure: function() {
				alert("An error occured. Please, try again later.");
			}
		}
	);
}


fromJSON = function(s) {
	return eval('('+ s +')');
}


popup = function(url, opts) {
	var title 	= opts['title']        || '';
	var width  	= opts['width']        || screen.width;
	var height 	= opts['height']       || screen.height;
	var status 	= opts['status']       || 'no';
	var toolbar 	= opts['toolbar']      || 'no';
	var menubar 	= opts['menubar']      || 'yes';
	var scrollbars 	= opts['scrollbars']   || 'no';
	var centered 	= opts['centered'] ? 1 : 0;
	if (centered) {
		_left = (screen.width  - width)  / 2;
		_top  = (screen.height - height) / 2;
	} else {
		_left = _top = 0;
	}


	window.open(
		url, 
		title,
		'width=' + width + ', height=' + height + ', status=' + status +', toolbar='+toolbar+', menubar='+menubar+', scrollbars='+scrollbars+',left='+_left+',top='+_top
	);
};

defined = function(o) {
	return o != undefined;
}

/**
 * toogle tab
 * required: div.id must have the same id with li.id. eg div_site tab_site
 */
function toggleTab(e) {
	e = e.parentNode; 
	var isMenu = 0;
	var allDivs = getElementsByTagNames("div");
	allDivs.each(function(thisDiv) {
		if (thisDiv.id.indexOf("menu_") != -1)
			isMenu = 1;

		// hide all divs	
		if (	thisDiv.id.indexOf("lang_") != -1 || 
			thisDiv.id.indexOf("menu_") != -1 || 
			thisDiv.id.indexOf("div_") != -1) {
				thisDiv.style.display = "none";
		}
	});

	var activeDiv = "div_" + e.id.replace(/tab_/, "");
	$(activeDiv).style.display = "";

	var allTabs = getElementsByTagNames("li");
	allTabs.each(function(thisTab) {
		if (thisTab.id.indexOf("tab_") != -1)
			thisTab.className = isMenu ? "no_content" : "normal";
	});
	
	e.className = "activ";
}

function getElementsByTagNames(list, obj) {
	if (!obj) 
		var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i = 0;i < tagNames.length; i++)
	{
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j = 0; j < tags.length; j++)
		{
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (testNode.sourceIndex)
	{
		resultArray.sort(function (a,b) {
			return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition)
	{
		resultArray.sort(function (a,b) {
		return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}



function addAgendaDate() {
	var newDate = document.createElement("div");
	var s = '';
	var maxId = 0;
	var adates = $A($("agenda_dates").getElementsByTagName("div"));

	if (adates.length)
		maxId = parseInt(adates[adates.length-1].id.replace(/agenda_date_/, '')) + 1;
	if (!maxId)
		return;
	newDate.id = "agenda_date_" + maxId;

	//s += '<div id="agenda_date_' + maxId + '">\n';
	s += '<table class="insert" summary="agenda dates" style="border: 0;">\n';
	s += '<tr>\n';
	s += '<th><label for=date_from_' + maxId + '>Ημερομηνία Έναρξης:</label></th>\n';
	s += '<td colspan="2">\n';
	s += '<input type="text" name="date_from[]" id="date_from_' + maxId + '" class="text" value="" />\n';
	s += '<a href="javascript:void(0)" onclick="calendar.display(\'calendar-container\', \'date_from_' + maxId + '\', event, $F(\'date_from_' + maxId + '\'));"><img src="img/calendar.gif" alt="calendar" /></a>\n';
	s += '</td>\n';
	s += '<td>\n';
	s += '<a style="text-decoration: none;" href="javascript:void(0)" onclick="removeAgendaDate(' + maxId + ')" title="Προσθήκη"><img src="/img/img_minus.gif" title="" /></a>\n';
	s += '</td>\n';
	s += '</tr>\n';
	
	s += '<tr>\n';	
	s += '<th><label for="tm_' + maxId + '">Ωρα:</label></th>\n';
	s += '<td colspan="2">\n';
	s += '<input type="text" name="tm[]" id="tm_' + maxId + '" value="" class="text" />\n';
	s += '</td>\n';
	s += '<td></td>\n';
	s += '</tr>\n';

	s += '<tr>\n';
	s += '<th><label for=date_to_' + maxId + '>Ημερομηνία Λήξης:</label></th>\n';
	s += '<td colspan="2">\n';
	s += '<input type="text" name="date_to[]" id="date_to_' + maxId + '" class="text" value="" />\n';
	s += '<a href="javascript:void(0)" onclick="calendar.display(\'calendar-container\', \'date_to_' + maxId + '\', event, $F(\'date_to_' + maxId + '\'));"><img src="img/calendar.gif" alt="calendar" /></a>\n';
	s += '</td>\n';
	s += '<td></td>\n';
	s += '</tr>\n';
		s += '</table>\n';
	//s += '</div>\n';

	newDate.innerHTML = s;

	$("agenda_dates").appendChild(newDate);	
}

function removeAgendaDate(id) {
	if (defined($("agenda_date_" + id)))
		Element.remove($("agenda_date_" + id));
}


validateForm = function(form) {
	if (!form)
		form = document.forms[0];
	errors = [];
	var requiredFields = $AT(["input:required", "select:required", "textarea:required", "input:regexp", "select:regexp", "textarea:regexp"], form);
	requiredFields.each(function(e) {
		e = $(e);
		var required = e.getAttribute("required");
		var or = e.getAttribute("or"); // if field is empty, check 'or' elements also
		var re = e.getAttribute("regexp");
		var flags = e.getAttribute("regexpFlags");
		var emptyMessage = e.getAttribute("emptyMessage") || "[ERROR] emptyMessage not found for" + e.id;
		var invalidMessage = e.getAttribute("invalidMessage") || "[ERROR] invalidMessage not found for" + e.id;

		switch (e.type) {
			case "text":
			case "textarea":
			case "password":
				e.value = e.value.strip();
				if (required && !e.value) {
					if (or) {
						_error = 0;
						var orElements = or.split(",");
						for (var i = 0; (_e = $(orElements[i])); i++) {
							_e.value = _e.value.strip();
							if (_e.value) {
								// alternative fields have values. check for invalid values
								var _re = _e.getAttribute("regexp");
								var _flags = _e.getAttribute("regexpFlags");
								var _emptyMessage = _e.getAttribute("emptyMessage") || "[ERROR] emptyMessage not found for" + _e.id;
								var _invalidMessage = _e.getAttribute("invalidMessage") || "[ERROR] invalidMessage not found for" + _e.id;
								if (_re && !pregMatch.g(_re, _flags, _e.value)) {
									_error = 1;
									errors.push(_invalidMessage);
									break;
								} else if (_re && pregMatch.g(_re, _flags, _e.value)) {
									_error = 0;
									break;
								}
							} else {
								_error = 1;
							}
						}
						if (_error)
							errors.push(emptyMessage);
					} else {
						errors.push(emptyMessage);
					}	
				}

				if (e.value && re && !pregMatch.g(re, flags, e.value)) 
					errors.push(invalidMessage);
				break;
			case "checkbox":
			case "radio":
				if (required && !e.checked) {
					var _or = e.getAttribute("or");
					if (_or) {
						var orElements = _or.split(",");
						_error = 1;
						for (var i = 0; (_e = $(orElements[i])); i++) {
							if (_e.checked) {
								_error = 0;
								break;
							}	
						}
						if (_error)
							errors.push(emptyMessage);
					} else {
						errors.push(emptyMessage);
					}
				}	
				break;	
		}
	});

	if (errors.length) {
		alert(errors.join('\n'));
		return false;
	}
	return true;
}


// todo implement non array call
function $AT(el, cont) {
	cont = cont ? $(cont) : document;
	res = [];
	if (isArray(el)) {
		el.each(function(e) {
			var _attr;
			if (e.indexOf(":") != -1) {
				var ar  = e.split(":");
				e       = ar[0];
				_attr   = ar[1];
			}

			if (!_attr) {
				alert("Not fount required : in caller");
				return;
			}

			var _ = $A(cont.getElementsByTagName(e));
			for (var j = 0; j < _.length; ++j) {
				if (_[j].getAttribute(_attr) && !inArray(_[j], res)) 
					res.push(_[j]);
			}
		});
	}
	return res;
}




function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}	
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
} 


function inArray(e, arr) {
	if (!isArray(arr) || arr.length == 0)
		return 0;
	var opt = arr.find( function(a){
		return (a.id == e.id);
	});
	return opt;
}

pregMatch = function(re, flags, str, matches) {
	if (flags)
		var myre = new RegExp(re, flags)
	else
		var myre = new RegExp(re);

	var ret;
	if (defined(matches)) {
		var _m  = myre.exec(str);
		ret     = _m.length || 0;
		for (var i = 0; match = _m[i]; i++)
			matches.push(match);
	} else {
		ret     = myre.test(str);
	}
	return ret;

};


function isArray(arg)  { return (arg instanceof Array || typeof arg == "array"); }
function isObject(arg) { return(typeof arg == "object" || isArray(arg) || isFunction(arg)); }
function isFunction(arg) { return (arg instanceof Function || typeof arg == "function"); }
function isString(arg) { return typeof arg == "string"; }
function isNumber(arg) { return arg instanceof Number || typeof arg == "number"; }
function isBoolean(arg){ return arg instanceof Boolean|| typeof arg == "boolean"; }
function fromJSON(arg) { return eval("(" + arg + ")"); }



