<?php
/*
Plugin Name: FanBridge toolbox
Plugin URI: http://www.fanbridge.com/?src=wordpress_plugin_settings
Description: The FanBridge Toolbox plugin allows you to setup an email signup form to collect emails on your FanBridge account, an events widget to show your upcoming events and a fan question widget to allow your subscribers to ask you questions directly from within your Wordpress.
Version: 0.3.3
Author: FanBridge Inc.
Author URI: http://www.fanbridge.com/?src=wordpress_plugin_settings
License: GPLv2 or later.
*/

// constants
require_once dirname(__FILE__) . "/fanbridge-toolbox.constants.php";

// here goes all widget functions
require_once dirname(__FILE__) . "/fanbridge-toolbox.widget.php";

// fanbridge PHP SDK
if (!class_exists('Fanbridge_Api')) {
	require_once dirname(__FILE__) . "/fanbridge_api/fanbridge_api.php";
}


/**
 * some globals
 * yeah...ugly
 */
$fb_errors = array();

/**
 * Indicates the schema on how should we call the jsonp service
 * 
 * @param void
 * @return string; the string of the schema to use
 */

if (!function_exists('get_schema'))
{
	function get_schema() {
		if (!isset($_SERVER['HTTPS']) || (strtolower($_SERVER['HTTPS']) != 'on'))
		{
			return 'http:';
		}
		return 'https:';
	}
}

function fbridge_toolbox_init () {
	fbridge_toolbox_load_assets();
}
add_action('init', 'fbridge_toolbox_init');


function fbridge_toolbox_register_options_menu(){
	add_options_page('FanBridge toolbox', 'FanBridge toolbox', FBTB_PLUGIN_GRANTS, 'fbridge_toolbox_settings', 'fbridge_toolbox_admin_settings');  
}
add_action('admin_menu', 'fbridge_toolbox_register_options_menu');


function fbridge_toolbox_first_req_handler() {

	$method = strtolower($_SERVER["REQUEST_METHOD"]);
	$action = isset($_REQUEST['_fbridge_tb_action']) ? $_REQUEST['_fbridge_tb_action'] : null;

	switch ($action) {
		
		case 'toolbox-css':
			header("Content-type: text/css");

			if (get_option(FBTB_PREFIX . FBTB_SN_CUSTOM_COLORS) == 'on') {
					fbridge_tb_custom_css(get_option(FBTB_PREFIX . FBTB_SN_HIGHLIGHT_COLOR, '#CCCCCC'));
				}
				else {
					fbridge_tb_inherit_css();
				}
				
				exit;
		break;

		case 'save-settings':
			fbridge_tb_save_settings();
		
		break;

		case 'fq-widget-save-settings':
			fbridge_tb_widget_save_settings('fan_questions');
		break;

		case 'events-widget-save-settings':
			fbridge_tb_widget_save_settings('events');
		break;

		case 'connect':
			if (!isset($_GET['fbridge_secret'])) {
				die('Missing secret parameter');
			}

			try
			{

				$secret = $_GET['fbridge_secret'];

				$token = retrieve_api_token($secret);

				if (strlen($token)) 
				{ 

					$fanbridge_api = new Fanbridge_Api(array( 
			    			'secret' => $secret, 
			    			'token' => $token));
					$me = $fanbridge_api->call('account/me');

					$me = json_decode($me, true);
					// save the data
					update_option(FBTB_PREFIX . FBTB_SN_API_SECRET, $secret);
					update_option(FBTB_PREFIX . FBTB_SN_API_TOKEN, $token);
					update_option(FBTB_PREFIX . FBTB_SN_API_USER_ID, $me["id"]);
				} 
				else {

				}
				// we are in some popup window
				// so we reload the parent and close us.			
				die("<script>window.opener.location.reload(); window.close(); </script>");
			}
			catch (Exception $e) {
				throw new Exception("Error connecting to FanBridge API");
			}

		break;

		case 'disconnect':
			delete_option(FBTB_PREFIX . FBTB_SN_API_SECRET);
			delete_option(FBTB_PREFIX . FBTB_SN_API_TOKEN);
			delete_option(FBTB_PREFIX . FBTB_SN_API_USER_ID);
			delete_option(FBTB_PREFIX . FBTB_SN_GROUP);
			die("<script>window.location.replace('options-general.php?page=fbridge_toolbox_settings');</script>");
		break;
	}
	
}
add_action('init', 'fbridge_toolbox_first_req_handler');
wp_enqueue_style('fanbridge_toolbox_main_css', home_url('?_fbridge_tb_action=toolbox-css&cb=' . FBTB_PLUGIN_VERSION));


