<?php
/*
 * ARI Smart Content
 *
 * @package		ARI Smart Content
 * @version		1.0.0
 * @author		ARI Soft
 * @copyright	Copyright (c) 2009 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

defined('_JEXEC') or die ('Restricted access');

require_once dirname(__FILE__) . '/../kernel/class.AriKernel.php';

jimport('joomla.html.html');
JFormHelper::loadFieldClass('textarea');

JHtml::_('behavior.modal', 'a.modal');

class JFormFieldSourcetemplate extends JFormFieldTextarea
{
	protected $type = 'Sourcetemplate';
	
	protected function getInput()
	{
		$input = parent::getInput();

		$element = $this->element;
		$sourceId = (string)$element['source'];
		
		$sourceId = $this->formControl . '_' . $this->group . '_' . $sourceId;
		
		$this->registerScripts($this->id);

		return sprintf('<div style="float:left;clear:right;">%1$s<br/><a href="#" onclick="openSourceTemplateEditor(\'%3$s\', \'%2$s\', \'sourceTemplateEditorCallback_%2$s\');return false;">Open in editor</a></div>',
			$input,
			$this->id,
			$sourceId
		);
	}
	
	function registerScripts($id)
	{
		static $loaded = false;
		
		$doc = JFactory::getDocument();
		
		if (!$loaded)
			$doc->addScriptDeclaration(
				sprintf(
					';function openSourceTemplateEditor(ctrlSourceId, ctrlTemplateId, callback) {
						var sourceId = document.getElementById(ctrlSourceId).value;
					
						SqueezeBox.open("index.php?option=com_arismartcontent&view=sourcetemplate&tmpl=component&sourceId=" + sourceId + "&callback=" + callback, {handler:"iframe",size:{width:900,height:350}});
					};'
				)
			);
			
		$doc->addScriptDeclaration(
			sprintf(
				';function sourceTemplateEditorCallback_%1$s(context) {
					var editorManager = context.YAHOO.ARISoft.page.pageManager.editorManager,
						content = document.getElementById("%1$s").value;

					editorManager.setContent(content);
					
					editorManager.applyContentEvent.subscribe(function(event, data) {
						var editorData = data[0];
						
						document.getElementById("%1$s").value = editorData.Content;
	
						SqueezeBox.close();
					});
				};',
				$id
			)
		);
		
		$loaded = true;
	}
}