<?php
/**
 * @file
 * Spider Calendar module for Drupal 7.
 *
 * Written by Webdorado team.
 */

/**
 * Implements hook_help().
 */
function spider_calendar_help($path, $arg) {
  switch ($path) {
    case "admin/help#spider_calendar":
      $output = '';
      $output .= '<h3>' . t("Spider Calendar module help.") . '</h3>';
      $output .= t("Download 'jscolor' library form !url_jscolor and extract it to 'sites/all/libraries/jscolor' directory.<br /><br />
      To show HTML editor in <strong>Administer > Spider Calendar > Calendars > Manage event > HTML</strong> field download 'tinymce' library from !url_html_tiny and extract it to 'sites/all/libraries/tinymce directory'.<br /><br />
      <h4><strong>Step 1: <a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-2.html'>Creating/Editing Calendars.</a></strong></h4>
      <p>
        <strong>1.1 </strong>From the <strong>Navigation</strong> menu on the top click on <strong>Spider Calendar</strong>.
      </p>
      <p>
        <strong>1.2 </strong>Click on <strong>New</strong> on the upper left hand of the pop-up window..
      </p>
      <p>
        <strong>1.3 Title.</strong> Add a title for the calendar.
      </p>
      <p>
        <strong>1.4 Published.</strong> Choose whether to publish the calendar or not.
      </p>
      <p>
        <strong>1.5 </strong>Click on the <strong>Save</strong> button to save the created calendar.
      </p>
      <div style='text-align:right;'><a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-2.html'>More</a></div>
      <h4><strong>Step 2: <a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-3.html'>Creating/Editing Events.</a></strong></h4>
      <p>
        <strong>2.1 </strong>From the <strong>Navigation</strong> menu on the top click on <strong>Spider Calendar</strong>.
      </p>
      <p>
        <strong>2.2 </strong>Locate the calendar for which you want to create/edit events and click on the corresponding <strong>Manage Events</strong> link.
      </p>
      <p>
        <strong>2.3 </strong>Click <strong>New</strong> on the upper left hand of the window.
      </p>
      <p>
        <strong>2.4 Title.</strong> Specify a title for the event.
      </p>
      <p>
        <strong>2.5 Date.</strong> Select the event date.
      </p>
      <p>
        <strong>2.6 Time.</strong> Specify the starting and ending times of the event (Optional).
      </p>
      <p>
        <strong>2.7 Note.</strong> Here you can add a description for the event.
      </p>
      <p>
        <strong>2.8 Published.</strong> Choose whether to publish the event or not.
      </p>
      <p>
        <strong>2.9 Repeat Event.</strong> Select a repeat mode for the event.
        <ul>
          <li><strong>Don't repeat this event.</strong></li>
          <li><strong>Repeat daily.</strong> Choose a periodicity for repeating the event (e.g. every 7 days).</li>
          <li><strong>Repeat weekly.</strong> Choose a periodicity for repeating the event (e.g. every 2 weeks) and the day of the week.</li>
          <li><strong>Repeat monthly.</strong> Choose a periodicity for repeating the event (e.g. every 3 months) and the day of the month.</li>
          <li><strong>Repeat yearly.</strong> Choose a periodicity for repeating the event (e.g. every 2 years), the month of the year, and the day of the month.</li>
          <li><strong>Repeat until.</strong> Choose the end date for repeating the event.</li>
        </ul>
      </p>
      <p>
        <strong>2.10 </strong>Click on the <strong>Save</strong> button to save the created event.
      </p>
      <div style='text-align:right;'><a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-3.html'>More</a></div>
      <h4><strong>Step 3: <a target='_blank' href='http://web-dorado.com/4-creatingediting-calendar-themes/drupal-event-calendar-guide-step-4-1.html'>Creating/Editing Calendar Themes.</a></strong></h4>
      <p>
        <strong>3.1 </strong>From the <strong>Navigation</strong> menu on the top click on <strong>Spider Calendar</strong> and select the <strong>Calendar Themes</strong> tab. You can fill all the parameters or inherit the parameters of the theme from default themes. There are 11 default themes. You can use one of the default themes or create a new one. If you change the parameters of the default theme there is a big <strong>Reset Theme</strong> button for resetting default themes parameters to original.
      </p>
      <p>
        <strong>3.2 </strong>Click on the <strong>New</strong> link on the upper left hand of the window.
      </p>
      <p>
        <strong>3.3 Inherit from theme.</strong> You can choose to inherit the parameters from one of the default themes.
      </p>
      <div style='text-align:right;'><a target='_blank' href='http://web-dorado.com/4-creatingediting-calendar-themes/drupal-event-calendar-guide-step-4-1.html'>More</a></div>
      <h4><strong>Step 4: <a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-5.html'>Publishing the Calendar.</a></strong></h4>
       <p>
        <strong>4.1 </strong>Click on <strong>Add content</strong> on the upper left hand of the screen and choose <strong>Spider Calendar</strong>.
      </p>
      <p>
        <strong>4.2 Title.</strong> Choose a header title for the calendar.
      </p>
      <p>
        <strong>4.3 Select Calendar.</strong> Select the calendar you want to publish.
      </p>
      <p>
        <strong>4.4 Select Theme.</strong> Choose a theme for the calendar.
      </p>
      <p>
        <strong>4.5 </strong>Click on the <strong>Save</strong> button.
      </p>
      <div style='text-align:right;'><a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-5.html'>More</a></div>
      <h4><strong>Step 5: <a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-6.html'>Publishing the Calendar in a Block.</a></strong></h4>
       <p>
        <strong>5.1 </strong>From the navigation menu on the top select <strong>Spider Calendar</strong>.
      </p>
      <p>
        <strong>5.2 Number of Calendar Blocks.</strong> Specify the number of calendar blocks you want to publish and click <strong>Save Blocks Number.</strong>
      </p>
      <p>
        <strong>5.3 </strong>From the navigation menu on the top select <strong>Structure</strong> and choose <strong>Blocks</strong>.
      </p>
      <p>
        <strong>5.4 </strong>Locate the <strong>Spider Calendar</strong> blocks in the list and configure the blocks using <strong>the Configure</strong> link (Operations column).
      </p>
      <p>
        <strong>5.5 </strong>Click on the <strong>Save</strong> button.
      </p>
      <div style='text-align:right;'><a target='_blank' href='http://web-dorado.com/drupal-event-calendar-guide-step-6.html'>More</a></div>
      ", array(
        '!url_jscolor' => l(t('http://jscolor.com/release/jscolor-1.4.0.zip'), 'http://jscolor.com/release/jscolor-1.4.0.zip'),
        '!url_html_tiny' => l(t('http://github.com/downloads/tinymce/tinymce/tinymce_3.5.7.zip'), 'http://github.com/downloads/tinymce/tinymce/tinymce_3.5.7.zip'),
      )) . '</p>';
      return $output;
  }
}