function fbridge_toolbox_load_assets() {
		wp_enqueue_script('jquery.validate', FBTB_PLUGIN_URL . 'js/jquery.validate.min.js', array('jquery'), FBTB_PLUGIN_VERSION);
		wp_enqueue_script('jquery-ui-tabs');
		wp_enqueue_script('css_browser_selector', FBTB_PLUGIN_URL . 'js/css_browser_selector.js', false, FBTB_PLUGIN_VERSION);
}

function fbridge_toolbox_action_links($links) {
	$settings_page = add_query_arg(array('page' => 'fbridge_toolbox_settings'), admin_url('options-general.php'));
	$settings_link = '<a href="'.esc_url($settings_page).'">Settings</a>';
	array_unshift($links, $settings_link);
	return $links;
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'fbridge_toolbox_action_links', 10, 1);


/**
 * registers the plugin to the blog
 *
 * @param void
 * @return void
 */
function fbridge_toolbox_register_widget() {
	register_widget('FanBridge_ToolBox_Widget_SignUp');
	register_widget('FanBridge_ToolBox_Widget_FanQuestions');
	register_widget('FanBridge_ToolBox_Widget_Events');
}
add_action('widgets_init', 'fbridge_toolbox_register_widget');




function fbridge_toolbox_admin_head() {
	$out = '';
	$out .= "\n" . '<link type="text/css" rel="stylesheet" href="' . FBTB_PLUGIN_URL . "css/admin.css?cb=" . FBTB_PLUGIN_VERSION . '">';
	$out .= "\n" . '<link type="text/css" rel="stylesheet" href="' . FBTB_PLUGIN_URL . "css/jquery.miniColors.css?cb=" . FBTB_PLUGIN_VERSION . '">';
	$out .= "\n" . '<script type="text/javascript" src="' . FBTB_PLUGIN_URL . "js/jquery.miniColors.min.js?cb=" . FBTB_PLUGIN_VERSION . '"></script>';
	$out .= "\n" . '<script type="text/javascript" src="' . FBTB_PLUGIN_URL . "js/fanbridge_toolbox.admin.js?cb=" . FBTB_PLUGIN_VERSION . '"></script>';
	$out .= "\n" . '<script type="text/javascript" src="' . FBTB_PLUGIN_URL . "js/panel-interaction.js?cb=" . FBTB_PLUGIN_VERSION . '"></script>';
	$out .= "\n";

	echo $out;
}
add_action('admin_head', 'fbridge_toolbox_admin_head');


