<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendTextbox.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendDatetime.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/QuoteRequestName.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/QuoteRequestPhone.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/QuoteLoginEmail.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobServices.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/FrontendTextarea.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/MultiLangPairSelector.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobQualityPreference.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobAttachments.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobRecipients.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobQuoteDeadline.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobDeadline.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/BotJS.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/JobHandler.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Languages.inc.php" );

	require_once( $GLOBALS["site_root"]."/includes/models/ServiceTypes.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Specialties.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Job.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/User.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/MyUser.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Constants.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/TemplateMail.inc.php" );


	require_once( $GLOBALS["site_root"]."/includes/urlgen/RequestQuote.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/urlgen/MyUser.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/urlgen/Article.inc.php" );

	class QuotePane extends Widget {
		protected $offer_contact_name;
		protected $offer_contact_email;
		protected $offer_contact_phone;

		protected $offer_services;
		protected $offer_quote_deadline;
		protected $offer_specialty;

		protected $offer_deadline;
		protected $offer_description;
		protected $offer_quality_preference;
		protected $offer_languages;

		protected $offer_recipients;
		protected $offer_attachments;
		
		protected $offer_submit;

		protected $bPreview;
		protected $bActivation;


		protected function isLanguagesValid( $languages ) {
			$lk = LanguagesModel::getLanguageOptions( false );
	
			if (!count( $languages )) return false;
			foreach ($languages as $language) {
				if (!$language["source_language_id"]) return false;
				// if (!isset( $lk[$language["source_language_id"]] )) return false;
				if (!$language["target_language_id"]) return false;
				// if (!isset( $lk[$language["target_language_id"]] )) return false;
			}
			return true;
		}

		protected function isServicesValid( $services ) {
			if (!count( $services )) {
				GlobalWarningMessage( "error_services" , __("quotepage_error_No_service_filled") );
				return false;
			}
			foreach ($services as $servicetype_id => $service) {
				if (!$service["unit"]) {
					GlobalWarningMessage( "error_services_unit" , __("quotepage_error_No_service_unit_filled") );
					return false;
				}
				if (!strlen(trim( $service["quantity"] ))) {
					GlobalWarningMessage( "error_services_size" , __("quotepage_error_No_service_size_filled") );
					return false;
				}
				// tolmacsolas
				if ($servicetype_id==2) {
					if (!isset( $service["loc"] ) || !strlen( trim( $service["loc"] ) ) ) {
						GlobalWarningMessage( "error_services_location" , __("Location_empty") );
						return false;
					}
				}
			}
			return true;
		}
	
		protected function isValidQuoteDeadline() {
			$deadline = $this->offer_quote_deadline->getValue();
			if (strlen($deadline)!=16) {
				GlobalWarningMessage( "error_no_quote_deadline" , __("quotepage_error_No_quote_deadline") );
				return false;
			}
			if ($deadline<fo3_date("Y-m-d H:i",fo3_time() + JOB_QUOTE_DEADLINE_MIN_DELTA)) {
				GlobalWarningMessage( "error_quote_deadline_in_past" , __("quotepage_error_Quote_deadline_too_early" ) );
				return false;
			}
			if ($deadline>fo3_date("Y-m-d H:i",fo3_time() + JOB_QUOTE_DEADLINE_MAX_DELTA )) {
				GlobalWarningMessage( "error_quote_deadline_in_far_future" , __("quotepage_error_Quote_deadline_in_far_future" ) );
				return false;
			}

			return true;
		}

		protected function isValidDeadline() {
			$deadline = $this->offer_deadline->getValue();
			if (strlen($deadline)!=16) {
				GlobalWarningMessage( "error_no_deadline" , __("quotepage_error_No_deadline") );
				return false;
			}
			if ($deadline<fo3_date("Y-m-d H:i")) {
				GlobalWarningMessage( "error_deadline_in_past" , __("quotepage_error_Deadline_in_past" ) );
				return false;
			}
			$deadline2 = $this->offer_quote_deadline->getValue();
			if ($deadline<$deadline2) {
				GlobalWarningMessage( "error_deadline_before_quote_deadline" , __("quotepage_error_Deadline_before_quote_deadline") );
				return false;
			}
			return true;
		}

		protected function validateQuoteRequest() {
			$retval = true;

			if (!$this->oBotJS->isValid()) {
				GlobalWarningMessage( "no_bots_please" , __("No_bots_please") );
				$retval = false;
			}
			// validate languages
			$languages = $this->offer_languages->getValue();
			if (!$this->isLanguagesValid( $languages )) {
				GlobalWarningMessage( "error_languages" , __("quotepage_error_One_or_more_language_not_defined" ) );
				$retval = false;
			}
			// validate services
			$services = $this->offer_services->getValue();
			if (!$this->isServicesValid( $services )) {
				$retval = false;
			}
			// validate specialty
			$specialty = $this->offer_specialty->getValue();
			if (!$specialty) {
				// egyeb
				if (!strlen( $this->offer_custom_specialty->getValue() )) {
					GlobalWarningMessage( "error_specialty" , __("quotepage_error_No_specialty_filled") );
					$retval = false;
				}
			}
			// validate description
			$description = $this->offer_description->getValue();
			if (!strlen( trim( $description ))) {
				GlobalWarningMessage( "error_description" , __("quotepage_error_Description_not_filled") );
				$retval = false;
			}

			// validate quote_deadline
			if (!$this->isValidQuoteDeadline()) $retval = false;
			// validate deadline
			if (!$this->isValidDeadline()) $retval = false;

			// validate job recipients
			$recipients = $this->offer_recipients->getValue();
			switch ($recipients["type"]) {
			case "all":
			case "agencies":
			case "freelancers":
				break;
			case "custom":
				if (empty( $recipients["custom_recipients"] )) {
					GlobalWarningMessage( "error_no_custom" , __("quotepage_error_No_custom_recipient") );
					$retval = false;
				}
				break;
			default:
			}

			// if logged in then contact info is not needed
			$myuser = new MyUserModel();
			if ($myuser->isUserLoggedin()) return $retval;
	
			if (!strlen( trim( $this->offer_contact_name->getValue()))) {
				GlobalWarningMessage( "error_contact_name" , __("quotepage_error_Contact_name_not_filled") );
				$retval = false;
			}
			$email = trim( $this->offer_contact_email->getValue() );
			if (!strlen( $email )) {
				GlobalWarningMessage( "error_contact_email" , __("quotepage_error_Contact_email_not_filled") );
				$retval = false;
			} else if (!fo3_is_email_valid( $email )) {
				GlobalWarningMessage( "error_contact_email" , __("quotepage_error_Contact_email_invalid") );
				$retval = false;
			}

			if (!strlen( trim( $this->offer_contact_phone->getValue()))) {
				GlobalWarningMessage( "error_contact_phone" , __("quotepage_error_Contact_phone_not_filled") );
				$retval = false;
			}
			return $retval;
		}

		protected function generateJobTitleDeadline() {
			// TODO maybe language specific
			$val = substr( $this->offer_quote_deadline->getValue() , 0 , 10 );
			$val = str_replace( "-" , "." , $val );
			switch ($GLOBALS["language"]) {
			case "hu":
			default:
				$val=$val."-ig";break;
			case "en":
				$val="until ".$val;break;
			}
			return $val;	
		}

		protected function generateJobTitleTranslators() {
			$recs = $this->offer_recipients->getValue();
			$allusers = new AllUsersModel();
			switch ($recs["type"]) {
			default:
				return sprintf( " | %s",__("recipients_title_all") );
			case "freelancers":
			case "agencies":
				return sprintf( " | %s",__("recipients_title_".$recs["type"]) );
			/*
				$num = $allusers->getActiveAgencies();
				break;
			case "freelancers":
				$num = $allusers->getActiveFreeLancers();
				break;
			case "all":
				$num = $allusers->getActiveAgencies()+$allusers->getActiveFreelancers();
				break;
			*/
			case "custom":
				$num = count( $recs["custom_recipients"] );
				return sprintf( " | %d %s",$num,__("recipients_recipients" ));
			}
			return "";
		}

		protected function generateJobTitle() {
			$retval = "";

			// generate languages
			$languages = $this->offer_languages->getValue();
			$lm = new LanguagesModel();
			$langs = $lm->getLanguageOptions( false );
			$lstrings = array();
			foreach ($languages as $language) {
				$lstrings[]= sprintf( "%s-%s",
					$langs[$language["source_language_id"]],
					$langs[$language["target_language_id"]] );
			}
			$retval.=implode( ", " , $lstrings ) . " | ";
			//generate services
			$services = $this->offer_services->getValue();
			$sstrings = array();
			$sm = new ServiceTypesModel();
			$stypes = $sm->getServiceTypeOptions( false );
			$sutypes = $sm->getServiceTypeUnitOptions( false );
			foreach ($services as $servicetypeid => $service) {
				$us = "";
				switch ($service["unit"]) {
				case 6:	// FIXME csunya
					$us=sprintf( "%s %s",
						$sutypes[$service["unit"]],
						$stypes[$servicetypeid] );
					break;
				default:
					$us=sprintf( "%s %s %s",
						$service["quantity"],
						$sutypes[$service["unit"]],
						$stypes[$servicetypeid] );
					break;
				}
				if ($servicetypeid==2) {
					$us.=sprintf( " - %s" , $service["loc"] );
				}
				$sstrings[]=$us;
			}
			$retval.=implode( ", " , $sstrings );
			// generate specialty
			$sm = new SpecialtiesModel();
			$spec_id = $this->offer_specialty->getValue();
			if ($spec_id) {
				$specs = $sm->getSpecialtyOptions();
				$retval.=", " . $specs[$spec_id];
			} else {
				$retval.=", " . $this->offer_custom_specialty->getValue();
			}
			// generate quote deadline
			$retval.=" | " . $this->generateJobTitleDeadline();
			// generate translators
			$retval.=$this->generateJobTitleTranslators();
			return $retval;
		}

		protected function saveState() {
			$_SESSION["job_offer"]=$this->aP;
		}

		protected function loadState() {
			if (!isset( $_SESSION["job_offer"] )) return;
			$this->aP = $_SESSION["job_offer"];
		}

		protected function clearState() {
			if (isset( $_SESSION["job_offer"] )) return;
			unset( $_SESSION["job_offer"] );
		}

		protected function isAwaitingConfirmation() {
			return isset( $this->aG["awaiting_confirmation"] );
		}

		protected function isPreview() {
			return isset( $this->aG["preview"] );
		}

		protected function goToPreview() {
			$rqu = new RequestQuoteURL();
			$url = $rqu->renderPreviewURL();
			FNTH_redirect( $url );
		}

		protected function cameFromPreview() {
			$uri = fo3_get_http_referer_uri();
			
			$url = (strlen( $uri )) ? "http://" . $_SERVER["SERVER_NAME"] . $uri : "";

			$eurl = FNTH_explode_url( $url );
			$rqu = new RequestQuoteURL();
			$previewurl = $rqu->renderPreviewURL();
			return ($eurl["path"]==$previewurl);
		}

		protected function saveJob() {
			$muu = new MyUserModel();
			$mmm = new MyMemberModel();
			$um = new UserModel();
			$datas = array();
			if (!$muu->isUserLoggedin()) {
				$user_id = $um->getUserIdFromEmail( $this->offer_contact_email->getValue() );
				if (!$user_id) {
					// A, ha meg nincs user, akkor elso regisztracio => quickreg, userid ment
					$p = array();
					$p["user_name"]=$this->offer_contact_name->getValue();
					$p["email"]=$this->offer_contact_email->getValue();
					$p["pwd"]=fo3_pwgen();
					$p["contact_phone"]=$this->offer_contact_phone->getValue();
					$user_id = $um->addUser( $p );
				}
			} else {
				// B, mar be van jelentkezve, csak user_id = loggedinuser
				$user_id = $muu->getLoggedinUserId();
				$datas["poster_acknowledged"]=true;	// instant acknowledgement
			}
			$user = $um->getUserFromUserId( $user_id );
			$datas["poster_user_id"]=$user_id;
			$datas["poster_name"]=$user["user_name"];
			$datas["poster_email"]=$user["email"];
				
			$datas["poster_phone"]=$user["contact_phone"];
			if ($mmm->isMemberLoggedIn()) {
				$mm = new MemberModel();
				$member = $mm->getMemberFromMemberId( $mmm->getLoggedInMemberId() );
				if ($member["is_phone_visible"] && strlen( $member['phone'] ))
					$datas["poster_phone"]=$member['phone'];
			}
			// $datas["poster_cellular"]="majduserbol";
			// $datas["poster_show_phone"]=false;
			$datas["job_title"]=$this->generateJobTitle();
			$datas["job_quote_deadline"]=$this->offer_quote_deadline->getValue();
			if ($this->offer_specialty->getValue()>0) {
				$datas["job_specialty"]=$this->offer_specialty->getValue();
			} else {
				$datas["job_custom_specialty"]=$this->offer_custom_specialty->getValue();
			}
			$datas["job_deadline"]=$this->offer_deadline->getValue();
			$datas["job_description"]=$this->offer_description->getValue();
			$datas["job_languages"]=$this->offer_languages->getValue();
			$datas["job_services"]=$this->offer_services->getValue();
			// $datas["job_mainaspects"]="majdaformrol";	// mar nincs
			$datas["job_qualitypreference"]=$this->offer_quality_preference->getValue();
			$datas["job_recipients"]=$this->offer_recipients->getValue();

			// job rogzitese			
			$jm = new JobModel();
			$job_id = $jm->addJob( $datas );

			// attachmentek rogzitese
			$attachments = $this->offer_attachments->getAttachments();
			if (is_array( $attachments ) && !empty( $attachments )) {
				foreach ($attachments as $att) $jm->addJobAttachment( $job_id , $att );
			}
			if ($muu->isUserLoggedin()) {
				$this->sendAcknowledgementMail( $job_id );
			} else {
				$this->sendConfirmationMail( $job_id );
			}

			// cleanup
			$this->offer_attachments->clearAttachments();
			$this->clearState();
			return $job_id;
		}

		protected function sendAcknowledgementMail( $job_id ) {
			// emlekezteto a munkaajanlatrol
			$jm = new JobModel();
			$job = $jm->getJobFromId( $job_id );
			$um = new UserModel();
			$user = $um->getUserFromUserId( $job["poster_user_id"] );
			$muu = new MyUserURL();

			$mail = new TemplateMailModel( "sys_quote_request_notification" , $GLOBALS["language"] );
			$cm = new ConstantsModel( $mail );
			$cm->addSystemParametersToTemplate();
			$cm->addJobConstantsToTemplate( $job_id );

			$mail->setParam( "url_confirm_job", $muu->renderQuoteRequestActivationURL( array( "hash" => $job["hash"] ) ) );
			$mail->setParam( "url_close_job", $muu->renderQuoteRequestCloseURL( array( "hash" => $job["hash"] ) ) );
			$mail->setParam( "url_revoke_job", $muu->renderQuoteRequestRevokeURL( array( "hash" => $job["hash"] ) ) );


			$mail->setParam( "user" , $user );
			$mail->sendMail( $job["poster_email"] );
		}

		protected function isJobActivationAvailable( $job_id ) {
			$myuser = new MyUserModel();
			if (!$myuser->isUserLoggedin()) return false;	// ha nincs belepve eselytelen

			$um = new UserModel();
			$user = $um->getUserFromUserId( $myuser->getLoggedinUserId() );
			if (!$user) return false;
			return ($user["is_instant_sender"]=="t");		// siman csak van-e joga instant sendre

			/*
			// TODO	
			$jm = new JobModel();
			$jobs = $jm->getLastJobsFromPoster( $myuser->getLoggedinUserId() , 2 );	// leszedjuk a 2 utolso jobot
			foreach ($jobs as $job) {
				if ($job["job_id"]==$job_id) continue;	// nem azt keressuk, amit eppen vizsgalunk
				if ($job["admin_acknowledged"]=="t") return true;	// ha az elozot jovahagyta az admin, akkor kimehet
				if ($job["is_sent"]=="f") return false;	// baszdmeg ag: esetleg meg az elozo sem ment ki
				$time = fo3_convert_YmdHis_to_unix( $job["sent_at"] );
				if ($time>fo3_time()-86400) return false;	// nem telt el 24 ora az utolso utan
			}
			return true;
			*/
		}

		protected function sendConfirmationMail( $job_id ) {
			// kattints a levelben levo linkre es akkor user+job ackolas
			$jm = new JobModel();
			$job = $jm->getJobFromId( $job_id );
			$um = new UserModel();
			$user = $um->getUserFromUserId( $job["poster_user_id"] );
			$muu = new MyUserURL();

			$mail = new TemplateMailModel( "sys_quote_request_confirmation" , $GLOBALS["language"] );
			$cm = new ConstantsModel( $mail );
			$cm->addSystemParametersToTemplate();
			$cm->addJobConstantsToTemplate( $job_id );

			$mail->setParam( "url_confirm_job", $muu->renderQuoteRequestActivationURL( array( "hash" => $job["hash"] ) ) );
			$mail->setParam( "url_close_job", $muu->renderQuoteRequestCloseURL( array( "hash" => $job["hash"] ) ) );
			$mail->setParam( "url_revoke_job", $muu->renderQuoteRequestRevokeURL( array( "hash" => $job["hash"] ) ) );


			$mail->setParam( "user" , $user );
			$mail->sendMail( $job["poster_email"] );
		}

		protected function goToConfirmed() {
			$myuser = new MyUserModel();
			if ($myuser->isUserLoggedin()) {
				// mar be van lepve
				$muu = new MyUserURL();
				FNTH_redirect( $muu->renderMyQuoteRequestsURL() );
			} else {
				$rqu = new RequestQuoteURL();
				FNTH_redirect( $rqu->renderAwaitingConfirmationURL() );
			}
		}

		protected function getJobLanguagePairs() {
			// FNTH_da( $this->offer_languages->getValue() );
			return $this->offer_languages->getValue();
		}
		protected function getJobServices() {
			// FNTH_da( $this->offer_services->getValue() );
			return $this->offer_services->getValue();
		}

		protected function getJobRecipients() {
			$data =  $this->offer_recipients->getValue();
			return fo3_render_job_recipients( $data , true );
		}

		protected function handleQuoteRequestPreviewEvent() {
			// ha previewben vagyunk

			$saved = $this->aP;		// mentsuk a postot
			$this->loadState();		// sessionbol turjuk felul a postot
			$this->aP = array_merge( $this->aP , $saved );	// toltsu vissza a post cuccait
			$this->offer_submit->setValue( __("quotepage_Confirm_the_job","attr") );
			$this->refreshChildValuesFromArray( $this->aP );
			if (!$this->offer_submit->isSubmitted()) {
				// preview elokeszites
				$this->setParam( "job_title" , $this->generateJobTitle() );
				$this->setParam( "languages" , LanguagesModel::getLanguageOptions() );
				$this->setParam( "job_languagepairs" , $this->getJobLanguagePairs() );
				$this->setParam( "servicetypes" , ServiceTypesModel::getServiceTypeOptions() );
				$this->setParam( "servicetypeunits" , ServiceTypesModel::getServiceTypeUnitOptions() );
				$this->setParam( "job_services" , $this->getJobServices() );
				$this->setParam( "specialties" , SpecialtiesModel::getSpecialtyOptions() );
				$this->setParam( "job_specialty" , $this->offer_specialty->getValue() );
				$this->setParaM( "job_custom_specialty" , $this->offer_custom_specialty->getValue() );
				$this->setParam( "job_description" , $this->offer_description->getValue() );
				$this->setParam( "job_quote_deadline" , $this->offer_quote_deadline->getValue() );
				$this->setParam( "job_deadline" , $this->offer_deadline->getValue() );
				$this->setParam( "job_quality_preference" , $this->offer_quality_preference->getValue() );
				$this->setParam( "job_recipients" , $this->getJobRecipients() );
				return parent::handleEvents();
			}
			// preview submit, itt jon a job feladas
			$job_id = $this->saveJob();			// elmentjuk a jobot, es kuldunk konfirmacios mailt, ha kell
			if ($this->isJobActivationAvailable( $job_id )) {
				$jm = new JobModel();
				$jm->adminAcknowledgeJob( $job_id , true );
				$jm->activateJob( $job_id );
			}

			// uzemeltetoi mail
			$mail = new TemplateMailModel( "sys_admin_quote_request_confirmation" );
			$cm = new ConstantsModel( $mail );
			$cm->addSystemParametersToTemplate();
			$cm->addJobConstantsToTemplate( $job_id );
			$mail->sendMail( $GLOBALS["fo3_admin_email"] );
			
			$this->goToConfirmed();		// vagy email confirmalos lapra megyunk, vagy
		}	

		protected function handleQuoteRequestEvent() {
			// eles quote event
			$this->offer_submit->setValue( __("quotepage_Post_the_job","attr") );
			$this->offer_submit->refreshValueFromArray();
			if (!$this->offer_submit->isSubmitted()) {	// ha nem volt submit gomb, akkor nem magunkrol jottunk
				if ($this->cameFromPreview()) {	// ha previewbol jottunk (vissza egyet)
					$this->loadState();			// akkor toltsuk be az allapotot es frissitsunk mindent
					$this->refreshChildValuesFromArray( $this->aP );
				}
				return parent::handleEvents();	// egyebkent meg tok ures a form
			}
			$this->handleChildEvents();			// job preview miatt kell
			$this->refreshChildValuesFromArray( $this->aP );	// felulbasszuk a default parametereket
			if (!$this->validateQuoteRequest())	// ha nem valid, akkor maradunk itt ahol vagyunk
				return parent::handleEvents();

			$this->saveState();				// previewre megyunk, eloszor save
			$this->goToPreview();			// aztan irany a preview
			return parent::handleEvents();
		}


		public function handleEvents() {
			if ($this->isPreview()) {
				// #2 fazis
				// - #1 fazis submittalt
				// - itt nem lehetmar a masodik stageben jarunk valahol (submittel vagy nelkule)
				return $this->handleQuoteRequestPreviewEvent();
			} else {
				// elso fazisban jarunk
				// - vagy frissen kitoltesre varva
				// - vagy previewrol visszakattintva
				return $this->handleQuoteRequestEvent();
			}
			return parent::handleEvents();
		}

		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );

			$this->jm = new JobModel();
			$this->um = new UserModel();
			$this->mum = new MyMemberModel();
			$this->muu = new MyUserURL();
			$this->ulm = new UserLogModel();

			$this->oBotJS = new BotJS( "BotJS" , $this );
			$this->oJobHandler = new JobHandler( "job_handler" , $this );

			$this->offer_contact_name = new QuoteRequestName( "offer_contact_name" , $this );
			$this->offer_contact_email = new QuoteLoginEmail( "offer_contact_email" , $this );
			$this->offer_contact_phone = new QuoteRequestPhone( "offer_contact_phone" , $this );

			$this->offer_services = new JobServices( "offer_services" , $this );
			$this->offer_services->setServiceType( 1 , 3 , 1 );
			$this->offer_services->setAttribute( "class" , "offer_services" );

			$this->offer_quote_deadline = new JobQuoteDeadline( "offer_quote_deadline" , $this );
			$this->offer_specialty = new FrontendSelect( "offer_specialty" , $this );
			$this->offer_specialty->setValue( 2 );

			$this->offer_custom_specialty = new FrontendTextbox( "offer_custom_specialty" , $this );

			$this->offer_deadline = new JobDeadline( "offer_deadline" , $this );
			$this->offer_description = new FrontendTextarea( "offer_description" , $this );
			$this->offer_quality_preference = new JobQualityPreference( "offer_quality_preference" , $this );
			$this->offer_languages = new MultiLangPairSelector( "offer_languages" , $this );


			$this->offer_recipients = new JobRecipients( "offer_recipients" , $this );
			$this->offer_attachments = new JobAttachments( "offer_attachments" , $this );

			$this->offer_submit = new FrontendSubmit( "offer_submit" , $this );
			$this->offer_submit->setButtonBig( true );
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "quotepage_error_Title_not_filled" );
			fo3_add_js_langdef( "quotepage_error_Size_not_filled" );
			fo3_add_js_langdef( "quotepage_error_No_service_filled" );
			fo3_add_js_langdef( "quotepage_error_No_service_unit_filled" );
			fo3_add_js_langdef( "quotepage_error_No_service_size_filled" );
			fo3_add_js_langdef( "quotepage_error_Description_not_filled" );
			fo3_add_js_langdef( "quotepage_error_One_or_more_language_not_defined" );
			fo3_add_js_langdef( "quotepage_error_Contact_name_not_filled" );
			fo3_add_js_langdef( "quotepage_error_Contact_email_not_filled" );
			fo3_add_js_langdef( "quotepage_error_Contact_phone_not_filled" );
			fo3_add_js_langdef( "quotepage_error_No_custom_recipient" );
		}
		
		protected function generateEmptyValidator() {
			return "if (\$(this).attr(\"value\").length)
				\$(this).removeClass( \"invalid\" );
			else
				\$(this).addClass( \"invalid\" );";
		}

		protected function addEmptyValidator( $widget ) {
			FNTHPage::addUniquePageFullInit(
				sprintf( "\$(\"#%s\").change( function() { %s } );",
					$widget->getId(),$this->generateEmptyValidator() ) );
		}

		protected function renderForm() {
			if (!strlen( trim( $this->offer_contact_name->getValue() ) ) )
				$this->offer_contact_name->setAttribute( "class" , "FrontendTextbox invalid" );
			$this->addEmptyValidator( $this->offer_contact_name );
			
			if (!strlen( trim( $this->offer_contact_email->getValue() ) ) )
				$this->offer_contact_email->setAttribute( "class" , "FrontendTextbox invalid" );
			$this->addEmptyValidator( $this->offer_contact_email );

			if (!strlen( trim( $this->offer_contact_phone->getValue() ) ) )
				$this->offer_contact_phone->setAttribute( "class" , "FrontendTextbox invalid" );
			$this->addEmptyValidator( $this->offer_contact_phone );

			$this->offer_quote_deadline->setAttribute( "class" , "FrontendTextbox" );
			$this->addEmptyValidator( $this->offer_quote_deadline );

			$specm = new SpecialtiesModel();
			$this->offer_specialty->setOptions( $specm->getSpecialtyOptions( false , true ) );

			$this->offer_deadline->setAttribute( "class" , "FrontendTextbox" );
			$this->addEmptyValidator( $this->offer_deadline );

			if (!strlen( trim( $this->offer_description->getValue() ) ) )
				$this->offer_description->setAttribute( "class" , "FrontendTextarea invalid" );
			$this->offer_description->setAttribute( "rows" , 4 );
			$this->offer_description->setAttribute( "cols" , 44 );
			$this->addEmptyValidator( $this->offer_description );

			// now params
			$myuser = new MyUserModel();
			if ($this->bLoggedIn) {
				$user = new UserModel();
				$userdata = $user->getUserFromUserId( $myuser->getLoggedinUserId() );
				$this->offer_contact_email->setValue( $userdata["email"] );
			} else {

			}

		}

		protected function renderPreview() {
			$rqu = new RequestQuoteURL();
			$this->setParam( "url_back" , $rqu->renderURL() );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->setParam( "url_quote_request_terms_and_conditions",
				ArticleURL::renderURLFromArticleName( "sys_quote_request_terms_and_conditions" ) );
			$this->generateLangDefs();
			FNTHPage::addUniquePageFullInit( sprintf( "InitQuotePane('%s');\n",$this->getId() ) );

			if ($this->offer_specialty->getValue()>0)
				$this->offer_custom_specialty->setAttribute( "class" , "FrontendTextbox invis" );

			$myuser = new MyUserModel();
			$this->bLoggedIn = $myuser->isUserLoggedin();
			$this->setParam( "bLoggedIn" , $this->bLoggedIn );

			$this->bAwaitingConfirmation = $this->isAwaitingConfirmation();
			$this->setParam( "bAwaitingConfirmation" , $this->bAwaitingConfirmation );

			if ($this->bAwaitingConfirmation) {

			} else {
				$this->bPreview = $this->isPreview();
				$this->setParam( "bPreview" , $this->bPreview );

				if ($this->bPreview) {
					$this->offer_attachments->setReadOnly( true );
					$this->renderPreview();
				} else {
					$this->renderForm();
				}
			}
			return parent::render();
		}
		
	}
?>