/**
 * Implements hook_permission().
 */
function spider_calendar_permission() {
  return array(
    'access Spider Calendar administration' => array(
      'title' => t('Administer Spider Calendar module.'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function spider_calendar_menu() {
  $items = array();
  $items['admin/settings/spider_calendar'] = array(
    'title' => 'Spider calendar',
    'description' => 'Spider calendar module allow to create calendars with own events.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_calendars'),
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_calendars.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/settings/spider_calendar/Calendars'] = array(
    'title' => 'Calendars',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_calendars'),
    'access arguments' => array('access Spider Calendar administration'),
    'weight' => 1,
    'file' => 'includes/spider_calendar_calendars.inc',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );
  $items['admin/settings/spider_calendar/Calendars/add'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_add_calendar'),
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_calendars.inc',
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/spider_calendar/Calendars/edit'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_edit_calendar'),
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_calendars.inc',
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/spider_calendar/Calendars/events'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_manage_events'),
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_manage_events.inc',
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/spider_calendar/Calendars/events/add'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_add_events'),
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_manage_events.inc',
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/spider_calendar/Calendar Themes'] = array(
    'title' => 'Calendar Themes',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_cal_theme'),
    'access arguments' => array('access Spider Calendar administration'),
    'weight' => 2,
    'file' => 'includes/spider_calendar_cal_theme.inc',
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );
  $items['admin/settings/spider_calendar/Calendar Themes/add'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_add_theme'),
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_cal_theme.inc',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/settings/spider_calendar/Calendar Themes/add/preview_popup'] = array(
    'page callback' => 'spider_calendar_theme_preview',
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_cal_theme_preview.inc',
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/spider_calendar/Block Calendar Themes'] = array(
    'title' => 'Block Calendar Themes',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_block_cal_theme'),
    'access arguments' => array('access Spider Calendar administration'),
    'weight' => 3,
    'file' => 'includes/spider_calendar_block_cal_theme.inc',
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );
  $items['admin/settings/spider_calendar/Block Calendar Themes/add'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_add_block_theme'),
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_block_cal_theme.inc',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/settings/spider_calendar/Block Calendar Themes/add/preview_popup'] = array(
    'page callback' => 'spider_calendar_block_theme_preview',
    'access arguments' => array('access Spider Calendar administration'),
    'file' => 'includes/spider_calendar_block_cal_theme_preview.inc',
    'type' => MENU_CALLBACK,
  );
  $items['see_more'] = array(
    'page callback' => 'spider_calendar_see_more',
    'access callback' => TRUE,
    'file' => 'includes/spider_calendar_see_more.inc',
    'type' => MENU_CALLBACK,
  );
  $items['spider_calendar_block'] = array(
    'page callback' => 'spider_calendar_block_view',
    'page arguments' => array(3),
    'access callback' => TRUE,
    'file' => 'includes/spider_calendar_block_view.inc',
    'type' => MENU_CALLBACK,
  );
  $items['spider_calendar_block_events'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('spider_calendar_block_events_view'),
    'access callback' => TRUE,
    'file' => 'includes/spider_calendar_block_events_view.inc',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Function spider_calendar_variable_get().
 */
function spider_calendar_variable_get($variable) {
  switch ($variable) {
    case 'spider_calendar_allowed_tags':
      $result = variable_get('spider_calendar_allowed_tags', array(
        'a',
        'em',
        'strong',
        'code',
        'img',
      ));
      break;

    case 'spider_calendar_node_types':
      $result = variable_get('spider_calendar_node_types', array('spider_calendar'));
      break;

    case 'spider_calendar_node_types_primary':
      $result = variable_get('spider_calendar_node_types_primary', array('spider_calendar'));
      break;
  }
  return $result;
}

/**
 * Implements hook_node_info().
 */
function spider_calendar_node_info() {
  return array(
    'spider_calendar' => array(
      'name' => t('Spider Calendar'),
      'base' => 'spider_calendar',
      'module' => 'spider_calendar',
      'description' => t("Create a new calendar with Spider Calendar module"),
    )
  );
}

/**
 * Implements hook_form().
 */
function spider_calendar_form(&$node, &$form_state) {
  $form = array();
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#default_value' => $node->title,
  );
  if (isset($node->nid)) {
    $cal_row = db_query("SELECT * FROM {spider_calendar_form_table} WHERE  vid=:vid", array(':vid' => $node->nid))->fetchObject();
    $default_value = $cal_row->calendar;
  }
  else {
    $default_value = 0;
  }
  $calendars = spider_calendar_get_calendars_array();
  $form['select_calendars'] = array(
    '#type' => 'select',
    '#title' => t('Select calendar'),
    '#description' => t('Create calendars on !url.', array('!url' => l('admin/settings/spider_calendar/Calendars/add', url('admin/settings/spider_calendar/Calendars/add', array('absolute' => TRUE))))),
    '#default_value' => $default_value,
    '#required' => FALSE,
    '#options' => $calendars,
  );
  $form['select_themes'] = array(
    //'#prefix' => '<div class="messages warning">' . t('Themes are disabled for the non-commercial version.') . '</div>
    //              <a href="http://web-dorado.com/files/fromSpiderCalendarDrupal.php" target="_blank" style="color:red; text-decoration:none; float:right;">
    //                <img src="' . base_path() . drupal_get_path('module', 'spider_calendar') . '/images/header.png" border="0" alt="www.web-dorado.com" width="215"><br />
    //              <div style="float:right;">' . t('Get the full version') . '&nbsp;&nbsp;&nbsp;&nbsp;</div>
    //              </a>',
    '#type' => 'select',
    '#title' => t('Select theme'),
    '#description' => t('Select the calendar theme.'),
    '#required' => FALSE,
    '#disabled' => FALSE,
    '#options' => array('Blue'),
  );
  return system_settings_form($form);
}

/**
 * Implements hook_node_insert().
 */
function spider_calendar_node_insert($node) {
  if ($node->type == 'spider_calendar') {
    $type = 'spider_calendar';
    $title = '';
    $title = $node->select_calendars;
    $theme = 12;
    db_insert('spider_calendar_form_table')->fields(array(
      'vid' => $node->nid,
      'type' => $type,
      'calendar' => $title,
      'theme' => $theme,
    ))->execute();
    db_query("UPDATE {node_revision} SET comment=:comment WHERE nid=:nid", array(':comment' => 0, ':nid' => $node->nid));
  }
}

/**
 * Implements hook_node_update().
 */
function spider_calendar_node_update($node) {
  if ($node->type == 'spider_calendar') {
    $title = '';
    $title = $node->select_calendars;
    $theme = 12;
    db_query("UPDATE {spider_calendar_form_table} SET calendar=:calendar,theme=:theme WHERE vid = :vid", array(':calendar' => $title, ':theme' => $theme, ':vid' => $node->nid));
  }
}

/**
 * Implements hook_node_delete().
 */
function spider_calendar_node_delete($node) {
  db_query("DELETE FROM {spider_calendar_form_table} WHERE vid = :vid", array(':vid' => $node->nid));
}

/**
 * Implements hook_node_view().
 */
function spider_calendar_node_view($node, $view_mode) {
  if (!in_array($node->type, spider_calendar_variable_get('spider_calendar_node_types'))) {
    return;
  }
  $teaser = $view_mode == 'teaser';
  $page = arg(0) == 'node' && arg(1) == $node->nid;
  if (($teaser) || empty($node->uid)) {
    return;
  }
  $select_calendars = db_query("SELECT calendar FROM {spider_calendar_form_table} WHERE vid=:vid", array(':vid' => $node->nid))->fetchField();
  if ($select_calendars == -1 || $select_calendars == 0 || !db_query("SELECT id FROM {spider_calendar_calendar_table} WHERE published=1 and id=:id", array(':id' => $select_calendars))->fetchField()) {
    $error_message = t('The calendar is not chosen. Select calendar !url.', array('!url' => l('here', url('node/' . $node->nid . '/edit', array('absolute' => TRUE)))));
    drupal_set_message($error_message, 'error', FALSE);
    $node_view = '';
  }
  else {
    require_once "includes/spider_calendar_view.inc";
    $cal_theme = db_query("SELECT theme FROM {spider_calendar_form_table} WHERE vid=:vid", array(':vid' => $node->nid))->fetchField();
    $node_view = spider_calendar_content_view($select_calendars, $cal_theme, $node->nid);
  }
  $select_calendars = db_query("SELECT calendar FROM {spider_calendar_form_table} WHERE vid=:vid", array(':vid' => $node->nid))->fetchField();
  $node->content['spider_calendar'] = array(
    '#node' => $node,
    '#teaser' => $teaser,
    '#page' => $page,
    '#markup' => $node_view,
    '#enabled' => TRUE,
    '#weight' => 10,
  );
}

/**
 * Function spider_calendar_get_calendars_array().
 */
function spider_calendar_get_calendars_array() {
  $calendar = array();
  $calendar = db_query("SELECT id,title FROM {spider_calendar_calendar_table} WHERE published=1 ORDER BY title")->fetchAllKeyed();
  $calendar[0] = t('-Select calendar-');
  return $calendar;
}

/**
 * Function spider_calendar_get_calendars_block_theme_array().
 */
function spider_calendar_get_calendars_block_theme_array() {
  $calendar = array();
  $calendar = db_query("SELECT id,title FROM {spider_calendar_block_theme_table} ORDER BY title")->fetchAllKeyed();
  $calendar[0] = t('-Select theme-');
  return $calendar;
}

/**
 * Implements hook_block_info().
 */
function spider_calendar_block_info() {
  $spider_calendar_block_count = db_query("SELECT block_number FROM {spider_calendar_block_number_table} WHERE id=:id", array(':id' => 1))->fetchField();
  for ($i = 0; $i < $spider_calendar_block_count; $i++) {
    $blocks['spider_calendar' . $i] = array(
      'info' => 'School Calendar ' . ($i + 1),
      'cache' => DRUPAL_CACHE_PER_ROLE,
    );
  }
	
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function spider_calendar_block_view($delta) {
  $spider_calendar_block_count = db_query("SELECT block_number FROM {spider_calendar_block_number_table} WHERE id=:id", array(':id' => 1))->fetchField();
  require_once "includes/spider_calendar_block_view.inc";
  $blocks = array();
  
  for ($i = 0; $i < $spider_calendar_block_count; $i++) {
	$selected_calendars_id = variable_get(('spider_calendar_block_select_calendars' . $i), -1);
	$selected_calendars_theme_id = (int)variable_get(('spider_calendar_block_select_themes' . $i), -1);
	//if ($selected_calendars_id != -1 && $selected_calendars_id != 0 && db_query("SELECT id FROM {spider_calendar_calendar_table} WHERE published=:published and id=:id", array(':published' => 1, ':id' => $selected_calendars_id))->fetchField()) {
	  switch ($delta) {
		case 'spider_calendar' . $i:
		  $blocks['subject'] = '';
		  if($i==1)
			$blocks['content'] = spider_calendar_block_show2(0, $selected_calendars_theme_id, $i);
		  else
			$blocks['content'] = spider_calendar_block_show($selected_calendars_id, $selected_calendars_theme_id, $i);
		  break;
		}
	//}
	//else {
	//  switch ($delta) {
	//	case 'spider_calendar' . $i:
	//	  $blocks['subject'] = '';
	//	  $blocks['content'] = '';
	//	  break;
	//	}
	//}
  }

  return $blocks;
}

/**
 * Implements hook_block_configure().
 */
function spider_calendar_block_configure($delta) {
  $spider_calendar_block_count = db_query("SELECT block_number FROM {spider_calendar_block_number_table} WHERE id=:id", array(':id' => 1))->fetchField();
  $calendars = spider_calendar_get_calendars_array();
  $calendars_theme = spider_calendar_get_calendars_block_theme_array();
  for ($i = 0; $i < $spider_calendar_block_count; $i++) {
    if ($delta == 'spider_calendar' . $i) {
      $form['spider_calendar_block_select_calendars' . $i] = array(
        '#type' => 'select',
        '#title' => t('Select calendar'),
        '#description' => t('Select calendar, which you want to see in this block.'),
        '#default_value' => variable_get(('spider_calendar_block_select_calendars' . $i), 0),
        '#required' => FALSE,
        '#options' => $calendars,
      );
      $form['spider_calendar_block_select_themes' . $i] = array(
        //'#prefix' => '<div class="messages warning">' . t('Themes are disabled for the non-commercial version.') . '</div>
        //          <a href="http://web-dorado.com/files/fromSpiderCalendarDrupal.php" target="_blank" style="color:red; text-decoration:none; float:right;">
        //            <img src="' . base_path() . drupal_get_path('module', 'spider_calendar') . '/images/header.png" border="0" alt="www.web-dorado.com" width="215"><br />
        //          <div style="float:right;">' . t('Get the full version') . '&nbsp;&nbsp;&nbsp;&nbsp;</div>
        //          </a>',
        '#type' => 'select',
        '#title' => t('Select theme'),
        '#description' => t('Select the block calendar theme.'),
		'#default_value' => variable_get(('spider_calendar_block_select_themes' . $i), 0),
        '#required' => FALSE,
        '#options' => $calendars_theme,
      );
    }
  }
  
  return $form;
}

/**
 * Implements hook_block_save().
 */
function spider_calendar_block_save($delta, $edit = array()) {
  $spider_calendar_block_count = db_query("SELECT block_number FROM {spider_calendar_block_number_table} WHERE id=:id", array(':id' => 1))->fetchField();
  for ($i = 0; $i < $spider_calendar_block_count; $i++) {
    if ($delta == 'spider_calendar' . $i) {
      variable_set('spider_calendar_block_select_calendars' . $i, $edit['spider_calendar_block_select_calendars' . $i]);
	  variable_set('spider_calendar_block_select_themes' . $i, $edit['spider_calendar_block_select_themes' . $i]);
    }
  }
  
  return;
}

/**
 * Implements hook_library().
 */
function spider_calendar_library() {
  $libraries = array(
    'jscolor' => array(
      'version' => '1.3.9',
      'js' => array('sites/all/libraries/jscolor/jscolor.js' => array(
        'group' => JS_LIBRARY,
        ),
      ),
    ),
    'tinymce' => array(
      'version' => '3.5.7',
      'js' => array('sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js' => array(
        'group' => JS_LIBRARY,
        ),
      ),
    ),
  );
  return $libraries;
}

/**
 * Implements hook_init().
 */
function spider_calendar_init() {
  drupal_add_css(drupal_get_path('module', 'spider_calendar') . '/css/spider_calendar_fieldset.css');
}
