<?php
/**
 * @file
 * Add Playlist.
 */

/**
 * Add playlist form.
 */
function spider_video_player_add_playlist_form() {
  global $user;
  drupal_add_js(drupal_get_path('module', 'spider_video_player') . '/js/spider_video_player_check_all.js');
  drupal_add_js(drupal_get_path('module', 'spider_video_player') . '/js/spider_video_player_open_iframe.js');
  drupal_add_css(drupal_get_path('module', 'spider_video_player') . '/css/spider_video_player_iframe.css');
  $form = array();
  $form['search_playlists_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Search by titles'),
    '#size' => 25,
    '#default_value' => variable_get('spider_video_player_search_add_playlists_name', ''),
  );
  $form['search_playlists'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_search_add_playlists_name'),
    '#value' => t('Go'),
  );
  $form['reset_playlists'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('spider_video_player_reset_add_playlists_name'),
  );
  $ids_col = db_query("SELECT id FROM {spider_video_player_playlist}")->fetchCol();
  drupal_add_js('var data = [];', array('type' => 'inline'));
  foreach ($ids_col as $id) {
    $row = db_query("SELECT * FROM {spider_video_player_playlist} WHERE id=:id", array(':id' => $id))->fetchObject();
    drupal_add_js('
      data[' . $id . '] = [];
      data[' . $id . ']["title"] = "' . $row->title . '";
      data[' . $id . ']["thumb"] = "' . $row->thumb . '";
      data[' . $id . ']["count"] = "' . (($row->videos != '') ? (count(explode(',', $row->videos)) - 1) : '0') . '";', array('type' => 'inline'));
  }
  $form['add_playlist_button'] = array(
    '#type' => 'image_button',
    '#src' => base_path() . drupal_get_path('module', 'spider_video_player') . '/images/add_but.png',
    '#attributes' => array('onclick' => 'spider_video_player_add(document.getElementById("playlist_ids_str").value, "all");spider_video_player_remove_iframe(window.parent.document.getElementById("preview_iframe"));return false;'),
  );
  // Remove button standart class.
  drupal_add_js('if(document.getElementById("edit-add-playlist-button")){document.getElementById("edit-add-playlist-button").className = ""}', array('type' => 'inline', 'scope' => 'footer'));
  drupal_add_js('
    function spider_video_player_add(id_col_string, one_or_all) {
      var ids = id_col_string.split(",");
      var tbody = window.parent.document.getElementById("video_list");
      var i = ' . variable_get('spider_video_player_playlist_count', 0) . ';
      for (key in ids) {
        if (document.getElementById("check_" + ids[key]) && ((document.getElementById("check_" + ids[key]).checked == true) || (one_or_all == "one"))) {
          var tr = window.parent.document.createElement("tr");
          tr.setAttribute("id", i);
          tr.setAttribute("video_id", ids[key]);
          tbody.appendChild(tr);
          // Image td.
          var td_image = window.parent.document.createElement("td");
          td_image.setAttribute("id", "info_" + i);
          tr.appendChild(td_image);
          var image = window.parent.document.createElement("img");
          image.setAttribute("height", "100");
          image.setAttribute("align", "left");
          image.setAttribute("style", "margin-right: 10px;");
          image.setAttribute("src", data[ids[key]]["thumb"]);
          td_image.appendChild(image);
          var b = window.parent.document.createElement("b");
          b.innerHTML = data[ids[key]]["title"];
          td_image.appendChild(b);
          var p = window.parent.document.createElement("p");
          p.setAttribute("style", "font-style: normal; color: rgb(102, 102, 102);");
          p.innerHTML = "' . t('Number of videos') . ' : ' . '" + data[ids[key]]["count"];
          td_image.appendChild(p);
          // Delete td.
          var td_delete = window.parent.document.createElement("td");
          td_delete.setAttribute("id", "X_" + i);
          td_delete.setAttribute("valign", "middle");
          td_delete.setAttribute("style", "width:50px;");
          tr.appendChild(td_delete);
          var image_delete = window.parent.document.createElement("img");
          image_delete.setAttribute("onclick", "spider_video_player_remove_row(\'" + i + "\')");
          image_delete.setAttribute("style", "cursor: pointer; margin-left: 30px;");
          image_delete.setAttribute("src", "' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/delete.png");
          td_delete.appendChild(image_delete);
          // Up td.
          var td_up = window.parent.document.createElement("td");
          td_up.setAttribute("id", "up_" + i);
          td_up.setAttribute("valign", "middle");
          td_up.setAttribute("style", "width:20px;");
          tr.appendChild(td_up);
          var image_up = window.parent.document.createElement("img");
          image_up.setAttribute("onclick", "spider_video_player_up_row(\'" + i + "\')");
          image_up.setAttribute("style", "cursor: pointer;");
          image_up.setAttribute("src", "' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/up.png");
          td_up.appendChild(image_up);
          // Down td.
          var td_down = window.parent.document.createElement("td");
          td_down.setAttribute("id", "down_" + i);
          td_down.setAttribute("valign", "middle");
          td_down.setAttribute("style", "width:20px;");
          tr.appendChild(td_down);
          var image_down = window.parent.document.createElement("img");
          image_down.setAttribute("onclick", "spider_video_player_down_row(\'" + i + "\')");
          image_down.setAttribute("style", "margin: 2px; cursor: pointer;");
          image_down.setAttribute("src", "' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/down.png");
          td_down.appendChild(image_down);
          i++;
          window.parent.document.getElementById("added_videos").value += ids[key] + ",";
          ' . variable_set('spider_video_player_playlist_count', (variable_get('spider_video_player_playlist_count', 0) + 1)) . '
        }
      }
      
    }', array('type' => 'inline'));
  $header = array(
    'checkbox' => array(
      'data' => array(
        '#type' => 'checkbox',
        '#attributes' => array(
          'id' => 'checkall_id',
          'onclick' => 'spider_video_player_check_all("checkall_id", document.getElementById("playlist_ids_str").value, "check_")',
        ),
      ),
    ),
    'id' => array('data' => t('ID'), 'field' => 'n.id'),
    'title' => array('data' => t('Title'), 'field' => 'n.title'),
    'number_of_videos' => array('data' => t('Number of Videos')),
    'published' => array('data' => t('Published'), 'field' => 'n.published'),
  );
  $options = array();
  $query = db_select('spider_video_player_playlist', 'n')
    ->fields('n', array('id'))
    ->condition('n.title', '%' . db_like(variable_get('spider_video_player_search_add_playlists_name', '')) . '%', 'LIKE')
    ->extend('TableSort')
    ->orderByHeader($header)
    ->extend('PagerDefault')
    ->limit(20);
  // Allow users edit only own playlists.
  if (($user->uid != 1) && (user_access('access Spider Video Player user playlists administration'))) {
    $query = $query
      ->condition(
        db_or()
        ->condition('n.uid', $user->uid, '=')
        ->condition('n.uid', 1, '=')
      );
  }
  $playlists_ids = $query->execute()->fetchCol();
  $playlist_ids_str = '';
  foreach ($playlists_ids as $playlist_id) {
    $row = db_query("SELECT * FROM {spider_video_player_playlist} WHERE id=:id", array(':id' => $playlist_id))->fetchObject();
    if ($row->published) {
      $publish_unpublish_png = 'publish.png';
      $publish_unpublish_function = 'unpublish';
      $disabled = 'enabled';
    }
    else {
      $publish_unpublish_png = 'unpublish.png';
      $publish_unpublish_function = 'publish';
      $disabled = 'disabled';
    }
    $playlist_ids_str .= $playlist_id . ',';
    $options[$playlist_id] = array(
      'checkbox' => array(
        'data' => array(
          '#type' => 'checkbox',
          '#attributes' => array(
            'id' => 'check_' . $playlist_id,
            $disabled => $disabled,
          ),
        ),
      ),
      'id' => $playlist_id,
      'title' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => $row->title,
          '#href' => '',
          '#attributes' => array(
            'onclick' => (($row->published == 1) ? 'spider_video_player_add("' . $playlist_id . ',", "one");spider_video_player_remove_iframe(window.parent.document.getElementById("preview_iframe"));return false;' : 'alert(Drupal.t("You can\'t add unpublished playlist."));return false;'),
          ),
        ),
      ),
      'number_of_videos' => (($row->videos != '') ? (count(explode(',', $row->videos)) - 1) : 0),
      'published' => '<img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/' . $publish_unpublish_png . '" />',
    );
  }
  $form['playlist_ids_str'] = array(
    '#type' => 'hidden',
    '#value' => $playlist_ids_str,
    '#attributes' => array('id' => 'playlist_ids_str'),
  );
  $form['playlists_table'] = array(
    '#prefix' => '<br /><strong>' . t('Playlists') . '</strong>',
    '#type' => 'tableselect',
    '#js_select' => FALSE,
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No playlists available.'),
    '#suffix' => theme('pager', array('tag' => array())),
  );
  // Disable default checkboxes.
  foreach ($playlists_ids as $playlist_id) {
    $form['playlists_table'][$playlist_id]['#disabled'] = TRUE;
  }
  // Change in iframe all page with content.
  drupal_add_js('window.onload = function() {
    var content = document.getElementById("content");
    var body = document.getElementsByTagName("body")[0];
    body.innerHTML = content.innerHTML;
    body.setAttribute("style", "padding:20px;height:0px;");
  };', array('type' => 'inline', 'scope' => 'footer'));
  return $form;
}

/**
 * Search in playlists.
 */
function spider_video_player_search_add_playlists_name($form, &$form_state) {
  if ($form_state['values']['search_playlists_name'] != '') {
    variable_set('spider_video_player_search_add_playlists_name', $form_state['values']['search_playlists_name']);
  }
  else {
    variable_set('spider_video_player_search_add_playlists_name', '');
  }
}

/**
 * Reset playlists.
 */
function spider_video_player_reset_add_playlists_name($form, &$form_state) {
  variable_set('spider_video_player_search_add_playlists_name', '');
}