function fbridge_toolbox_admin_settings() {
	global $fb_errors;

	?>	
	<div id="fanbridgeTBConfig">
		
		<h1>FanBridge Toolbox Plugin</h1>
		<?php $token = get_option(FBTB_PREFIX . FBTB_SN_API_TOKEN);
		$connected = false;
		if ($token == ''):?>
        	<a href="#" target="_blank" class="fb-connect-account" onclick="FanBridge.toolbox.connect('<?php echo FBTB_API_SCHEMA . FBTB_SITE_URL ?>', '<?php echo FBTB_API_KEY ?>', '<?php echo urlencode(admin_url('?_fbridge_tb_action=connect')) ?>');return false;">Connect Your Account</a>
        <?php else: 
        	$secret = get_option(FBTB_PREFIX . FBTB_SN_API_SECRET);
			$token = get_option(FBTB_PREFIX . FBTB_SN_API_TOKEN);
			$user_id = get_option(FBTB_PREFIX . FBTB_SN_API_USER_ID);
			$selected_groups = get_option(FBTB_PREFIX . FBTB_SN_GROUP);
			$fq_widget_id = get_option(FBTB_PREFIX . FBTB_FQ_WIDGET_ID);
			$events_widget_id = get_option(FBTB_PREFIX . FBTB_EVENTS_WIDGET_ID);

			try{
				$fanbridge_api = new Fanbridge_Api(array( 
    			'secret' => $secret, 
    			'token' => $token));

				$me = $fanbridge_api->call('account/me');
				$me = json_decode($me, true);

				$email_groups = $fanbridge_api->call('email_group/fetch_all');
				$email_groups = json_decode($email_groups, true);

				$current_fq_widgets = $fanbridge_api->call('widget/fetch_all', array('type' => 'fan_questions'));
				$current_fq_widgets = json_decode($current_fq_widgets, true);

				$current_events_widgets = $fanbridge_api->call('widget/fetch_all', array('type' => 'events'));
				$current_events_widgets = json_decode($current_events_widgets, true);
				$connected = true;
				?>
        		<p class="usr_conn">You are connected as: <?php echo $me['firstname'] . ' ' . $me['lastname'] ?></p><a href="<?php echo admin_url('?_fbridge_tb_action=disconnect') ?>" class="fb-connect-account">Disconnect</a>
        	<?php
			} 
			catch (Exception $e) {
				?>
				<a href="#" target="_blank" class="fb-connect-account" onclick="FanBridge.toolbox.connect('<?php echo FBTB_API_SCHEMA . FBTB_SITE_URL ?>', '<?php echo FBTB_API_KEY ?>', '<?php echo urlencode(admin_url('?_fbridge_tb_action=connect')) ?>');return false;">Connect Your Account</a>
				<?php
			}
    	endif;?>

    	<script type="text/javascript">
		    jQuery(document).ready(function($) {
		        $( "#tabs" ).tabs();
		    });
		</script>
        
        <div id="tabs">
        <ul class="tabbed-navigation" id="tabs">
        	<li><a href="#fan-acquisition-options" id="fan-acquisition" <?php echo (($token == '')?'class="active"':'');?>>Fan Acquisition</a></li>
        	<li><a href="#fan-questions-options" id="fan-questions">Fan Questions</a></li>
            <li><a href="#events-options" id="events">Events</a></li>
        </ul>
		
        
        <div class="fan-acquisition-options" id="fan-acquisition-options">
        <?php if ((strlen($token)) && ($connected)):?>
        <form method="post" action="options-general.php?page=fbridge_toolbox_settings#fan-acquisition-options">
        <div class="section">
			<h2 class="basic-title">Basic Settings</h2>
			<?php fbridge_toolbox_admin_show_errors($fb_errors['basic']) ?>	
				<label>Signup Form Title</label>
				<input class="textInput" name="<?php echo FBTB_SN_FORM_TITLE ?>" type="text" value="<?php echo get_option(FBTB_PREFIX . FBTB_SN_FORM_TITLE, 'Join my list'); ?>"/>
		</div>
        <div class="section">
        	<h2 class="appearance-title">Appearance Settings</h2>
            <div class="widget-options">
                <div class="color-options">
                	<h5>Highlight Color</h5>
                    <?php fbridge_toolbox_admin_show_errors($fb_errors['appearance']) ?>
                    <input type="radio" name="<?php echo FBTB_SN_CUSTOM_COLORS ?>" id="<?php echo FBTB_SN_CUSTOM_COLORS ?>-custom"  value="custom" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_CUSTOM_COLORS), 'on'); ?> />
					Custom Color <input size="7" autocomplete="on" maxlength="7" value="<?php echo get_option(FBTB_PREFIX . FBTB_SN_HIGHLIGHT_COLOR, '#CCCCCC'); ?>" name="<?php echo FBTB_SN_HIGHLIGHT_COLOR ?>" type="text" class="color-picker"/>
                    <div class="match-theme"><input type="radio" name="<?php echo FBTB_SN_CUSTOM_COLORS ?>" id="<?php echo FBTB_SN_CUSTOM_COLORS ?>-inherit" value="inherit" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_CUSTOM_COLORS), 'off'); ?> />Or, Match Current Wordpress Theme</div>
                </div>
               </div>
        </div>    
        
		<div class="section">
			<h2 class="data-title">Choose what data you want to collect</h2>
			<table class="largeTable">
				<tbody>
					<tr>
						<th>Type</th>
						<th>Display?</th>
						<th>Make Required?</th>
					</tr>
					<tr>
						<td>Email</td>
						<td><input checked="checked" disabled="disabled" type="checkbox" name="email">&nbsp;yes</td>
						<td><input checked="checked" disabled="disabled" type="checkbox">&nbsp;yes</td>
					</tr>
					<tr>
						<td>First Name</td>
						<td><input id="<?php echo FBTB_SN_FIRST_NAME ?>-show" onchange="javascript:if(jQuery(this).is(':checked')) { jQuery('#<?php echo FBTB_SN_FIRST_NAME ?>-required').attr('disabled', false); } else{ jQuery('#<?php echo FBTB_SN_FIRST_NAME ?>-required').attr('disabled', true); jQuery('#<?php echo FBTB_SN_FIRST_NAME ?>-required').attr('checked', false); }" name="<?php echo FBTB_SN_FIRST_NAME ?>_show" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_FIRST_NAME . '_show'), 'on'); ?>/>&nbsp;yes</td>
						<td><input id="<?php echo FBTB_SN_FIRST_NAME ?>-required" name="<?php echo FBTB_SN_FIRST_NAME ?>_required" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_FIRST_NAME . '_required'), 'on'); ?>/>&nbsp;yes</td>
					</tr>
					<tr>
						<td>Last Name</td>
						<td><input id="<?php echo FBTB_SN_LAST_NAME ?>-show" onchange="javascript:if(jQuery(this).is(':checked')) { jQuery('#<?php echo FBTB_SN_LAST_NAME ?>-required').attr('disabled', false); } else{ jQuery('#<?php echo FBTB_SN_LAST_NAME ?>-required').attr('disabled', true); jQuery('#<?php echo FBTB_SN_LAST_NAME ?>-required').attr('checked', false); }" name="<?php echo FBTB_SN_LAST_NAME ?>_show" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_LAST_NAME . '_show'), 'on'); ?>/>&nbsp;yes</td>
						<td><input id="<?php echo FBTB_SN_LAST_NAME ?>-required" name="<?php echo FBTB_SN_LAST_NAME ?>_required" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_LAST_NAME . '_required'), 'on'); ?>/>&nbsp;yes</td>
					</tr>
					<tr>
						<td>Zip Code</td>
						<td><input id="<?php echo FBTB_SN_ZIP_CODE ?>-show" onchange="javascript:if(jQuery(this).is(':checked')) { jQuery('#<?php echo FBTB_SN_ZIP_CODE ?>-required').attr('disabled', false); } else{ jQuery('#<?php echo FBTB_SN_ZIP_CODE ?>-required').attr('disabled', true); jQuery('#<?php echo FBTB_SN_ZIP_CODE ?>-required').attr('checked', false); }" name="<?php echo FBTB_SN_ZIP_CODE ?>_show" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_ZIP_CODE . '_show'), 'on'); ?>/>&nbsp;yes</td>
						<td><input id="<?php echo FBTB_SN_ZIP_CODE ?>-required" name="<?php echo FBTB_SN_ZIP_CODE ?>_required" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_ZIP_CODE . '_required'), 'on'); ?>/>&nbsp;yes</td>
					</tr>
					<tr>
						<td>City</td>
						<td><input id="<?php echo FBTB_SN_CITY ?>-show" onchange="javascript:if(jQuery(this).is(':checked')) { jQuery('#<?php echo FBTB_SN_CITY ?>-required').attr('disabled', false); } else{ jQuery('#<?php echo FBTB_SN_CITY ?>-required').attr('disabled', true); jQuery('#<?php echo FBTB_SN_CITY ?>-required').attr('checked', false); }" name="<?php echo FBTB_SN_CITY ?>_show" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_CITY . '_show'), 'on'); ?>/>&nbsp;yes</td>
						<td><input id="<?php echo FBTB_SN_CITY ?>-required" name="<?php echo FBTB_SN_CITY ?>_required" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_CITY . '_required'), 'on'); ?>/>&nbsp;yes</td>
					</tr>
					<tr>
						<td>State/Region</td>
						<td><input id="<?php echo FBTB_SN_STATE ?>-show" onchange="javascript:if(jQuery(this).is(':checked')) { jQuery('#<?php echo FBTB_SN_STATE ?>-required').attr('disabled', false); } else{ jQuery('#<?php echo FBTB_SN_STATE ?>-required').attr('disabled', true); jQuery('#<?php echo FBTB_SN_STATE ?>-required').attr('checked', false); }" name="<?php echo FBTB_SN_STATE ?>_show" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_STATE . '_show'), 'on'); ?>/>&nbsp;yes</td>
						<td><input id="<?php echo FBTB_SN_STATE ?>-required" name="<?php echo FBTB_SN_STATE ?>_required" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_STATE . '_required'), 'on'); ?>/>&nbsp;yes</td>
					</tr>
					<tr>
						<td>Country</td>
						<td><input id="<?php echo FBTB_SN_COUNTRY ?>-show" onchange="javascript:if(jQuery(this).is(':checked')) { jQuery('#<?php echo FBTB_SN_COUNTRY ?>-required').attr('disabled', false); } else{ jQuery('#<?php echo FBTB_SN_COUNTRY ?>-required').attr('disabled', true); jQuery('#<?php echo FBTB_SN_COUNTRY ?>-required').attr('checked', false); }" name="<?php echo FBTB_SN_COUNTRY ?>_show" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_COUNTRY . '_show'), 'on'); ?>/>&nbsp;yes</td>
						<td><input id="<?php echo FBTB_SN_COUNTRY ?>-required" name="<?php echo FBTB_SN_COUNTRY ?>_required" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_COUNTRY . '_required'), 'on'); ?>/>&nbsp;yes</td>
					</tr>
					<tr>
						<td>Birthdate</td>
						<td><input id="<?php echo FBTB_SN_BIRTHDATE ?>-show" onchange="javascript:if(jQuery(this).is(':checked')) { jQuery('#<?php echo FBTB_SN_BIRTHDATE ?>-required').attr('disabled', false); } else{ jQuery('#<?php echo FBTB_SN_BIRTHDATE ?>-required').attr('disabled', true); jQuery('#<?php echo FBTB_SN_BIRTHDATE ?>-required').attr('checked', false); }" name="<?php echo FBTB_SN_BIRTHDATE ?>_show" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_BIRTHDATE . '_show'), 'on'); ?>/>&nbsp;yes</td>
						<td><input id="<?php echo FBTB_SN_BIRTHDATE ?>-required" name="<?php echo FBTB_SN_BIRTHDATE ?>_required" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_BIRTHDATE . '_required'), 'on'); ?>/>&nbsp;yes</td>
					</tr>
				</tbody>	
			</table>
		</div>
		<?php if(!empty($email_groups)):?>
	 		<div class="section">
				<h2>Choose which groups you want to display?</h2>
				<table class="largeTable">
					<tbody>
						<tr>
							<th>Group Name</th>
							<th>Group Description</th>
							<th>Display?</th>
						</tr>
						<?php foreach ($email_groups as $group):
							if((!$group["default"])&&($group["public"])):?>
								<tr>
									<td><?php echo $group["name"];?></td>
									<td><?php echo $group["description"];?></td>
									<td><input type="checkbox" name="<?php echo FBTB_SN_GROUP?>[<?php echo $group["id"].'_'.$group["name"];?>]" id="<?php echo FBTB_SN_GROUP;?>_<?php echo $group["id"];?>" <?php echo ((($selected_groups) && (isset($selected_groups[$group["id"]])))?"checked='checked'":"");?> />&nbsp;yes</td>
								</tr>
						<?php endif;
						endforeach;?>
					</tbody>
				</table>
			</div>
		<?php endif;?>

		<div class="section">
			<h2 class="additional-title">Additional Settings</h2>
			<table>
				<tbody>
					<tr>
						<td><input name="<?php echo FBTB_SN_GEOIP ?>" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_GEOIP), 'on'); ?>/></td>
						<td>Guess Geolocation <i>(This will autofill the form with a fan's <a target="_blank" href="http://en.wikipedia.org/wiki/Geolocation">location based on IP</a>)</i></td>
					</tr>
					<tr>
						<td><input name="<?php echo FBTB_SN_COPPA_COMPLIANT ?>" id="<?php echo FBTB_SN_COPPA_COMPLIANT ?>" type="checkbox" <?php checked(get_option(FBTB_PREFIX . FBTB_SN_COPPA_COMPLIANT), 'on'); ?>/></td>
						<td>COPPA Compliant</i></td>
					</tr>	
				</tbody>
			</table>
		</div>
		<input class="configButton" name="_submit" value="Save settings" type="submit">
		<input name="_fbridge_tb_action" value="save-settings" type="hidden"/>
		</form>
			<?php else:?>
			<div class="section">
				Please connect to FanBridge by clicking on Connect your account
			</div>
			<?php endif;?>
        </div>

        <div id="fan-questions-options" class="fan-questions-options">
        	<?php if(strlen($token)):?>
        		<div class="section">
        			<?php if(!empty($current_fq_widgets)): ?>
        			<form method="post" action="options-general.php?page=fbridge_toolbox_settings#fan-questions-options">
	        			<h2 class="data-title">Choose the widget you want to add</h2>
	        			<h4>NOTE: The minimum width of the Fan Questions widget is 320px. Because of this the widget doesn't fit in all Wordpress sidebars.  We recommend using a theme with a larger sidebar or one with a "Flexible Width" design.</h4>
						<table class="largeTable widgetTable" border="1" cellpading="0" cellspacing="0" bordercolor="#CCCCCC">
							<tbody>
								<tr>
									<th></th>
									<th>Width</th>
									<th>Highlight Color</th>
									<th>Theme</th>
									<th>Full Height</th>
									<th>Preview</th>
								</tr>
								<?php
								foreach ($current_fq_widgets as $widget)
								{
									?>
									<tr height="20">
										<td>
											<input type="radio" id="<?php echo FBTB_PREFIX.FBTB_FQ_WIDGET_ID.'_'.$widget['id'];?>" name="<?php echo FBTB_PREFIX.FBTB_FQ_WIDGET_ID;?>" value="<?php echo $widget['id'];?>" <?php echo((($fq_widget_id) && ($fq_widget_id == $widget['id']))?'checked="checked"':"") ?> />
										</td>
										<td>
											<?php echo $widget['settings']['width'].((!strpos($widget['settings']['width'], '%'))?'px':'');?>
										</td>
										<td>
											<div style="width:18px; height:18px;background-color:<?php echo $widget['settings']['highlight_color']; ?>"></div>
										</td>
										<td>
											<?php echo $widget['settings']['theme'];?>
										</td>
										<td>
											<?php echo (($widget['settings']['full_height'])?"yes":"no");?>
										</td>
										<td>
											<a href="<?php echo $widget['url'];?>" target="_blank">Preview</a>
										</td>
									</tr>
									<?php
								}
								?>
							</tbody>
						</table>
						<input class="configButton" name="_submit" value="Select widget" type="submit">
						<input name="_fbridge_tb_action" value="fq-widget-save-settings" type="hidden"/>
					</form>
					<?php else: ?>
						You don't have any Fan Questions widget.<br/><br/>
						Please set them up at <a href="<?php echo get_schema(). '//' . FBTB_SITE_URL;?>/fan_question/widget/?ref=fbridge_toolbox" target="_blank">FanBridge</a> and then refresh this page.
				<?php endif; ?>
        		</div>
        	<?php else:?>
				<div class="section">
					Please connect to FanBridge by clicking on Connect your account
				</div>
			<?php endif;?>
        </div>
        
        <div class="events-options" id="events-options">
        	<?php if(strlen($token)):?>
        	<div class="section">
        		<?php if(!empty($current_events_widgets)): ?>
	        		<form method="post" action="options-general.php?page=fbridge_toolbox_settings#events-options">
		        		<h2 class="data-title">Choose the widget you want to add</h2>
		        		<h4>NOTE: The minimum width of the Event widget is 320px. Because of this the widget doesn't fit in all Wordpress sidebars.  We recommend using a theme with a larger sidebar or one with a "Flexible Width" design.</h4>
						<table class="largeTable widgetTable" border="1" cellpading="0" cellspacing="0" bordercolor="#CCCCCC">
							<tbody>
								<tr>
									<th></th>
									<th>Width</th>
									<th>Highlight Color</th>
									<th>Theme</th>
									<th>Full Height</th>
									<th>Preview</th>
								</tr>
								<?php
								foreach ($current_events_widgets as $widget)
								{
									?>
									<tr height="20">
										<td>
											<input type="radio" id="<?php echo FBTB_PREFIX.FBTB_EVENTS_WIDGET_ID.'_'.$widget['id'];?>" name="<?php echo FBTB_PREFIX.FBTB_EVENTS_WIDGET_ID;?>" value="<?php echo $widget['id'];?>" <?php echo((($events_widget_id) && ($events_widget_id == $widget['id']))?'checked="checked"':"") ?> />
										</td>
										<td>
											<?php echo $widget['settings']['width'].((!strpos($widget['settings']['width'], '%'))?'px':'');?>
										</td>
										<td>
											<div style="width:18px; height:18px;background-color:<?php echo $widget['settings']['highlight_color']; ?>"></div>
										</td>
										<td>
											<?php echo $widget['settings']['theme'];?>
										</td>
										<td>
											<?php echo (($widget['settings']['full_height'])?"yes":"no");?>
										</td>
										<td>
											<a href="<?php echo $widget['url'];?>" target="_blank">Preview</a>
										</td>
									</tr>
									<?php
								}
								?>
							</tbody>
						</table>
						<input class="configButton" name="_submit" value="Select widget" type="submit">
						<input name="_fbridge_tb_action" value="events-widget-save-settings" type="hidden"/>
					</form>
				<?php else: ?>
					You don't have any events widget.<br/><br/>
					Please set them up at <a href="<?php echo get_schema(). '//' . FBTB_SITE_URL;?>/tourdates/widget/?ref=fbridge_toolbox" target="_blank">FanBridge</a> and then refresh this page.
				<?php endif; ?>
        	</div>
	        <?php else:?>
				<div class="section">
					Please connect to FanBridge by clicking on Connect your account
				</div>
			<?php endif;?>
        
        </div>
        </div>
	</div> <!-- End fanbridgeTBConfig -->

	<script type="text/javascript">
			jQuery(document).ready( function() {
				jQuery(".color-picker").miniColors({
 					letterCase: 'uppercase',
 					open: function() {
 						jQuery('#<?php echo FBTB_SN_CUSTOM_COLORS ?>-custom').attr('checked', true);
 					}
 				});

				jQuery.each(['<?php echo FBTB_SN_FIRST_NAME ?>', '<?php echo FBTB_SN_LAST_NAME ?>', '<?php echo FBTB_SN_ZIP_CODE ?>', '<?php echo FBTB_SN_CITY ?>', '<?php echo FBTB_SN_STATE ?>', '<?php echo FBTB_SN_COUNTRY ?>', '<?php echo FBTB_SN_BIRTHDATE ?>'], function(i, value) {
					if (jQuery('#' + value + '-show').is(':checked')) {
							jQuery('#' + value + '-required')
							.attr('disabled', false);
					}
					else {
							jQuery('#' + value + '-required')
							.attr('disabled', true)
							.attr('checked', false);
					}
				});

				var query = location.href.split('#');
				if(query.length > 1)
				{
					switch(query[1])
					{
						case 'fan-questions-options':
							jQuery('#fan-questions').addClass('active');
						break;
						case 'events-options':
							jQuery('#events').addClass('active');
						break;
						default:
							jQuery('#fan-acquisition').addClass('active');
					}
				}
				else
				{
					jQuery('#fan-acquisition').addClass('active');
				}

				jQuery("#<?php echo FBTB_SN_COPPA_COMPLIANT ?>").click(function(){
					var is_checked = jQuery(this).is(':checked');
					if(is_checked)
					{
						jQuery('#<?php echo FBTB_SN_BIRTHDATE ?>-show').attr('checked', 'checked');
						jQuery('#<?php echo FBTB_SN_BIRTHDATE ?>-required').attr('checked', 'checked');
						jQuery('#<?php echo FBTB_SN_BIRTHDATE ?>-required').attr('disabled', false);
					}
				})

				jQuery('#<?php echo FBTB_SN_BIRTHDATE ?>-show, #<?php echo FBTB_SN_BIRTHDATE ?>-required').click(function(){
					if(jQuery("#<?php echo FBTB_SN_COPPA_COMPLIANT ?>").is(':checked'))
					{
						alert("Because you have COPPA Compliance activated, collecting full date of birth is required. To disable this field, you will need to deactivate the COPPA Compliance Setting.");
						return false;
					}
				})
			});				
	</script>
	<?php
}

