<?php
	
	//because anon users dont get jquery ui https://drupal.org/node/802432
	function wysiwyg_grammar_checker_init() {
		drupal_add_library('system', 'ui');
	}
	/**
		* Implementation of hook_help().
	*/
	function wysiwyg_grammar_checker_help($path, $arg) {
		if ($path == 'admin/modules#description') {
			return t('Enables the Proofread Bot plugin for TinyMCE.');
		}
	}
	
	
	function wysiwyg_grammar_checker_wysiwyg_editor_settings_alter(&$settings, $context) {
		// Each editor has its own collection of native settings that may be extended
		// or overridden. Please consult the respective official vendor documentation
		// for details.
		global $base_url;
		//dpm($base_url);
		if ($context['profile']->editor == 'tinymce') {
			// Supported values to JSON data types.
			$settings['cleanup_on_startup'] = TRUE;
			$settings['proofread_bot_rpc_url']        = $base_url . "/proofread_bot/check";
			$settings['proofread_bot_ignore_rpc_url'] = $base_url . "/proofread_bot/check";
			$settings['proofread_bot_rpc_id']         = 'drupal';
			//$settings['proofread_bot_theme']          = 'wordpress';
			$settings['proofread_bot_ignore_enable']  = 'true';
			//$settings['proofread_bot_strip_on_get']   = 'true';
			//$settings['proofread_bot_ignore_strings'] = str_replace( '"', '', proofread_bot_get_setting( $user->ID, 'proofread_bot_ignored_phrases' ) );
			//$settings['proofread_bot_show_types']     = proofread_bot_get_setting( $user->ID, 'proofread_bot_options' );
			
		}
	}
	
	
	
	/**
		* Implementation of hook_wysiwyg_plugin().
	*/
	function wysiwyg_grammar_checker_wysiwyg_plugin($editor) {
		$path = drupal_get_path('module', 'wysiwyg_grammar_checker');
		switch ($editor) {
			case 'tinymce':
			return array(
			// SEE http://drupal.org/files/issues/wysiwyg_api_documentation.patch
			'proofread_bot' => array(
            // SEE http://drupal.org/node/767550
            'path' => $path."/plugin/tinymce",
            'filename' => 'editor_plugin.js',
            'buttons' => array('proofread_bot' => t('Proofread Bot')),
            'url' => 'http://proofreadbot.com',
            'load' => TRUE,
			),
			);
			break;
			
			/* case 'ckeditor':
				if (file_exists("$path/plugin.js")) {
				return array(
				'aspell' => array(
				'path' => $path,
				'buttons' => array('SpellCheck' => t('Server Side Spell Check')),
				'url' => 'http://cksource.com/forums/viewtopic.php?p=40830#p40830',
				'load' => TRUE,
				),
				);
				}
			break;*/
		}
	}
	
	//crappy hack to add an additional js file to the plugin...Currently multiple js files are unsupported http://drupal.org/node/1039076#comment-6457758
	function wysiwyg_grammar_checker_preprocess_page(&$vars)
	{
		//If I don't add to every page the site might break, where there is a text field with pbot filter enabled...
		//if( arg(1) == 'add' OR arg(2) == 'edit' )
		//{
			drupal_add_js(drupal_get_path('module', 'wysiwyg_grammar_checker')."/plugin/proofread_bot.core.js");
			drupal_add_css(drupal_get_path('module', 'wysiwyg_grammar_checker')."/plugin/proofread_bot.css");
			
		//}
	}
	
	
	
	/**
		* implementation of hook_permission
	*/
	function wysiwyg_grammar_checker_permission() {
		return array(
		'proofread bot permission' => array(
		'title' => t('Use Proofread Bot'),
		'description' => t('Permission for role to perform Proofread Bot checks.'),
		),
		);
	}
	
	
	/**
		* Implementation of hook_menu
	*/
	function wysiwyg_grammar_checker_menu() {
		$items = array();
		
		$items['admin/config/content/proofread_bot'] = array(
		'title' => 'Proofread Bot Settings',
		'description' => 'Set the various Proofread Bot Settings here',
		'page callback' => 'drupal_get_form',
		'page arguments' => array('wysiwyg_grammar_checker_admin'),
		'access arguments' => array('access administration pages'),
		'type' => MENU_NORMAL_ITEM,
		);
		
		$items['proofread_bot/check/checkDocument'] = array(
		'title' => 'Proofread Bot Check',
		'page callback' => 'wysiwyg_grammar_checker_perform',
        //'page arguments' => array(1,2), // start from 0/1/2/3/etc
		'access arguments' => array("proofread bot permission"),
        'type' => MENU_CALLBACK,      // no link in nav menu
		);
		
		
		return $items;
	}
	
	// ======================================
	// Administration Page:
	// ======================================
	function wysiwyg_grammar_checker_admin() {
		
		/*
			// get fields of type text
			foreach (field_info_fields() as $field)  {
			if ($field["module"] == "text")
			$text_fields[$field["field_name"]] = $field["field_name"];
			}
			//dpm($text_fields);
			
			$form['field'] = array(
			'#type' => 'fieldset',
			'#title' => t('Field Settings'),
			'#description' => t("Select the field which will be enabled for proofreading content."),
			'#weight' => 0,
			'#collapsible' => FALSE,
			'#collapsed' => FALSE,
			);
			$form['field']['proofread_bot_field'] = array(
			'#type' => 'select',
			'#title' => t('Proofread Bot Field'),
			'#default_value' => variable_get('proofread_bot_field', 'body'),
			'#options' => $text_fields,
			'#description' => t("Your Proofread Bot field."),
			'#required' => FALSE,
			);
			$form['field']['proofread_bot_field_location'] = array(
			'#type' => 'select',
			'#title' => t('Proofread Bot Field Location'),
			'#default_value' => variable_get('proofread_bot_field', 'before'),
			'#options' => array("before" => "before", "after" => "after"),
			'#description' => t("Show the Proofread Bot button before or after the text field."),
			'#required' => FALSE,
			);
		*/
		
		$form['account'] = array(
		'#type' => 'fieldset',
		'#title' => t('Account Settings'),
		'#description' => t("Your account details for <a href=\"http://proofreadbot.com\" target=\"_blank\">proofreadbot.com</a>. You can use the service without an account, but your usage is limited to checking one post up to 600 words per day. If you want more get an account <a href=\"http://proofreadbot.com/user\" target=\"_blank\">here</a>."),
		'#weight' => 0,
		'#collapsible' => FALSE,
		'#collapsed' => FALSE,
		);
		$form['account']['proofread_bot_username'] = array(
		'#type' => 'textfield',
		'#title' => t('Proofread Bot Username'),
		'#default_value' => variable_get('proofread_bot_username', ''),
		'#size' => 32,
		'#maxlength' => 128,
		'#description' => t("Your Proofread Bot username."),
		'#required' => FALSE,
		);
		$form['account']['proofread_bot_password'] = array(
		'#type' => 'textfield',
		'#title' => t('Proofread Bot Password'),
		'#default_value' => variable_get('proofread_bot_password', ''),
		'#size' => 32,
		'#maxlength' => 128,
		'#description' => t("Your Proofread Bot password."),
		'#required' => FALSE,
		);
		$form['debug'] = array(
		'#type' => 'fieldset',
		'#title' => t('Debug Settings'),
		'#weight' => 1,
		'#collapsible' => FALSE,
		'#collapsed' => FALSE,
		);
		$form['debug']['proofread_bot_debug'] = array(
		'#type' => 'checkbox',
		'#title' => t('Debug Mode'),
		'#default_value' => variable_get('proofread_bot_debug', FALSE),
		'#description' => t("Check this to write all debug messages to the log."),
		'#required' => FALSE,
		);
		
		return system_settings_form($form);
	}
	
	function wysiwyg_grammar_checker_perform() {
		module_load_include("php", "wysiwyg_grammar_checker", "proofread_bot.api");
		
		if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
		$postText = trim(  file_get_contents( 'php://input' )  );
		
		if (!$postText)
		{
			print "No text received";
			die;
		}
		
		parse_str($postText);
		
		//print ($postText);
		//print $data;
		
		//proofread_bot_debug_message('Received a raw POST submission: '. print_r($_POST,TRUE));
		
		$node = proofread_bot_check_api ($data);
		
		
		header('Content-type:application/xml;charset=utf-8');	
		
		$xml = "<xmldoc>";
		
		if ($node->field_html_report_text)	{
			$xml .="<display>
			<![CDATA[";
			$xml .= preg_replace('/[^(\x20-\x7F)]*?/','', $node->field_html_report_text->und[0]->value);
			$xml .= "]]>
				</display>";
			$xml .= preg_replace('/[^(\x20-\x7F)]*?/','', $node->field_wysiwyg_report_text->und[0]->value);
		}
		else  {
		$xml .= "<message>
<![CDATA[\n"
		.$node."
]]>
		</message>";
		}
		$xml .= "</xmldoc>";
		
		print $xml;
	}