<?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('text');
$ds = DIRECTORY_SEPARATOR;

class JFormFieldIAccessToken extends JFormFieldText {
	protected $type 	= 'IAccessToken';

	public function getInput(){
		$field_id 	= $this->id;
		$html		= parent::getInput();
		$form_control 	= $this->formControl;
		$btn_check_text = JText::_('MOD_OBINSTAGRAMFEED_CHECK');
		$url_check		= JUri::root().'index.php?option=com_ajax&module=obinstagramfeed&method=getUserInfor&format=raw';
		$html_check = <<<MIT
			<div>
				<a href="javascript:obInstagramFeedCheckAccessToken();" class="btn btn-small">{$btn_check_text}</a>
				<div id="{$field_id}_message"></div>
			</div>
MIT;
		
		$script = <<<MIT
			function obInstagramFeedCheckAccessToken(){
				var at = jQuery('#{$field_id}').val();
//				jQuery.post("{$url_check}", {tk: at}, function(result){
//					jQuery("#{$field_id}_message").html(result);
//				});
				
				jQuery.ajax(
					{
						url: '$url_check',
						dataType: 'json',
						data:{tk: at}
					}
				).done( function( data ) {
					if(data.length<0){
						jQuery('#{$field_id}_message').html('Invalid Access Token');
					}
					
					jQuery('#{$form_control}_params_iuserid 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('#{$form_control}_params_iuserid').append(option);
						jQuery('#{$form_control}_params_iuserid').val(val.id)
						jQuery('#{$form_control}_params_iusername').val(val.username)
					});

					jQuery('#{$form_control}_params_iuserid').trigger('liszt:updated');
					jQuery('#{$field_id}_message').html('Valid Access Token');
				});
			}
MIT;
		$doc = JFactory::getDocument();
		$doc->addScriptDeclaration( $script );
		
		return $html.$html_check;
	}

}
