<?php
	FNTH_class( "Widget" );
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/Languages.inc.php" );

	class MultiLangPairSelector extends Widget {
		protected $aLanguages = array( array( "source_language_id" => 0 , "target_language_id" => 0 ) );

		public function __construct( $id = "FrontendTextbox" , $parent = null ) {
			// $this->addMediaDirectory( $GLOBALS["site_root"] , $GLOBALS["site_www"] , "design/rp/","widgets/");
			parent::__construct( $id , $parent );
			// $this->setParam("language",$GLOBALS["language"]);
			$this->setAttribute( "class" , "MultiLang" );
		}

		public function setLanguagePairs( $arr ) { $this->aLanguages = $arr; }

		public function refreshValueFromArray( $arr = null ) {
			if (!isset( $arr )) $arr = $this->aP;
			$sid = sprintf( "%s_srclang_" , $this->getId() );
			$did = sprintf( "%s_dstlang_" , $this->getId() );
			$a = array();
			foreach ($arr as $k => $v) {
				if (strpos($k,$sid)!==false) {
					$id = (int)str_replace( $sid , "" , $k );
					if (!isset( $a[$id] )) $a[$id]=array();
					$a[$id]["source_language_id"]=$v;
				}
				if (strpos($k,$did)!==false) {
					$id = (int)str_replace( $did , "" , $k );
					if (!isset( $a[$id] )) $a[$id]=array();
					$a[$id]["target_language_id"]=$v;
				}
			}
			if (!empty( $a ))
				$this->aLanguages = $a;
		}

		public function getValue() {
			return $this->aLanguages;
		}

		protected function renderLanguageJSArray( $langs = array() ) {
			$l = array();
			foreach ($langs as $k => $v) $l[]=sprintf( "['%s','%s']" , $k , $v );
			return sprintf( "[ %s ]",implode( $l , "," ) );
		}

		protected function renderSelectedLanguages( $arr ) {
			return json_encode( $arr );
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "Delete_languagepair" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$langs = LanguagesModel::getLanguageOptions();
			$this->setParam( "languages" , $langs );
			FNTHPage::setPageFullInit( "multilang_languages_js" ,
				sprintf( "aLangs = %s;",$this->renderLanguageJSArray($langs) ) );
			
			$this->generateLangDefs();	// generate strings for javascript

			FNTHPage::setPageFullInit( "langs_" . $this->getId() . "_js",
				sprintf( "MultiLangPairInit( '%s',%s );",
					$this->getId(),
					$this->renderSelectedLanguages( $this->aLanguages ) ) );
			return parent::render();
		}

	}

?>