/**
 * UTILITY FUNCTIONS
 */



/**
 * Display errors in the admin settings forms
 *
 * @param $errors; array of errors to be displayed
 * @return string; the rendered errors ready to be shown
 */
function fbridge_toolbox_admin_show_errors($errors) {
	if (count($errors)) {
		echo '<div id="configError"><ul><li>' . implode('</li><li>', $errors) . '</li></ul></div>';
	}
}

/**
 * Calls the fanbridge API to get required token
 *
 * @param $secret; secret param to retrieve the token
 * @return string $token or NULL otherwise
 */
function retrieve_api_token($secret) {

	$params = array( 
		'secret' => $secret
	);

	$curl_opts = array( 
		CURLOPT_RETURNTRANSFER => true, 
		CURLOPT_URL => FBTB_API_URL . '/v3/auth/request_token', 
		CURLOPT_POSTFIELDS => http_build_query($params, null, '&')); 

	$ch = curl_init(); 
	curl_setopt_array($ch, $curl_opts); 
	$token = curl_exec($ch); 

	// Check the request was successfull 
	$info = curl_getinfo($ch); 
	curl_close($ch);

	if ($info['http_code'] == '200') 
	{ 
		return $token;
	}

	return null;
}

function fbridge_tb_save_settings() {

	$fb_form_title = stripslashes($_POST[FBTB_SN_FORM_TITLE]);
	$fb_form_highlight_color = stripslashes($_POST[FBTB_SN_HIGHLIGHT_COLOR]);

	if (!strlen(trim($fb_form_title))) {
		$fb_errors['basic'][] = 'Invalid form title';
	}
	if (($_POST[FBTB_SN_CUSTOM_COLORS] == 'custom') && (strlen(trim($fb_form_highlight_color)) != 7)) {
		$fb_errors['appearance'][] = 'Invalid highlight color';
	}
	if (!count($fb_errors)) {

		// fields
		update_option(FBTB_PREFIX . FBTB_SN_FIRST_NAME . '_show', $_POST[FBTB_SN_FIRST_NAME . '_show'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_FIRST_NAME . '_required', $_POST[FBTB_SN_FIRST_NAME . '_required'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_LAST_NAME . '_show', $_POST[FBTB_SN_LAST_NAME . '_show'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_LAST_NAME . '_required', $_POST[FBTB_SN_LAST_NAME . '_required'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_ZIP_CODE . '_show', $_POST[FBTB_SN_ZIP_CODE . '_show'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_ZIP_CODE . '_required', $_POST[FBTB_SN_ZIP_CODE . '_required'] == 'on' ? 'on' : 'off');

		update_option(FBTB_PREFIX . FBTB_SN_CITY . '_show', $_POST[FBTB_SN_CITY . '_show'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_CITY . '_required', $_POST[FBTB_SN_CITY . '_required'] == 'on' ? 'on' : 'off');

		update_option(FBTB_PREFIX . FBTB_SN_STATE . '_show', $_POST[FBTB_SN_STATE . '_show'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_STATE . '_required', $_POST[FBTB_SN_STATE . '_required'] == 'on' ? 'on' : 'off');

		update_option(FBTB_PREFIX . FBTB_SN_COUNTRY . '_show', $_POST[FBTB_SN_COUNTRY . '_show'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_COUNTRY . '_required', $_POST[FBTB_SN_COUNTRY . '_required'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_BIRTHDATE . '_show', $_POST[FBTB_SN_BIRTHDATE . '_show'] == 'on' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_BIRTHDATE . '_required', $_POST[FBTB_SN_BIRTHDATE . '_required'] == 'on' ? 'on' : 'off');

		// additional
		update_option(FBTB_PREFIX . FBTB_SN_FORM_TITLE, $fb_form_title);
		update_option(FBTB_PREFIX . FBTB_SN_GEOIP, $_POST[FBTB_SN_GEOIP] == 'on' ? 'on' : 'off');

		// styling
		update_option(FBTB_PREFIX . FBTB_SN_CUSTOM_COLORS, $_POST[FBTB_SN_CUSTOM_COLORS] == 'custom' ? 'on' : 'off');
		update_option(FBTB_PREFIX . FBTB_SN_HIGHLIGHT_COLOR, $fb_form_highlight_color);
		update_option(FBTB_PREFIX . FBTB_SN_COPPA_COMPLIANT, $_POST[FBTB_SN_COPPA_COMPLIANT] == 'on' ? 'on' : 'off');

		$groups_data = array();
		if(isset($_POST[FBTB_SN_GROUP]))
		{
			$groups = $_POST[FBTB_SN_GROUP];
			foreach ($groups as $key => $group)
			{
				list($group_id, $group_name) = explode("_", $key);
				$groups_data[$group_id] = array("name" => $group_name);
			}
		}
		update_option(FBTB_PREFIX . FBTB_SN_GROUP, $groups_data);
	}
	else {
		// we found errors;
	}
}

function fbridge_tb_widget_save_settings($widget_type) {

	if($widget_type == 'fan_questions')
	{
		$input_id = FBTB_PREFIX.FBTB_FQ_WIDGET_ID;
		$widget_data_option_id = FBTB_PREFIX . FBTB_FAN_QUESTIONS;
		$cached_time_option_id = FBTB_PREFIX . FBTB_FAN_QUESTIONS . '_' . FBTB_CACHED_TIME;
	}
	elseif($widget_type == 'events')
	{
		$input_id = FBTB_PREFIX.FBTB_EVENTS_WIDGET_ID;
		$widget_data_option_id = FBTB_PREFIX . FBTB_EVENTS;
		$cached_time_option_id = FBTB_PREFIX . FBTB_EVENTS . '_' . FBTB_CACHED_TIME;
	}
	else
	{
		throw new Exception("Invalid widget type", 1);
		
	}

	if((!isset($_POST[$input_id])) || (!strlen($_POST[$input_id])))
	{
		$fb_error['widget'][] = "Invalid widget id";
	}

	if (!count($fb_errors)) {
		if($widget_type == 'fan_questions')
		{
			$input_id = FBTB_PREFIX.FBTB_FQ_WIDGET_ID;
			$widget_data_option_id = FBTB_PREFIX . FBTB_FAN_QUESTIONS;
		}
		elseif($widget_type == 'events')
		{
			$input_id = FBTB_PREFIX.FBTB_EVENTS_WIDGET_ID;
			$widget_data_option_id = FBTB_PREFIX . FBTB_EVENTS;
		}


		$widget_id = $_POST[$input_id];
		$secret = get_option(FBTB_PREFIX . FBTB_SN_API_SECRET);
		$token = get_option(FBTB_PREFIX . FBTB_SN_API_TOKEN);

		try{
			$fanbridge_api = new Fanbridge_Api(array( 
    		'secret' => $secret, 
    		'token' => $token));

			$widget_data = $fanbridge_api->call('widget/fetch', array('id' => $widget_id));
			$widget_data = json_decode($widget_data, true);
		}
		catch(Exception $e){
			throw new Exception('Error connection to FanBridge API');
		}

		// widget id
		update_option($input_id, $widget_id);
		update_option($widget_data_option_id, $widget_data);
		update_option($cached_time_option_id, time());

	}
	else {
		// we found errors;
	}
}

// Gabriel Sosa and Magali Ickowicz for FanBridge Inc.
// @pendexgabo
// @maguitai
// 2014