<?php
//define this module's name and path
$mn = basename(__FILE__ , ".php");
include("modules/modules.php");

/*
Available variables:
All system classes
All request variables
$p (the template path)
$mp (the module path)
$sufixID (id sufix for this module's divs)
*/

$marginTop = ($moduleParameters['marginTop'] == "__EMPTY__" || empty($moduleParameters['marginTop'])) ? 0 : $moduleParameters['marginTop'];
$marginRight = ($moduleParameters['marginRight'] == "__EMPTY__" || empty($moduleParameters['marginRight'])) ? 0 : $moduleParameters['marginRight'];
$marginBottom = ($moduleParameters['marginBottom'] == "__EMPTY__" || empty($moduleParameters['marginBottom'])) ? 0 : $moduleParameters['marginBottom'];
$marginLeft = ($moduleParameters['marginLeft'] == "__EMPTY__" || empty($moduleParameters['marginLeft'])) ? 0 : $moduleParameters['marginLeft'];
$paddingTop = ($moduleParameters['paddingTop'] == "__EMPTY__" || empty($moduleParameters['paddingTop'])) ? 0 : $moduleParameters['paddingTop'];
$paddingRight = ($moduleParameters['paddingRight'] == "__EMPTY__" || empty($moduleParameters['paddingRight'])) ? 0 : $moduleParameters['paddingRight'];
$paddingBottom = ($moduleParameters['paddingBottom'] == "__EMPTY__" || empty($moduleParameters['paddingBottom'])) ? 0 : $moduleParameters['paddingBottom'];
$paddingLeft = ($moduleParameters['paddingLeft'] == "__EMPTY__" || empty($moduleParameters['paddingLeft'])) ? 0 : $moduleParameters['paddingLeft'];
$useModuleContainer = ($moduleParameters['useModuleContainer'] == "__EMPTY__" || empty($moduleParameters['useModuleContainer'])) ? 0 : (int)$moduleParameters['useModuleContainer'];
$widthInPixels = ($moduleParameters['widthInPixels'] == "__EMPTY__" || empty($moduleParameters['widthInPixels'])) ? null : (int)$moduleParameters['widthInPixels'];

if(empty($marginTop) && empty($marginRight) && empty($marginBottom) && empty($marginLeft)){
	$Mmargin = "0";
}else{
	$Mmargin = $marginTop." ".$marginRight." ".$marginBottom." ".$marginLeft." ";
}
if(empty($paddingTop) && empty($paddingRight) && empty($paddingBottom) && empty($paddingLeft)){
	$Mpadding = "0";
}else{
	$Mpadding = $paddingTop." ".$paddingRight." ".$paddingBottom." ".$paddingLeft." ";
}

// access from displayField function **********************
global $radioButtonsAlign;
global $form_catID;
global $protocol;
global $email_address;
global $domain_name;
//*************************************************

$formID = $moduleParameters['formID'];
$formMethod = $moduleParameters['formMethod'];
$radioButtonsAlign = $moduleParameters['radioButtonsAlign'];
$displayLabels = $moduleParameters['displayLabels'];
$useSystemStyling = $moduleParameters['useSystemStyling'];
$textOnly = $moduleParameters['textOnly'];
$uiTheme = $moduleParameters['uiTheme'];
$cssContent = $moduleParameters['cssContent'];
$contentBeforeSubmit = $moduleParameters['contentBeforeSubmit'];
$contentAfterSubmit = $moduleParameters['contentAfterSubmit'];
$contentOfEmail = $moduleParameters['contentOfEmail'];
$notifyEmail = (!empty($moduleParameters['notifyEmail'])) ? $moduleParameters['notifyEmail'] : $email_address;
$emailFrom = (!empty($moduleParameters['emailFrom'])) ? $moduleParameters['emailFrom'] : $email_address;
$emailSubject = (!empty($moduleParameters['emailSubject'])) ? $moduleParameters['emailSubject'] : "From ".$domain_name;

if($useModuleContainer ){
	?>

	<div id="<?php echo $mn.$sufixID;?>" data-editable="editable" class="responsive_float">
	<?php
}

