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

/**
 * Add Video form.
 */
function spider_video_player_add_video_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');
  if (isset($_GET['playlist_id'])) {
    $playlist_id = check_plain($_GET['playlist_id']);
  }
  else {
    $playlist_id = '';
  }
  $form['search_videos_name'] = array(
    '#prefix' => '<div id="spider_video_player_add_videos_search" style="display:inline-block; margin-right:10px;">',
    '#type' => 'textfield',
    '#size' => 25,
    '#title' => t('Title'),
    '#default_value' => variable_get('spider_video_player_search_add_videos_name', ''),
    '#attributes' => array('class' => array('spider_video_player_add_video_search')),
  );
  $tags = db_query("SELECT id,name FROM {spider_video_player_tag}")->fetchAllKeyed();
  foreach ($tags as $key => $tag) {
    $form['search_videos_' . $key] = array(
      '#type' => 'textfield',
      '#size' => 25,
      '#title' => check_plain($tag),
      '#default_value' => variable_get('spider_video_player_search_add_videos_' . $key, ''),
    );
  }
  $form['search_videos'] = array(
    '#prefix' => '</div>',
    '#type' => 'submit',
    '#submit' => array('spider_video_player_search_add_videos'),
    '#value' => t('Go'),
  );
  $form['reset_videos'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('spider_video_player_reset_add_videos'),
  );
  $ids_col = db_query("SELECT id FROM {spider_video_player_video}")->fetchCol();
  drupal_add_js('var data = [];', array('type' => 'inline'));
  foreach ($ids_col as $id) {
    $row = db_query("SELECT * FROM {spider_video_player_video} WHERE id=:id", array(':id' => $id))->fetchObject();
    if ($row->url != '') {
      $url = $row->url;
    }
    elseif ($row->urlHtml5 != '') {
      $url = $row->urlHtml5;
    }
    elseif ($row->urlHD != '') {
      $url = $row->urlHD;
    }
    elseif ($row->urlHdHtml5 != '') {
      $url = $row->urlHdHtml5;
    }
    else {
      $url = '';
    }
    drupal_add_js('
      data[' . $id . '] = [];
      data[' . $id . ']["title"] = "' . $row->title . '";
      data[' . $id . ']["thumb"] = "' . $row->thumb . '";
      data[' . $id . ']["type"] = "' . $row->type . '";
      data[' . $id . ']["url"] = "' . $url . '";', array('type' => 'inline'));
  }
  $form['add_video_button'] = array(
    '#prefix' => '<br />',
    '#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("video_ids_str").value, "all");spider_video_player_remove_iframe(window.parent.document.getElementById("preview_iframe"));return false;'),
  );
  drupal_add_js('if(document.getElementById("edit-add-video-button")){document.getElementById("edit-add-video-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_video_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('Type') . ' : ' . '" + data[ids[key]]["type"] + "<br />' . t('Url') . ' : ' . '" + data[ids[key]]["url"];
          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_video_count', (variable_get('spider_video_player_video_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("video_ids_str").value, "check_")',
        ),
      ),
    ),
    'id' => array('data' => t('ID'), 'field' => 'n.id'),
    'title' => array('data' => t('Title'), 'field' => 'n.title'),
    'type' => array('data' => t('Type'), 'field' => 'n.type'),
    'thumb' => array('data' => t('Thumb'), 'field' => 'n.thumb'),
    'published' => array('data' => t('Published'), 'field' => 'n.published'),
  );
  $video_ids_str = '';
  $options = array();
  $query = db_select('spider_video_player_video', 'n')
    ->fields('n', array('id'))
    ->condition('n.title', '%' . db_like(variable_get('spider_video_player_search_add_videos_name', '')) . '%', 'LIKE')
    ->extend('TableSort')
    ->orderByHeader($header)
    ->extend('PagerDefault')
    ->limit(20);
  // Allow users edit only own videos.
  if (($user->uid != 1) && (user_access('access Spider Video Player user videos administration'))) {
    $query = $query
      ->condition(
        db_or()
        ->condition('n.uid', $user->uid, '=')
        ->condition('n.uid', 1, '=')
      );
  }
  $videos_ids = $query->execute()->fetchCol();
  foreach ($videos_ids as $video_id) {
    $row = db_query("SELECT * FROM {spider_video_player_video} WHERE id=:id", array(':id' => $video_id))->fetchObject();
    $video_ids_str .= $video_id . ',';
    $params_array = explode('#***#', $row->params);
    foreach ($params_array as $param) {
      if ($param != '') {
        $param_array = explode('#===#', $param);
        // Search videos by tag name.
        if (((variable_get('spider_video_player_search_add_videos_' . $param_array[0], '') != '') && (strpos($param_array[1], variable_get('spider_video_player_search_add_videos_' . $param_array[0], '')) !== FALSE)) || (variable_get('spider_video_player_search', FALSE) === FALSE)) {
          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';
          }
          $options[$video_id] = array(
            'checkbox' => array(
              'data' => array(
                '#type' => 'checkbox',
                '#attributes' => array(
                  'id' => 'check_' . $video_id,
                  $disabled => $disabled,
                ),
              ),
            ),
            'id' => $video_id,
            'title' => array(
              'data' => array(
                '#type' => 'link',
                '#title' => $row->title,
                '#href' => '',
                '#attributes' => array(
                  'onclick' => (($row->published == 1) ? 'spider_video_player_add("' . $video_id . ',", "one");spider_video_player_remove_iframe(window.parent.document.getElementById("preview_iframe"));return false;' : 'alert(Drupal.t("You can\'t add unpublished videos."));return false;'),
                ),
              ),
            ),
            'type' => $row->type,
            'thumb' => (($row->thumb != '') ? '<img width="50" title="' . $row->thumb . '" src="' . $row->thumb . '" />' : ''),
            'published' => '<img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/' . $publish_unpublish_png . '" />',
          );
        }
      }
    }
  }
  $form['video_ids_str'] = array(
    '#type' => 'hidden',
    '#value' => $video_ids_str,
    '#attributes' => array('id' => 'video_ids_str'),
  );
  $form['videos_table'] = array(
    '#prefix' => '<br /><strong>' . t('Videos') . '</strong>',
    '#type' => 'tableselect',
    '#js_select' => FALSE,
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No videos available.'),
    '#suffix' => theme('pager', array('tag' => array())),
  );
  // Disable default checkboxes.
  foreach ($videos_ids as $video_id) {
    if (isset($form['videos_table']['#options'][$video_id])) {
      $form['videos_table'][$video_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 add videos.
 */
function spider_video_player_search_add_videos($form, &$form_state) {
  $search = FALSE;
  if ($form_state['values']['search_videos_name'] != '') {
    variable_set('spider_video_player_search_add_videos_name', $form_state['values']['search_videos_name']);
  }
  else {
    variable_set('spider_video_player_search_add_videos_name', '');
  }
  $tags = db_query("SELECT id,name FROM {spider_video_player_tag}")->fetchAllKeyed();
  foreach ($tags as $key => $tag) {
    if ($form_state['values']['search_videos_' . $key] != '') {
      variable_set('spider_video_player_search_add_videos_' . $key, $form_state['values']['search_videos_' . $key]);
      $search = TRUE;
    }
    else {
      variable_set('spider_video_player_search_add_videos_' . $key, '');
    }
  }
  variable_set('spider_video_player_search', $search);
}

/**
 * Reset add videos.
 */
function spider_video_player_reset_add_videos($form, &$form_state) {
  variable_set('spider_video_player_search_add_videos_name', '');
  variable_set('spider_video_player_search', FALSE);
  $tags = db_query("SELECT id,name FROM {spider_video_player_tag}")->fetchAllKeyed();
  foreach ($tags as $key => $tag) {
      variable_set('spider_video_player_search_add_videos_' . $key, '');
  }
}
