<?php
class ComFoobarTemplateHelperBehavior extends KTemplateHelperBehavior
{
	/*
	 * Array which holds a list of loaded javascript libraries
	 * 
	 * boolean
	 */
	protected $_loaded = array();
	
	/**
	 * Constructor.
	 *
	 * @param 	object 	An optional KConfig object with configuration options
	 */
	public function __construct( KConfig $config = null) 
	{ 
		parent::__construct($config);
	}
	
	/**
	 * Method to repeat an element and its content
	 */
	public function repeat($config = array())
	{
		$config = new KConfig($config);
		$config->append(array(
			'debug' => KDEBUG
		));
		
		
		$html ='';
		
		// Only load once
		if (!isset($this->_loaded['mootools'])) 
		{
			$this->mootools($config);
		}
		
		// Add the script to the page
		$html .= "
		<script>
		var i = 0;
		function repeatElement(id) 
		{
			i++;
			var c = $(id).clone();
			var newid = id+i;
			var regex = new RegExp(id);
			
			c.setAttribute('id', newid);
		
			c.getElements('*').each(function(el) {
			
				var elname = el.getAttribute('name');
				if (elname && elname.match(regex)) {
					name = elname.replace(regex, newid);
					el.setAttribute('name', name);
				}
				
				var elid = el.getAttribute('id');
				if(elid) {
					el.setAttribute('id', elid+i);
				}
				
				var elfor = el.getAttribute('for');
				if(elfor) {
					el.setAttribute('for', elfor+i);
				}
				
				// Adds Joomla calendar behavior to a text input element
				// Requires Behavior Calendar
				if(el.hasClass('showCalendar')) {
					el.addEvent('click', function() {
					this.value = showCalendar(elid+i,'%Y-%m-%d');
					});
				}
			});
		
			// Make the clone visible
			c.removeClass('hidden');
			
			// Make sure the clone is injected after its previous clone
			var clones = $(document.body).getElements('.clone');
			var last = clones[clones.length-1].getAttribute('id');
			if(last) {
				c.inject(last,'after');
			}
			else {
				c.inject(id,'after');
			}
		
			// Append remove function to element with class remove
			c.getElements('.remove').each(function(el) { 
				el.addEvent('click', function() {
					c.remove();
				});
			});
			}
		</script>
		";

		return $html;
	}
}