if((int)$formID){
	 // only if a form is defined
	 
	 
		global $langID;
		$q="select forms.*, content_forms.title from forms, content_forms 
		where content_forms.mainID=forms.id and forms.base_form='$formID' and content_forms.langID='$langID'";
		$form = $db->getRecord($q);
		$form_id = $form->id;
		$form_title = ($form->title) ? $form->title : $form_title;
		$base_form = $form->base_form;
		$form_htmlID = ($form->htmlID) ? $form->htmlID : $form_htmlID;
		$form_catID = ($form->catID) ? $form->catID : $form_catID;
		$form_captcha = ($form->captcha || isset($form->captcha)) ? $form->captcha : $form_captcha;
		$form_section = ($form->sectionID) ? $form->sectionID : $form_section;
		$form_protected = ($form->protected) ? $form->protected : $form_protected;
		$form_account_type = ($form->account_type) ? $form->account_type : $form_account_type;
		$form_use_email_field = ($form->use_email_field) ? $form->use_email_field : $form_use_email_field;
		
		$formID = $form_id;  // the formID of the current language form
		
		$criteria =  " ff.formID='".$formID."' ";
		$fields = $content->getContent("ff", $criteria, "*", "*", $form->lang, 'ff.sort');
		$idx = count($fields);
		$token = $formID;
		$keywordFound = false;
		$counter=1;
		foreach($fields as $f){
			if($f->name == "keyword") $keywordFound = true;
			global ${"field".$counter."_id"};
			global ${"field".$counter."_name"};
			global ${"field".$counter."_label"};
			global ${"field".$counter."_default"};
			global ${"field".$counter."_selectSource"};
			global ${"field".$counter."_class"};
			global ${"field".$counter."_required"};
			global ${"field".$counter."_currency"};
			global ${"field".$counter."_checked"};
			global ${"field".$counter."_fieldset"};
			global ${"field".$counter."_type"};
			global ${"field".$counter."_sort"};
			global ${"field".$counter."_interactive"};
			global ${"field".$counter."_condition_operator"};
			global ${"field".$counter."_condition_value"};
			global ${"field".$counter."_required"};
			global ${"field".$counter."_isemail"};
			global ${"field".$counter."_limit"};
			global ${"field".$counter."_rangeFrom"};
			global ${"field".$counter."_rangeTo"};
			global ${"field".$counter."_rules"};
			global ${"field".$counter."_actions"};
			${"field".$counter."_id"} = $f->id;
			${"field".$counter."_name"} = $f->name;
			${"field".$counter."_label"} = $f->title;
			${"field".$counter."_default"} = $f->defaultvalue;
			${"field".$counter."_selectSource"} = $f->selectSource;			
			${"field".$counter."_class"} = $f->class;
			${"field".$counter."_required"} = $f->required;
			${"field".$counter."_currency"} = $f->currency;
			${"field".$counter."_checked"} = $f->checked;
			${"field".$counter."_fieldset"} = $f->fieldset;
			${"field".$counter."_type"} = $content->getValue("fftypes", $f->fftype, "fftype", $langID);
			${"field".$counter."_sort"} = $f->sort;
			${"field".$counter."_interactive"} = $f->interactive;
			${"field".$counter."_condition_operator"} = $f->condition_operator;
			${"field".$counter."_condition_value"} = $f->condition_value;
			if(${"field".$counter."_required"}){
				if(${"field".$counter."_type"} == "textfield") ${"field".$counter."_isemail"} = $f->rules;
				if(${"field".$counter."_type"} == "textarea") ${"field".$counter."_limit"} = str_replace("limit ", "", $f->rules);
				if(${"field".$counter."_type"} == "int" || ${"field".$counter."_type"} == "decimal" || ${"field".$counter."_type"} == "date"){
					$r = $f->rules;
					$r = str_replace("range ", "", $r);
					list($rangeFrom, $rangeTo) = explode("~|~", $r);
					${"field".$counter."_rangeFrom"} =$rangeFrom;
					${"field".$counter."_rangeTo"} =$rangeTo;
				}								
			}
			${"field".$counter."_rules"} = $f->rules;
			${"field".$counter."_actions"} = $f->actions;
			$counter++;
		}
		
		
			 
	if($_POST['moduleFormSubmited']){
		// process the submited data
		if(!empty($_REQUEST['oForm_info'])){ // check for spam
			echo("Thank you!");
			exit;
		}
		if($form_captcha == "1"){ // Old Odyssey Captcha
			$_REQUEST['oForm_security_code'] = strtoupper( $_REQUEST['oForm_security_code']); // μονο κεφαλαια στο capcha
			if($_SESSION['security_code'] == $_REQUEST['oForm_security_code'] && !empty($_SESSION['security_code'] ) ) {
				unset($_SESSION['security_code']); // ολα ok με το captcha image
			}else{
				$messages->addError(t("Ο κωδικός ταυτοποίησης που πληκτρολογήσατε δεν είναι σωστός"));
			}
		}
		if($form_captcha == "2"){ // Google reCaptcha
			if(isset($_POST['g-recaptcha-response'])) $captcha = $_POST['g-recaptcha-response'];
			if(!$captcha){
				$messages->addError(t("Πρέπει να αποδείξετε πως δεν είστε ρομπότ"));
			}else{
				$secretKey = "6LesLCATAAAAADWqbi8Uro_z_OLzekDuxdAkdzX4";
				$ip = $_SERVER['REMOTE_ADDR'];
				$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
				$responseKeys = json_decode($response,true);
				$hostname = str_replace("www.", NULL, $responseKeys["hostname"]);
				$domainValidated = (strpos($domain_name, $hostname) !== false);
				if(!$domainValidated || intval($responseKeys["success"]) !== 1){
					$messages->addError(t("Πρέπει να αποδείξετε πως δεν είστε ρομπότ"));
				}
			}
		}		
		
		function makeTimestamp($givenDate){
			global $langExtension;
			$theDate = explode("/", $givenDate);
			$day = ($langExtension == "_gr") ? $theDate[0] : $theDate[1];
			$month = ($langExtension == "_gr") ? $theDate[1] : $theDate[0];
			$year = $theDate[2];
			$timestamp = gmmktime(date("H"),date("i"),date("s"),$month,$day,$year);	
			return $timestamp	;	
		}	
		?>
		<style>
		.error{
      display:block !important;
		}
		</style>
		<?php	
		$q = "select ff.name, content_ff.title from ff, content_ff where ff.formID='$formID' and ff.id=content_ff.mainID";
		$result = $db->getRecords($q);
		$fieldDescriptions = array();
		foreach($result as $row) $fieldDescriptions[$row->name] = $row->title;
		foreach($_POST as $key=>$value){
			if(preg_match('/_validation$/', $key)){
				list($var, $validation) = explode("_", $key);
				list($fid, $rule) = explode("*|*", $value);
				if($rule == "email"){ // required as email
					if(!validEmail(${$var}) && !empty(${$var})) $messages->addError("<div class='messageList'>".t("Το πεδίο")." [".$fieldDescriptions[$var]."] ".t("πρέπει να περιέχει e-mail διεύθυνση")."</div>");
				}
				if(preg_match('/^limit/', $rule)){ // required with limited characters
					$parts = explode(" ", $rule);
					$validationLimit = $parts[1];
					if(mb_strlen(${$var}) > $validationLimit) $messages->addError("<div class='messageList'>".t("Το πεδίο")."[ ".$fieldDescriptions[$var]."] ".t("πρέπει να περιέχει το ανώτερο")." ".$validationLimit." ".t("χαρακτήρες")."</div>");
				}
				if(preg_match('/^range/', $rule)){ // required with value in specific range
					$parts = explode(" ", $rule);
					$range = explode("~|~", $parts[1]);
					$rangeFrom = $range[0];
					$rangeTo = $range[1];	
					if($dates->isDate(${$var})){ // we have a date
						if($dates->isDate($rangeFrom)) $rangeFrom = makeTimestamp($rangeFrom);
						if($dates->isDate($rangeTo)) $rangeTo = makeTimestamp($rangeTo);
						$theDate = makeTimestamp(${$var});
						if(($theDate < $rangeFrom) && $rangeFrom){
							$rangeFrom = $dates->makeDateFromTimestamp($rangeFrom);
							$messages->addError("<div class='messageList'>".t("Το πεδίο")." [".$fieldDescriptions[$var]."] ".t("πρέπει να περιέχει ημερομηνία μεταγενέστερη της")." ".$rangeFrom."</div>");
						}
						if(($theDate > $rangeTo) && $rangeTo){
							$rangeTo = $dates->makeDateFromTimestamp($rangeTo);
							$messages->addError("<div class='messageList'>".t("Το πεδίο")."[ ".$fieldDescriptions[$var]."] ".t("πρέπει να περιέχει ημερομηνία προγενέστερη της")." ".$rangeTo."</div>");
						}						
					}else{ // compare floats
						if((float)${$var} < $rangeFrom && $rangeFrom){
							$messages->addError("<div class='messageList'>".t("Το πεδίο")." [".$fieldDescriptions[$var]."] ".t("πρέπει να έχει τιμή μεγαλύτερη από")." ".$rangeFrom."</div>");
						}
						if((float)${$var} > $rangeTo && $rangeTo){
							$messages->addError("<div class='messageList'>".t("Το πεδίο")." [".$fieldDescriptions[$var]."] ".t("πρέπει να έχει τιμή μικρότερη από")." ".$rangeTo."</div>");
						}						
					}
				}				 
				 if(empty($rule)){ // just a required value
					 if(empty(${$var})) $messages->addError("<div class='messageList'>".t("Το πεδίο")." ".$fieldDescriptions[$var]." ".t("πρέπει να συμπληρωθεί")."</div>");
				 }
        $messages->printErrorMessages();
			}
		}
		if(!$messages->hasErrors){

		// proceed to form action
		if($form_catID == 1){ // send form data via email
			if(count($fields)){
				$lines = array();
				$attachments = array();
				$files = array();
				$content_type = "text";
				for($n=1; $n < $counter; $n++){
					$type = ${"field".$n."_type"};
					$selectSource = ${"field".$n."_selectSource"};
					$varName = ${"field".$n."_name"};	
					$fid = ${"field".$n."_id"};	
					$currency = ${"field".$n."_currency"};		
					if($type == "fieldset" || $type == "submit" || $type == "reset") continue;
					if($type == "selectMenu"){
						if($selectSource != "custom_data"){
							if(preg_match('/^c/', $selectSource)){ // menu
								$thisSectionID = str_replace("c", "", $selectSource);
								$thisSectionName = $system->getTableSectionName($thisSectionID)."_categories";
								$thisCatID = ${$varName};
								$catName = $categories->getCategoryName($thisCatID, $thisSectionName, $langID);
								$lines[] = ${"field".$n."_label"}." : ".$catName." (".${$varName}.")";
								continue;
							}else{ // section
								$thisSectionName = $system->getTableSectionName($selectSource);
								$recordTitle = $content->getValue($thisSectionName, ${$varName}, "title", $langID);
								$lines[] = ${"field".$n."_label"}." : ".$recordTitle." (".${$varName}.")";
								continue;								
							}
						}else{ // selectMenu with custom data
							$value = ${$varName};
							$q = "select content_forms_selects.title from forms_selects, content_forms_selects where 
										forms_selects.id=content_forms_selects.mainID 
										and forms_selects.value='$value' 
										and forms_selects.fieldID='$fid' 
										and content_forms_selects.langID='$langID'";
							$optionTitle = $db->getRecord($q)->title;
							$lines[] = ${"field".$n."_label"}." : ".$optionTitle." (".$value.")";
							continue;							
						}
					}
					if($type == "radio"){
						$value = ${$varName};
						$q = "select content_forms_selects.title from forms_selects, content_forms_selects where 
									forms_selects.id=content_forms_selects.mainID 
									and forms_selects.value='$value' 
									and forms_selects.fieldID='$fid' 
									and content_forms_selects.langID='$langID'";
						$optionTitle = $db->getRecord($q)->title;
						$lines[] = ${"field".$n."_label"}." : ".$optionTitle." (".$value.")";
						continue;							
					}
					if($type == "textarea" || $type == "richTextarea"){
						if($type == "richTextarea") $content_type = "html";
						$lines[] = ${"field".$n."_label"}." : ".PHP_EOL.${$varName};
						continue;
					}
					if($type == "selectList"){
						$data = $_REQUEST[$varName];
						if($selectSource != "custom_data"){
							if(preg_match('/^c/', $selectSource)){ // menu
								$thisSectionID = str_replace("c", "", $selectSource);
								$thisSectionName = $system->getTableSectionName($thisSectionID)."_categories";
								$tempLine = ${"field".$n."_label"}." : ";
								$recordTitles = array();
								foreach($data as $record) $recordTitles[] = $categories->getCategoryName($record, $thisSectionName, $langID);
								$lines[] = $tempLine.implode(", ", $recordTitles)." (".implode(", ", ${$varName}).")";
								continue;
							}else{ // section
								$thisSectionName = $system->getTableSectionName($selectSource);
								$tempLine = ${"field".$n."_label"}." : ";
								$recordTitles = array();
								foreach($data as $record) $recordTitles[] = $content->getValue($thisSectionName, $record, "title", $langID);
								$lines[] = $tempLine.implode(", ", $recordTitles)." (".implode(", ", ${$varName}).")";
								continue;								
							}
						}else{ // selectMenu with custom data
							$tempLine = ${"field".$n."_label"}." : ";
							$recordTitles = array();
							foreach($data as $record){
								$q = "select content_forms_selects.title from forms_selects, content_forms_selects where 
											forms_selects.id=content_forms_selects.mainID 
											and forms_selects.value='$record' 
											and forms_selects.fieldID='$fid' 
											and content_forms_selects.langID='$langID'";
								$optionTitle = $db->getRecord($q)->title;
								$recordTitles[] = $optionTitle;
							}
							$lines[] = $tempLine.implode(", ", $recordTitles)." (".implode(", ", ${$varName}).")";
							continue;							
						}
					}
					if($type == "colorpicker"){
						$lines[] = ${"field".$n."_label"}." : #".${$varName};
						continue;
					}	
					if($type == "checkbox"){
						$checkboxValue = (!empty(${$varName})) ? t("ΝΑΙ") : t("ΟΧΙ");
						$lines[] = ${"field".$n."_label"}." : ".$checkboxValue;
						continue;
					}
					if($type == "file" && $form_catID ==1){ // upload image only for email sending
						$filename=$_FILES[$varName]['name'];
						$filename=($filename=="none")? "" : $filename;
						$attachments[] = $varName."~|~".$filename;
						continue;
					}
					if($form_use_email_field && $varName == "email") $notifyEmail2 = 	${$varName};				
					if($currency) $currency = "(".t("σε")." ".$currency.")";								
					$lines[] = ${"field".$n."_label"}." : ".${$varName}.$currency;
				}

				$email_body = htmlspecialchars_decode($variables->restoreModuleValue($contentOfEmail)).PHP_EOL;
				foreach($lines as $line){
					$line = nl2br($line)."<br>"; // prepare for html content
					$email_body.=htmlspecialchars_decode($line.PHP_EOL);
				}
				if(!validEmail($notifyEmail) && !validEmail($notifyEmail2) && $formCatID == 1){
					$messages->addError(t("Δεν ορίστηκε κάποιο e-mail παράδοσης των δεδομένων της φόρμας"));
				}else{
					set_time_limit(3000);
					foreach($attachments as $attachment){
						list($v, $filename) = explode("~|~", $attachment);	
						if(move_uploaded_file ($_FILES[$v]['tmp_name'], "uploads/".$filename)) $files[] = "uploads/".$filename;
					}
					
					$html1 = '<html>'.PHP_EOL.'<head>'.PHP_EOL.'<meta http-equiv="content-type" content="text/html; charset=UTF-8">'.PHP_EOL.'</head>'.PHP_EOL.'<body bgcolor="#FFFFFF" text="#000000">';
					$html2 = '</body>'.PHP_EOL.'</html>'.PHP_EOL;
					$email_body = $html1.$email_body.$html2;
					$boundary = md5(uniqid(time()));
					//headers
					$headers  = "From: $emailFrom\r\n";
					$headers .= "MIME-Version: 1.0\r\n";
					$headers .= "Content-Type: multipart/mixed; boundary=\"".$boundary."\"\r\n\r\n";
					//content
					$message = "This is a multi-part message in MIME format.\r\n";
					$message .= "--".$boundary."\r\n";
					$message .= "Content-type:text/html; charset=UTF-8\r\n";
					$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
					$message .= $email_body."\r\n\r\n";
					for($x=0;$x<count($files);$x++)	{
						$file = fopen($files[$x],"rb");
						$data = fread($file,filesize($files[$x]));
						fclose($file);
						$data = chunk_split(base64_encode($data));
						$message .= "--".$boundary."\r\n";
						$message .= "Content-Type: octet-stream; name=\"" . str_replace("uploads/", "", $files[$x]) . "\"\r\n";
						$message .= "Content-Transfer-Encoding: base64\r\n";
						$message .= "Content-Disposition: attachment; filename=\"" . str_replace("uploads/", "", $files[$x])  . "\"\r\n\r\n";
						$message .= $data; //The base64 encoded message
						$message .= "\r\n\r\n";
					}
					$message .= "--".$boundary."--";
					// send
					if(empty($textOnly)){
						if(validEmail($notifyEmail)){
							$ok = @mail($notifyEmail, $emailSubject, $message, $headers);
							if(!$ok) $messages->addError("Problem sending mail to ".$notifyEmail);
						}
						if(validEmail($notifyEmail2)){
							$ok = @mail($notifyEmail2, $emailSubject, $message, $headers);
							if(!$ok) $messages->addError("Problem sending mail to ".$notifyEmail2);
						}
					}else{
						$headers = "From: ".$emailFrom."\nContent-Type: text; charset=utf-8\n";
						$msg = strip_tags($email_body);
						if(validEmail($notifyEmail)){
							$ok = @mail($notifyEmail, $emailSubject, $msg, $headers);
							if(!$ok) $messages->addError("Problem sending mail to ".$notifyEmail);
						}
						if(validEmail($notifyEmail2)){
							$ok = @mail($notifyEmail2, $emailSubject, $msg, $headers);
							if(!$ok) $messages->addError("Problem sending mail to ".$notifyEmail2);
						}						
					}
					$messages->printSystemMessages();
					foreach($files as $file){ // clear uploads
						if(is_file($file)) unlink($file);
					}					
				}
			}
		}
		if($form_catID == 2){ // save form data to Odyssey section
			$pro_file = $mp."pro.php";
			if(is_file($pro_file)){
				include($pro_file);
			}else{
				$messages->addError(t("Η δυνατότητα αποθήκευσης των δεδομένων της φόρμας, παρέχεται μόνο στην έκδοση PRO του Odyssey Forms Module. Για τους τρόπους απόκτησής του παρακαλούμε επικοινωνήστε στο korinthorama@gmail.com"));
				$messages->printSystemMessages();
			}
		}	
					
		if(!$messages->hasErrors){
		?>
		<div class="contentAfterSubmit">
		<?php echo htmlspecialchars_decode($variables->restoreModuleValue($contentAfterSubmit)); ?>
		</div>		
		<?php
		}
		$messages->hasErrors = false; // make sure that the form will not be displayed
		}
	}
	$messages->printSystemMessages();
	if(empty($_POST['moduleFormSubmited']) || $messages->hasErrors){
		// render form
		if($useSystemStyling){
		?>
		<link rel="stylesheet" type="text/css" href="css/buttons.css">
		<link rel="stylesheet" type="text/css" href="css/forms.css">
		<?php
		}
		?>
		<style type="text/css">
		<?php if(!$displayLabels){ ?>.odyssey_form label{ display:none;}<?php }?>
		#<?php echo $mn.$sufixID;?>{
			text-align: <?php echo $moduleParameters['moduleAlign'];?>;
			margin : <?php echo $Mmargin;?>;
			padding : <?php echo $Mpadding;?>;
		<?php
		if(!empty($widthInPixels)){
			?>
			width: <?php echo $widthInPixels;?>px;
			<?php 
		}	
		if($moduleParameters['moduleHR'] == "top" || $moduleParameters['moduleHR'] == "bottom"){
		?>
			border-<?php echo $moduleParameters['moduleHR'];?> : 1px solid black;
		<?php 
		}
		?>
		}
		<?php
		if(!empty($cssContent)){ // load custom css 
			echo $variables->restoreModuleValue($cssContent).PHP_EOL;
		}
		?>
		</style>
		<?php

		if(count($fields)){ // make sure there are fields...
			$fieldsetFields = array();
			$freeFields = array();
			$registeredIDs = array();
			$fieldTypes = array();
			$iActions = array();

			for($n=1; $n < $counter; $n++){
				$fieldTypes[$n] = ${"field".$n."_type"};
				$fieldsetFields[$n] = ${"field".$n."_fieldset"};
				$iActions[$n] = ${"field".$n."_actions"};
			}
			array_unique($fieldTypes);
			?>
			<div class="contentBeforeSubmit">
			<?php echo htmlspecialchars_decode($variables->restoreModuleValue($contentBeforeSubmit)); ?>
			</div>			
			<?php
			if(in_array("colorpicker", $fieldTypes)){
			?>
			<link rel="stylesheet" type="text/css" href="css/jPicker-1.1.2.min.css">
		<script type="text/javascript" src="js/jpicker-1.1.2.min.js"></script>
			<?php
			$ready.="$('.colorpicker').jPicker().hide();".PHP_EOL;
			}
			if(in_array("date", $fieldTypes)){
				if($uiTheme != "default"){
				?>
		<link href="<?php echo $protocol;?>://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.6/themes/<?php echo $uiTheme;?>/jquery-ui.css" rel="stylesheet" type="text/css">
				<?php
				}
			}	
			?>
			<script  type="text/javascript" src="admin/editor/tiny_mce/tiny_mce.js"></script>
			<?php
			$editorLanguage = ($langID == 1) ? "el" : "en";				
			$ready.='tinyMCE.init({
						apply_source_formatting : true,
						mode : "specific_textareas",
						editor_selector : "mceEditor",
						theme : "advanced",
						entity_encoding : "raw",
						convert_urls: false,
						language : "'.$editorLanguage.'",
						plugins : "safari,style,table,inlinepopups,preview,paste,advlink,fullscreen,media,advimage",
						theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,|,bullist,numlist",
						theme_advanced_buttons2 : "fullscreen,charmap,|,sub,sup,|,hr,|,link,unlink,code",
						theme_advanced_buttons3 : "",
						theme_advanced_buttons4 : "",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : true
						});
						window.t = setInterval(function(){timer()}, 100);
						function timer(){
								if($(".mceLayout").length == 0){
									return;
								}									
								$(".mceLayout").css({"width": "95%", "max-width": "400px"});
								clearInterval(window.t);

						}'.PHP_EOL;
			if(in_array("selectList", $fieldTypes)){				
				$ready.='$("select[data-type=\"selectList\"]").each(function(){
					var numOfOptions = $(this).find("option").length;
					if(numOfOptions > 15) $(this).css("height", "150px");
				});'.PHP_EOL;
			}			
			?>
		<script type="text/javascript">

			<?php
			if($ready || count($iActions)){
			?>
			jQuery(function($){
			<?php
			echo $ready;
			?>
			window.IDs = new Array();
			window.initialValues = new Array();
			$('.formElement').each(function(){
				if($(this).attr('id')){
					window.IDs.push($(this).attr('id'));
					window.initialValues[$(this).attr('id')] = ($(this).attr('data-type') == "checkbox") ? $(this).attr('checked') : $(this).val();
					if($(this).attr('type') == "radio"){
						var fid = $(this).attr('data-fid');
						window.initialValues[$(this).attr('id')] = $('div .ff_elem'+fid+' :checked').attr('id');
					}
				}
			});
			$('[data-interactive]').each(function(){
				var elm = $(this);
				elm.bind('change start', function(e){
					if($(this).attr('data-type') == "radio" && e.type == "start") return;
					var actions = $(this).attr('data-interactive');
					actions = actions.split("*|*");
					var condition_data = actions[0].split("|");
					var condition_operator = condition_data[1];
					var condition_value = condition_data[2];
					actions = actions[1].replace('[', '');
					actions = actions.replace(']', '');				
					actions = actions.split("~~~|||~~~");									
					for( i in actions){
						thisActions = actions[i].split("~|~");
						var action = thisActions[0];
						var field = thisActions[1];
						var value = thisActions[2];
						var parts = value.split("~***~");
						if(parts[1]){
							var sectionID = parts[0];
							var itemID = parts[1];
						}else{
							var sectionID = "";
							var itemID = "";
						}
							
							if(action == "show"){						
								if(condition_operator == "equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() == condition_value){
											$('#ofElemWrap'+field).show().change();
										}else{
											$('#ofElemWrap'+field).hide().change();
										}
									}else{
										if($(this).attr('checked')){
											$('#ofElemWrap'+field).show().change();
										}else{
											$('#ofElemWrap'+field).hide().change();
										}										
									}
								}
								if(condition_operator == "not_equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() != condition_value){
											$('#ofElemWrap'+field).show().change();
										}else{
											$('#ofElemWrap'+field).hide().change();
										}
									}else{
										if(!$(this).attr('checked')){
											$('#ofElemWrap'+field).show().change();
										}else{
											$('#ofElemWrap'+field).hide().change();
										}										
									}
								}	
								if(condition_operator == "less"){
									if($(this).val() < condition_value){
										$('#ofElemWrap'+field).show().change();
									}else{
										$('#ofElemWrap'+field).hide().change();
									}
								}	
								if(condition_operator == "greater"){
									if($(this).val() > condition_value){
										$('#ofElemWrap'+field).show().change();
									}else{
										$('#ofElemWrap'+field).hide().change();
									}
								}	
							}
							
							
							if(action == "hide"){						
								if(condition_operator == "equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() == condition_value){
											$('#ofElemWrap'+field).hide().change();
										}else{
											$('#ofElemWrap'+field).show().change();
										}
									}else{
										if($(this).attr('checked')){
											$('#ofElemWrap'+field).hide().change();
										}else{
											$('#ofElemWrap'+field).show().change();
										}										
									}
								}
								if(condition_operator == "not_equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() != condition_value){
											$('#ofElemWrap'+field).hide().change();
										}else{
											$('#ofElemWrap'+field).show().change();
										}
									}else{
										if(!$(this).attr('checked')){
											$('#ofElemWrap'+field).hide().change();
										}else{
											$('#ofElemWrap'+field).show().change();
										}										
									}
								}	
								if(condition_operator == "less"){
									if($(this).val() < condition_value){
										$('#ofElemWrap'+field).hide().change();
									}else{
										$('#ofElemWrap'+field).show().change();
									}
								}	
								if(condition_operator == "greater"){
									if($(this).val() > condition_value){
										$('#ofElemWrap'+field).hide().change();
									}else{
										$('#ofElemWrap'+field).show().change();
									}
								}	
							}
							
							
							if(action == "value"){	
								if(sectionID) value = itemID;
								var richTextarea = tinyMCE.get('ff_elem'+field);					
								if(condition_operator == "equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() == condition_value){
											if(richTextarea != undefined) richTextarea.setContent(value);
											if($('#ff_elem'+field).length) $('#ff_elem'+field).val(value).change();
											if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', true).change();
											if($('#rb-'+value).attr('type') == "radio") $('#rb-'+value).attr('checked', true).change();
										}else{
											if(richTextarea != undefined) richTextarea.setContent(window.initialValues['ff_elem'+field]);											
											if($('#ff_elem'+field).length) $('#ff_elem'+field).val(window.initialValues['ff_elem'+field]).change();
											//if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', window.initialValues['ff_elem'+field]).change();
											//if($('#rb-'+value).attr('type') == "radio") $('#'+window.initialValues[$('#rb-'+value).attr('id')]).attr('checked', true).change();									
										}
									}else{ // its a checkbox
										if($(this).attr('checked')){
											if($('#ff_elem'+field).length) $('#ff_elem'+field).val(value).change();
											if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', true).change();
											if($('#rb-'+value).length) $('#rb-'+value).attr('checked', true).change();											
										}									
									}
								}
								if(condition_operator == "not_equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() != condition_value){
											if(richTextarea != undefined) richTextarea.setContent(value);
											if($('#ff_elem'+field).length) $('#ff_elem'+field).val(value).change();
											if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', true).change();	
											if($('#rb-'+value).attr('type') == "radio") $('#rb-'+value).attr('checked', true).change();										
										}else{
											if(richTextarea != undefined) richTextarea.setContent(window.initialValues['ff_elem'+field]);
											if($('#ff_elem'+field).length) $('#ff_elem'+field).val(window.initialValues['ff_elem'+field]).change();
											if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', window.initialValues['ff_elem'+field]).change();
											if($('#rb-'+value).attr('type') == "radio") $('#'+window.initialValues[$('#rb-'+value).attr('id')]).attr('checked', true).change();									
										}
									}else{ // its a checkbox
										if(!$(this).attr('checked')){
											if($('#ff_elem'+field).length) $('#ff_elem'+field).val(value).change();
											if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', true).change();
											if($('#rb-'+value).length) $('#rb-'+value).attr('checked', true).change();											
										}									
									}
								}	
								if(condition_operator == "less"){
									if($(this).val() < condition_value){
										if(richTextarea != undefined) richTextarea.setContent(value);
										if($('#ff_elem'+field).length) $('#ff_elem'+field).val(value).change();
										if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', true).change();
										if($('#rb-'+value).attr('type') == "radio") $('#rb-'+value).attr('checked', true).change();										
									}else{
										if(richTextarea != undefined) richTextarea.setContent(window.initialValues['ff_elem'+field]);
										if($('#ff_elem'+field).length) $('#ff_elem'+field).val(window.initialValues['ff_elem'+field]).change();
										if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', window.initialValues['ff_elem'+field]).change();
										if($('#rb-'+value).attr('type') == "radio") $('#'+window.initialValues[$('#rb-'+value).attr('id')]).attr('checked', true).change();									
									}
								}	
								if(condition_operator == "greater"){
									if($(this).val() > condition_value){
										if(richTextarea != undefined) richTextarea.setContent(value);
										if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', true).change();
										if($('#ff_elem'+field).length) $('#rb-'+value).attr('checked', true).change();										
										if($('#rb-'+value).attr('type') == "radio") $('#rb-'+value).attr('checked', true).change();	
									}else{
										if(richTextarea != undefined) richTextarea.setContent(window.initialValues['ff_elem'+field]);
										if($('#ff_elem'+field).length) $('#ff_elem'+field).val(window.initialValues['ff_elem'+field]).change();
										if($('#ff_elem'+field).length) $('#ff_elem'+field).attr('checked', window.initialValues['ff_elem'+field]).change();
										if($('#rb-'+value).attr('type') == "radio") $('#'+window.initialValues[$('#rb-'+value).attr('id')]).attr('checked', true).change();									
									}
								}	
							}
							
							if(action == "submit"){	
								if(condition_operator == "equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() == condition_value){
											if(validateForm('<?php echo $form_htmlID;?>')) $('#<?php echo $form_htmlID;?>').submit();
										}
									}else{
										if($(this).attr('checked')){
											if(validateForm('<?php echo $form_htmlID;?>')) $('#<?php echo $form_htmlID;?>').submit();
										}									
									}
								}
								if(condition_operator == "not_equal"){
									if($(this).attr('data-type') != "checkbox"){
										if($(this).val() != condition_value){
											if(validateForm('<?php echo $form_htmlID;?>')) $('#<?php echo $form_htmlID;?>').submit();
										}
									}else{
										if(!$(this).attr('checked')){
											if(validateForm('<?php echo $form_htmlID;?>')) $('#<?php echo $form_htmlID;?>').submit();
										}									
									}
								}	
								if(condition_operator == "less"){
									if($(this).val() < condition_value){
										if(validateForm('<?php echo $form_htmlID;?>')) $('#<?php echo $form_htmlID;?>').submit();
									}
								}	
								if(condition_operator == "greater"){
									if($(this).val() > condition_value){
										if(validateForm('<?php echo $form_htmlID;?>')) $('#<?php echo $form_htmlID;?>').submit();
									}
								}	
							}						
						}
					});
				});
				for(i in window.IDs){
					$('#'+window.IDs[i]).trigger('start');	
				}
			});
			<?php
			}
			?>
			function validateForm(formID){
				window.oErrors = new Array();
				var f = $('#'+formID);
				f.find('[data-validation]').each(function(){
					var dataValidation = $(this).attr('data-validation');
					var varName = $(this).attr('name');
					var data = dataValidation.split("*|*");
					var id = data[0];
					var rule = data[1];
					var elm = $('#ff_elem'+id);
					var hiddenField = '<input type="hidden" name="'+varName+'_validation" value="'+dataValidation+'">';
					$('#'+formID).append(hiddenField);
					var label = elm.parent().find('.formLabel').html().trim();
					var beginningText = "<?php echo t("• Το πεδίο ["); ?>"+label.replace(" :", "")+"] ";
					beginningText = beginningText.replace(/<(?:.|\n)*?>/gm, '');
					beginningText = beginningText.replace('*', '');
					beginningText = beginningText.replace(/\n/gm, '');
					if(!elm.val()){
						window.oErrors.push(beginningText+"<?php echo t("πρέπει να συμπληρωθεί");?>");
						beginningText = "<?php echo t("και");?> ";
					}
					if(rule.indexOf("email") == 0){ // check for valid email
						var pattern = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$";
						if(!elm.val().match(pattern)) {
							window.oErrors.push(beginningText+"<?php echo t("να περιέχει e-mail διεύθυνση");?> \n");
							beginningText = "<?php echo t("και");?> ";
						}
					}
					if(rule.indexOf("limit") == 0){ // check for limit in textarea content
						var parts = rule.split(" ");
						var limit = parts[1];
						if(elm.val().length > limit){
							window.oErrors.push(beginningText+"<?php echo t("να περιέχει το ανώτερο");?> "+limit+" <?php echo t("χαρακτήρες");?> \n");
							beginningText = "<?php echo t("και");?> ";	
						}
					}
					if(rule.indexOf("range") == 0){ // check for valid ranges
						var parts = rule.split(" ");
						var range = parts[1];
						var range = range.split("~|~");	
						var rangeFrom = range[0];
						var rangeTo = range[1];
						if(elm.val().indexOf("/") != -1){
							if($.datepicker.parseDate('dd/mm/yy', rangeFrom) || $.datepicker.parseDate('dd/mm/yy', rangeTo)){ // its a date!
								var dateFrom = rangeFrom;
								var dateTo = rangeTo;
								if($.datepicker.parseDate('dd/mm/yy', rangeFrom)){
									rangeFrom=rangeFrom.split("/");
									var rangeFrom = new Date(rangeFrom[2]+"/"+rangeFrom[1]+"/"+rangeFrom[0]).valueOf()/100;
								}							
								if($.datepicker.parseDate('dd/mm/yy', rangeTo)){
									rangeTo=rangeTo.split("/");
									var rangeTo = new Date(rangeTo[2]+"/"+rangeTo[1]+"/"+rangeTo[0]).valueOf()/100;
								}
								var theDate = elm.val().split("/");
								var theDate = new Date(theDate[2]+"/"+theDate[1]+"/"+theDate[0]).valueOf()/100;
								if((theDate < rangeFrom) && rangeFrom){
									window.oErrors.push(beginningText+"<?php echo t("να περιέχει ημερομηνία μεταγενέστερη της");?> "+dateFrom+" \n");
									beginningText = "<?php echo t("και");?> ";	
								}	
								if((theDate > rangeTo) && rangeTo){
									window.oErrors.push(beginningText+"<?php echo t("να περιέχει ημερομηνία προγενέστερη της");?> "+dateTo+" \n");
									beginningText = "<?php echo t("και");?> ";	
								}
							}
						}else{
							if((parseFloat(elm.val()) < rangeFrom) && rangeFrom){
								window.oErrors.push(beginningText+"<?php echo t("να έχει τιμή μεγαλύτερη από");?> "+rangeFrom+" \n");
								beginningText = "<?php echo t("και");?> ";	
							}	
							if((parseFloat(elm.val()) > rangeTo) && rangeTo){
								window.oErrors.push(beginningText+"<?php echo t("να μην υπερβαίνει την τιμή");?> "+rangeTo+" \n");
								beginningText = "<?php echo t("και");?> ";	
							}	
						}
					}										
				});
				var oValue = (oErrors.length > 0) ? false : true;
				if(!oValue){
					oErrors = oErrors.join("\n");
					alert(oErrors);
				}
				return oValue;
			}
			
			function resetForm(){
				setTimeout(function(){
					for(i in window.IDs){
						$("#"+window.IDs[i]).trigger("start");
					}
				},100);
				return true;				
			}
			</script>
			<?php
			$formMethod = ($form_catID == 3) ? "GET" : $formMethod;
			if($form_captcha == "2"){
				global $langCode;
				?>
			<script src='https://www.google.com/recaptcha/api.js?hl=<?php echo $langCode;?>'></script>
				<?php	
			}
			?>
		<form id="<?php echo $form->htmlID;?>" class="odyssey_form" method="<?php echo $formMethod;?>" accept-charset="UTF-8" action="<?php echo getBase();?>index.php" <?php if(in_array("file", $fieldTypes) && $form_catID != 3){?>enctype="multipart/form-data"<?php }?>>
			<?php
			if($form_catID == 3 && !$keywordFound){
			?>
			<div data-container="1">
			<label for="keyword"><?php echo t("Αναζήτηση για")." :";?></label>
			<input data-type="textfield" id="keyword" type="text" name="keyword" value="<?php echo $keyword; ?>" class="formElement">		
			</div>
			<?php	
			}
			$idx = 0;
			$fieldsetOpen=0;
			while($idx < $counter-1){
				$idx++;
				$required = ${"field".$idx."_required"};
				if(${"field".$idx."_type"} == "fieldset"){ 
					$fieldsetName = ${"field".$idx."_label"};
					$fieldsetOpen++;
					?>
					<fieldset>
					<legend <?php if(!empty(${"field".$idx."_class"})) echo 'class="'.${"field".$idx."_class"}.'"';?>><?php echo $fieldsetName;?></legend>
					<?php
					foreach($fieldsetFields as $key=>$value){
						if($value == $fieldsetName){ // field belongs to this fieldset
							$thisIndex = $key;
							?>
                            
                            
                            
                            <div style="margin: 0 auto;" class="<?php echo 'ff_elem'.$thisID;?> form_container" id="ofElemWrap<?php echo $thisID;?>" data-container="1">
                                <div class="formLabel left">
                                <?php 
								if(${"field".$idx."_type"} != "submit" && ${"field".$idx."_type"} != "reset"){
									if((int)$required) echo "<span class='req'>*</span>";
									echo ${"field".$thisIndex."_label"};
								}
								?>
                                </div>
								<?php
                                displayField($thisIndex, $form->htmlID, $formID); 
                                $registeredIDs[] = $thisIndex;
                                ?>
                            </div>                            
                            
                            
                            
														
							<?php
						}
						$registeredIDs[] = $thisIndex;
					}
					$fieldsetOpen--;
					?>
					</fieldset>
					<?php
				}else{
					$thisID = ${"field".$idx."_id"};
					if(!in_array($idx, $registeredIDs) && empty(${"field".$idx."_fieldset"})){
						if(${"field".$idx."_type"} != "checkbox"){
							?>
							<div style="margin: 0 auto;" class="<?php echo 'ff_elem'.$thisID;?> form_container" id="ofElemWrap<?php echo $thisID;?>" data-container="1">
							<?php
							if(${"field".$idx."_type"} != "hidden" && ${"field".$idx."_type"} != "radio"){
								if(${"field".$idx."_type"} != "submit" && ${"field".$idx."_type"} != "reset"){
									if((int)$required) echo "<span class='req'>*</span>";
									?>
                                    <div class="formLabel left">
                                    <?php
									echo ${"field".$idx."_label"}." :";
									?>
                                    </div>
                                    <?php
								}
							}
							if(${"field".$idx."_type"} == "submit") $submitID =${"field".$idx."_id"};
							if(${"field".$idx."_type"} == "reset"){
								$reset = $idx;
							}else{
								displayField($idx, $form->htmlID, $formID);
							}
							$registeredIDs[] = $idx;
							?>
							</div>	
							<?php
						}else{ // its a checkbox
							?>
							<div style="margin: 0 auto;" class="<?php echo 'ff_elem'.$thisID;?> form_container" id="ofElemWrap<?php echo $thisID;?>" data-container="1">
                                <div style="float:left; margin: 0 5px 0 0">
                                <?php displayField($idx, $form->htmlID, $formID);?>
                                </div>
                                <?php 
								 echo ${"field".$idx."_label"};  
								$registeredIDs[] = $idx;
								?>
							</div>	
							<?php							
						}
					}
				}
			?>
			
			<?php
			}
			if($form_captcha == "1" && $submitID){
                $captcha = '<div style="margin: 10px auto 2px auto;" class="form_container" id="ofElemWrapCaptcha" data-container="1"><div class="formLabel left"><span class="req">*</span>'.t("Κωδικός ταυτοποίησης (captcha)").'</div><div><img src="CaptchaSecurityImages.php?width=100&amp;height=40&amp;characters=5" style="float:left;min-width:100px;" alt="captcha" />&nbsp;<input name="oForm_security_code" id="oForm_security_code" type="text" style="width:80px"></div><div class="formLabel left" style="margin-bottom: 15px;">'.t("Συμπληρώστε τους χαρακτήρες που εμφανίζονται στην εικόνα").'</div></div>';				
				?>
				<script type="text/javascript">
					jQuery(function($){	
						$('#<?php echo "ofElemWrap".$submitID;?>').before('<?php echo $captcha;?>');			
					});
				</script>
				<?php				
			}
			if($form_captcha == "2" && $submitID){
                $captcha = '<div style="margin: 10px auto 20px auto;" class="form_container" id="ofElemWrapCaptcha" data-container="1"><div class="g-recaptcha" data-sitekey="6LesLCATAAAAAMb1V-SibnemWbLB995dZ_jCZgXa"></div></div>';				
				?>
				<script type="text/javascript">
					jQuery(function($){	
						$('#<?php echo "ofElemWrap".$submitID;?>').before('<?php echo $captcha;?>');			
					});
				</script>
				<?php				
			}			
			if($reset){
				$resetButton = addslashes(displayField($reset, $form->htmlID, $formID));
				?>
			<script type="text/javascript">
				jQuery(function($){	
					$('#<?php echo "ofElemWrap".$submitID;?>').append('<?php echo $resetButton;?>');			
				});
			</script>
				<?php
			}
			$section = ($form_catID == 3) ? $system->getTableSectionName($form_section) : $section;
			$view = ($form_catID == 3) ? "search" : $view;
			?>
			<input name="section" type="hidden" value="<?php echo $section;?>">
			<input name="view" type="hidden" value="<?php echo $view;?>">
			<input name="langID" type="hidden" value="<?php echo $langID;?>">	
			<?php
			if($form_catID != 3){
			?>
			<input name="id" type="hidden" value="<?php echo $id;?>">
			<input name="formID" type="hidden" value="<?php echo $formID;?>">		
			<input type="hidden" name="moduleFormSubmited" value="1">
			<?php
			}else{
			?>
			<input type="hidden" name="submitSearch" value="1">
			<?php	
			}
			?>
			<input type="text" name="oForm_info" class="required">
			</form>
			<?php
		}else{
			$messages->addError(t("Δεν βρέθηκαν πεδία αυτής της φόρμας στην επιλεγμένη γλώσσα"));
			?>
			<div style="height:30px; clear:both"></div>
			<?php
			$messages->printErrorMessages();
			?>
			<div style="height:30px; clear:both"></div>
			<?php
		}
	}
}

