<?php
/**
 * obInstagramFeed module
 * @version 1.0
 * @author Phong Lo <phonglq@foobla.com>
 * @link http://foobla.com
 * @Copyright (C) 2013 foobla.com. All Rights Reserved.
 * @license GNU General Public License version 2, see http://www.gnu.org/licenses/gpl-2.0.html
 */
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.html.parameter' );
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
$ds = DIRECTORY_SEPARATOR;

class JFormFieldIUsers extends JFormFieldList {
	protected $type 	= 'IUsers';
	protected $config 	= null;

	protected function getInput() {
		$app 			= JFactory::getApplication();
		$mod_id 		= $app->input->get('id');

		$redirect_url 	= JUri::root().'index.php?option=com_ajax&module=obinstagramfeed&method=getCode&format=raw';
		
		$redirect_uri 	= urlencode( $redirect_url );
		$form_control 	= $this->formControl;
		$field_id 		= $this->id;
		$juri_root 		= JUri::root();
		$script 		= <<<MIT
			jQuery(document).ready(function(){
				jQuery('#{$field_id}_chzn .chzn-search input').keyup(function(e){
//					console.log(e.which);
//					if(e.which!== 13){
//						return;
//					}
					var key = jQuery(this).val();
					if(key.length <= 2 ){
						return;
					}
					console.log( key );
					jQuery.ajax(
						{
							url: '{$juri_root}index.php?option=com_ajax&module=obinstagramfeed&method=searchUser&format=raw&q=' + key+'&mod_id={$mod_id}',
							dataType: 'json'
						}
					).done( function( data ) {
						jQuery('#{$field_id} option').each(function() {
							if ( jQuery(this).val() != 'self' ) {
								jQuery(this).remove();
							}
						});

						jQuery.each(data, function (i, val) {
							var option = jQuery('<option>');
							option.text(val.username).val(val.id);
							jQuery('#{$field_id}').append(option);
						});

						jQuery('#{$field_id}').trigger('liszt:updated');

					});
				});
				
				jQuery('#{$field_id}').change(function(){
					var opt_text = jQuery('#{$field_id} option[value="'+jQuery(this).val()+'"]').text();
					jQuery('#{$form_control}_params_iusername').val(opt_text);
				});
			});
MIT;
		$doc = JFactory::getDocument();
		$doc->addScriptDeclaration( $script );
		$html = parent::getInput();
		return $html;
	}
	
	public function getOptions(){
		$app = JFactory::getApplication();
		$mod_id = $app->input->get('id');
		$db = JFactory::getDbo();
		$sql = 'SELECT `params` FROM `#__modules` WHERE `id`='.$mod_id;
		$db->setQuery($sql);
		$params_str = $db->loadResult();
		$config = new Joomla\Registry\Registry( $params_str );
		$iusername = $config->get('iusername');
		
		$option = new stdClass();

		$option->value = $this->value;
		$option->text = $iusername;
		$option->disable = null;
		$option->class = null;
		$option->selected = null;
		$option->checked = null;
		$option->onclick = null;
		$option->onchange = null;

		$options = parent::getOptions();
		$options = array_merge($options, array($option));

		return $options;
	}

}