if($useModuleContainer){		
	?>
</div>
	<?php
	}

function displayField($index, $htmlFormID, $formID){
	global $radioButtonsAlign;
	global $form_catID;
	global ${"field".$index."_id"};
	global ${"field".$index."_name"};
	global ${"field".$index."_label"};
	global ${"field".$index."_default"};
	global ${"field".$index."_selectSource"};
	global ${"field".$index."_class"};
	global ${"field".$index."_required"};
	global ${"field".$index."_checked"};
	global ${"field".$index."_fieldset"};
	global ${"field".$index."_type"};
	global ${"field".$index."_sort"};
	global ${"field".$index."_interactive"};
	global ${"field".$index."_condition_operator"};
	global ${"field".$index."_condition_value"};
	global ${"field".$index."_required"};
	global ${"field".$index."_isemail"};
	global ${"field".$index."_limit"};
	global ${"field".$index."_rangeFrom"};
	global ${"field".$index."_rangeTo"};
	global ${"field".$index."_rules"};
	global ${"field".$index."_actions"};
	$id = ${"field".$index."_id"};
	$name = ${"field".$index."_name"};
	$label = ${"field".$index."_label"};
	$default = ${"field".$index."_default"};
	$selectSource = ${"field".$index."_selectSource"};
	$class = ${"field".$index."_class"};
	$required = ${"field".$index."_required"};
	$checked = ${"field".$index."_checked"};
	$fieldset = ${"field".$index."_fieldset"};
	$type = ${"field".$index."_type"};
	$sort = ${"field".$index."_sort"};
	$interactive = ${"field".$index."_interactive"};
	$condition_operator = ${"field".$index."_condition_operator"};
	$condition_value = ${"field".$index."_condition_value"};
	$required = ${"field".$index."_required"};
	$isemail = ${"field".$index."_isemail"};
	$limit = ${"field".$index."_limit"};
	$rangeFrom = ${"field".$index."_rangeFrom"};
	$rangeTo = ${"field".$index."_rangeTo"};
	$rules = ${"field".$index."_rules"};
	$actions = ${"field".$index."_actions"};
	global ${$id};
	global ${$name};
	global ${$label};
	global ${$default};
	global ${$selectSource};
	global ${$class};
	global ${$required};
	global ${$checked};
	global ${$fieldset};
	global ${$type};
	global ${$sort};
	global ${$interactive};
	global ${$condition_operator};
	global ${$condition_value};
	global ${$required};
	global ${$isemail};
	global ${$limit};
	global ${$rangeFrom};
	global ${$rangeTo};
	global ${$rules};
	global ${$actions};

	$default = (${$name}) ? ${$name} : $default;
	if($required){
		$validation = 'data-validation="'.$id."*|*".$rules.'"';
	}
	if($interactive){
		$interactive_actions = explode(PHP_EOL, $actions);
		array_pop($interactive_actions); // last item is empty, so get rid of it
		$data = "";
		foreach($interactive_actions as $ia) $data.=$ia."~~~|||~~~";
		$data = substr($data, 0, -9);
		$temp = implode(",",$interactive_actions);
		$interactive_actions = 'data-interactive=\''.$id."|".$condition_operator."|".$condition_value."*|*".$data.'\'';
		$interactive_actions = str_replace('"', null, $interactive_actions);
		$interactive_actions = str_replace('[', null, $interactive_actions);
		$interactive_actions = str_replace(']', null, $interactive_actions);
	}	
	
	if($type == "textfield"){
		?>
<input data-type="<?php echo $type;?>" <?php echo $validation;?> <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" type="text" name="<?php echo $name; ?>" value="<?php echo $default; ?>" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
	}
	
	if($type == "textarea"){
		$default = (${$name}) ? ${$name} : $default;
		?>
<textarea data-type="<?php echo $type;?>" <?php echo $validation;?> id="<?php echo 'ff_elem'.$id;?>" name="<?php echo $name; ?>" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>"><?php echo $default; ?></textarea>
		<?php
	}	
	
	if($type == "int"){
		?>
<input data-type="<?php echo $type;?>" <?php echo $validation;?> <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" type="text" name="<?php echo $name; ?>" value="<?php echo $default; ?>" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
	}	
	
	if($type == "decimal"){
		?>
<input data-type="<?php echo $type;?>" <?php echo $validation;?> <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" type="text" name="<?php echo $name; ?>" value="<?php echo $default; ?>" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
	}	
	if($type == "date"){
		?>
<input data-type="<?php echo $type;?>" <?php echo $validation;?> <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" type="text" name="<?php echo $name; ?>" value="<?php echo $default; ?>" class="formElement date_picker<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
	}	
	
	if($type == "colorpicker"){
		?>
<input data-type="<?php echo $type;?>" <?php echo $validation;?> <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" type="text" name="<?php echo $name; ?>" value="<?php echo $default; ?>" class="formElement colorpicker<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
	}		

	if($type == "richTextarea"){
		$default = (${$name}) ? ${$name} : $default;
		?>
<textarea data-type="<?php echo $type;?>" <?php echo $validation;?> id="<?php echo 'ff_elem'.$id;?>" name="<?php echo $name; ?>" class="formElement mceEditor<?php if(!empty($class)) echo ' '.$class; ?>"><?php echo $default; ?></textarea>
		<?php
	}
	
	if($type == "checkbox"){
		?>
<input data-type="<?php echo $type;?>" <?php echo $validation;?> <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" type="checkbox" name="<?php echo $name; ?>" value="1" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>" <?php if($checked) echo "checked";?> style="margin-top: -5px; ">
		<?php
	}	
	
	if($type == "radio"){
		global $db;
		global $langID;
		$q = "select forms_selects.*, content_forms_selects.title from forms_selects, content_forms_selects where 
				forms_selects.id = content_forms_selects.mainID and content_forms_selects.langID='$langID' 
				and forms_selects.formID='$formID' and forms_selects.fieldID='$id'";
		$options = $db->getRecords($q);
		?>
 		<div class="formLabel left"><?php echo $label." :";?></div> 
        <div>                          
		<?php
		foreach($options as $option){
			if(${$name}){
				$checked = (${$name} == $option->value) ? "checked=true" : "";
			}else{
				$checked = ($option->selected) ? "checked=true" : "";
			}			
		?>
        <div style="display:inline-block; margin-bottom: 5px;">
		<input data-fid="<?php echo $id;?>" data-type="<?php echo $type;?>" <?php echo $interactive_actions;?> type="radio" id="rb-<?php echo $option->value;?>" name="<?php echo $name; ?>" value="<?php echo $option->value;?>" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>" <?php echo $checked;?>> <?php echo $option->title;?>
        </div>
		<?php
		if($radioButtonsAlign == "list") echo "<br>";

		}
		?>
        </div>
        <?php
	}
	
	if($type == "selectMenu"){
		global $db;
		global $langID;
		global $system;
		global $categories;
		?>
		<select data-type="<?php echo $type;?>" <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" name="<?php echo $name; ?>" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
		if($selectSource == "custom_data"){
			$q = "select forms_selects.*, content_forms_selects.title from forms_selects, content_forms_selects where 
					forms_selects.id = content_forms_selects.mainID and content_forms_selects.langID='$langID' 
					and forms_selects.formID='$formID' and forms_selects.fieldID='$id'";
			$options = $db->getRecords($q);
			foreach($options as $option){
				if(${$name}){
					$selected = (${$name} == $option->value) ? "selected=true" : "";
				}else{
					$selected = ($option->selected) ? "selected=true" : "";
				}
			?>
			<option value="<?php echo $option->value;?>" <?php echo $selected;?>><?php echo $option->title;?></option>
			<?php
			}
			if(!count($options)){
			?>
			<option value=""><?php echo t("Δεν βρέθηκαν επιλογές αυτής της γλώσσας");?></option>
			<?php				
			}			
		}else{ // section or menu the contents of the select
			$isMenu = (preg_match('/^c/', $selectSource));
			$selectSectionID = str_replace("c", "", $selectSource);
			$selectSection = $system->getTableSectionName($selectSectionID);
			if(!$isMenu){
				$q = "select $selectSection.id, content_$selectSection.title from $selectSection, content_$selectSection where 
						$selectSection.id = content_$selectSection.mainID and content_$selectSection.langID='$langID' and $selectSection.active=1 
						order by $selectSection.sort, content_$selectSection.title";
				$options = $db->getRecords($q);	
				foreach($options as $option){
					$selected = (${$name} == $option->id) ? "selected=true" : "";
				?>
			<option value="<?php echo $option->id;?>" <?php echo $selected;?>><?php echo $option->title;?></option>
				<?php
				}
				if(!count($options)){
				?>
			<option value=""><?php echo t("Δεν βρέθηκαν επιλογές αυτής της γλώσσας");?></option>
				<?php				
				}				
			}else{ // its a menu
				$selectSection.="_categories";
				$options = $categories->getArrayOfCategoriesForSelect(0, 0, false, $selectSection, ${$name});
				echo $options;
				if(empty($options)){
				?>
			<option value=""><?php echo t("Δεν βρέθηκαν επιλογές αυτής της γλώσσας");?></option>
				<?php				
				}				
			}
		}
		?>
		</select>
		<?php
	}	
	
	if($type == "selectList"){
		global $db;
		global $langID;
		global $system;
		global $categories;
		?>
<select data-type="<?php echo $type;?>" <?php echo $interactive_actions;?> id="<?php echo 'ff_elem'.$id;?>" multiple="multiple" name="<?php echo $name; ?>[]" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
		if($selectSource == "custom_data"){
			$q = "select forms_selects.*, content_forms_selects.title from forms_selects, content_forms_selects where 
					forms_selects.id = content_forms_selects.mainID and content_forms_selects.langID='$langID' 
					and forms_selects.formID='$formID' and forms_selects.fieldID='$id' order by forms_selects.id";
			$options = $db->getRecords($q);
			foreach($options as $option){
				if(${$name}){
					$selected = (${$name} == $option->value) ? "selected=true" : "";
				}else{
					$selected = ($option->selected) ? "selected=true" : "";
				}
			?>
			<option value="<?php echo $option->value;?>" <?php echo $selected;?>><?php echo $option->title;?></option>
			<?php
			}
			if(!count($options)){
			?>
			<option value=""><?php echo t("Δεν βρέθηκαν επιλογές αυτής της γλώσσας");?></option>
			<?php				
			}			
		}else{ // section or menu the contents of the select
			$isMenu = (preg_match('/^c/', $selectSource));
			$selectSectionID = str_replace("c", "", $selectSource);
			$selectSection = $system->getTableSectionName($selectSectionID);
			if(!$isMenu){
				$q = "select $selectSection.id, content_$selectSection.title from $selectSection, content_$selectSection where 
						$selectSection.id = content_$selectSection.mainID and content_$selectSection.langID='$langID' and $selectSection.active=1 
						order by $selectSection.sort, content_$selectSection.title";
				$options = $db->getRecords($q);	
				foreach($options as $option){
					$selected = (${$name} == $option->id) ? "selected=true" : "";
				?>
				<option value="<?php echo $option->id;?>" <?php echo $selected;?>><?php echo $option->title;?></option>
				<?php
				}
				if(!count($options)){
				?>
				<option value=""><?php echo t("Δεν βρέθηκαν επιλογές αυτής της γλώσσας");?></option>
				<?php				
				}				
			}else{ // its a menu
				$selectSection.="_categories";
				$options = $categories->getArrayOfCategoriesForSelect(0, 0, false, $selectSection, ${$name});
				echo $options;
				if(empty($options)){
				?>
				<option value=""><?php echo t("Δεν βρέθηκαν επιλογές αυτής της γλώσσας");?></option>
				<?php				
				}				
			}
		}
		?>
		</select>
		<?php
	}	
	
	if($type == "password"){
		?>
<input data-type="<?php echo $type;?>" <?php echo $validation;?> id="<?php echo 'ff_elem'.$id;?>" type="password" name="<?php echo $name; ?>" value="<?php echo $default; ?>" class="formElement<?php if(!empty($class)) echo ' '.$class; ?>">
		<?php
	}	
	
	if($type == "file"){
		?>
		<input data-type="<?php echo $type;?>" id="<?php echo 'ff_elem'.$id;?>" type="file" name="<?php echo $name; ?>">
		<?php
	}		
	
	if($type == "hidden"){
		?>
		<input data-type="<?php echo $type;?>" id="<?php echo 'ff_elem'.$id;?>" type="hidden" name="<?php echo $name; ?>" value="<?php echo $default; ?>">
		<?php
	}
	
	if($type == "reset"){
		$resetButton = '<input data-type="'.$type.'" id="ff_elem'.$id.'" type="reset" name="'.$name.'" value="'.$label.'" class="formElement btn btn-warning ';
		if(!empty($class)) $resetButton.=$class;
		$resetButton.='" onclick="return resetForm()">';
		return $resetButton;
	}			
		
	if($type == "submit"){
		?>
<input data-type="<?php echo $type;?>" id="<?php echo 'ff_elem'.$id;?>" type="submit" name="<?php echo $name."_Oform"; ?>" value="<?php echo $label; ?>" class="formElement btn btn-inverse<?php if(!empty($class)) echo ' '.$class; ?>" onclick="return validateForm('<?php echo $htmlFormID;?>')">
		<?php
	}	

}
?>