<?php
/**
 * @file
 * Spider Video Player module playlists.
 */

/**
 * Menu loader callback. Load playlists.
 */
function spider_video_player_playlists() {
  global $user;
  $form = array();
  $free_version = '
    <a href="http://web-dorado.com/files/fromSVPDrupal.php" target="_blank" style="color:red; text-decoration:none; float:right;">
      <img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/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>';
  $form['fieldset_playlist_buttons'] = array(
    '#prefix' => $free_version,
    '#type' => 'fieldset',
  );
  $form['fieldset_playlist_buttons']['publish_playlist'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_playlists_publish'),
    '#value' => t('Publish'),
  );
  $form['fieldset_playlist_buttons']['unpublish_playlist'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_playlists_unpublish'),
    '#value' => t('Unpublish'),
  );
  $form['fieldset_playlist_buttons']['delete_playlist'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_playlists_delete'),
    '#value' => t('Delete'),
    '#attributes' => array('onclick' => 'if (!confirm(Drupal.t("Do you want to delete selected playlists?"))) {return false;}'),
  );
  $form['fieldset_playlist_buttons']['new_playlist'] = array(
    '#prefix' => l(t('New'), url('admin/settings/spider_video_player/playlists/edit', array('absolute' => TRUE))),
  );
  $form['fieldset_search_playlists_name'] = array(
    '#type' => 'fieldset',
    '#title' => t('Search playlists by name'),
    '#collapsible' => TRUE,
    '#collapsed' => ((variable_get('spider_video_player_search_playlists_name', '') == '') ? TRUE : FALSE),
  );
  $form['fieldset_search_playlists_name']['search_playlists_name'] = array(
    '#type' => 'textfield',
    '#size' => 25,
    '#default_value' => variable_get('spider_video_player_search_playlists_name', ''),
  );
  $form['fieldset_search_playlists_name']['search_playlists'] = array(
    '#type' => 'submit',
    '#submit' => array('spider_video_player_search_playlists_name'),
    '#value' => t('Go'),
  );
  $form['fieldset_search_playlists_name']['reset_playlists'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('spider_video_player_reset_playlists_name'),
  );
  $header = array(
    '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'),
    'delete' => array('data' => t('Delete')),
  );
  $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_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();
  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';
    }
    else {
      $publish_unpublish_png = 'unpublish.png';
      $publish_unpublish_function = 'publish';
    }
    $options[$playlist_id] = array(
      'id' => $playlist_id,
      'title' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => $row->title,
          '#href' => url('admin/settings/spider_video_player/playlists/edit', array('query' => array('playlist_id' => $playlist_id), 'absolute' => TRUE)),
        ),
      ),
      'number_of_videos' => (($row->videos != '') ? (count(explode(',', $row->videos)) - 1) : 0),
      'published' => l(t('<img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/' . $publish_unpublish_png . '" />'), url('admin/settings/spider_video_player/playlists/' . $publish_unpublish_function, array('query' => array('playlist_id' => $playlist_id), 'absolute' => TRUE)), array('html' => TRUE)),
      'delete' => array(
        'data' => array(
          '#type' => 'link',
          '#title' => t('Delete'),
          '#href' => url('admin/settings/spider_video_player/playlists/delete', array('query' => array('playlist_id' => $playlist_id), 'absolute' => TRUE)),
        ),
      ),
    );
  }
  $form['playlists_table'] = array(
    '#type' => 'tableselect',
    '#js_select' => TRUE,
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No playlists available.'),
    '#suffix' => theme('pager', array('tag' => array())),
  );
  return $form;
}

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

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

/**
 * Publish selected playlists.
 */
function spider_video_player_playlists_publish($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_playlist}")) {
    $playlist_ids_col = db_query("SELECT id FROM {spider_video_player_playlist}")->fetchCol();
    $flag = FALSE;
    foreach ($playlist_ids_col as $playlist_id) {
      if (isset($_POST['playlists_table'][$playlist_id])) {
        $flag = TRUE;
        db_query("UPDATE {spider_video_player_playlist} SET published=:published WHERE id=:id", array(':published' => 1, ':id' => $playlist_id));
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one playlist.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('Selected playlists successfully published.'), 'status', FALSE);
    }
  }
}

/**
 * Publish playlist.
 */
function spider_video_player_playlist_publish() {
  if (isset($_GET['playlist_id'])) {
    $playlist_id = check_plain($_GET['playlist_id']);
    db_query("UPDATE {spider_video_player_playlist} SET published=:published WHERE id=:id", array(':published' => 1, ':id' => $playlist_id));
  }
  drupal_set_message(t('Playlist successfully published.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/playlists', array('absolute' => TRUE)));
}

/**
 * Unpublish selected playlists.
 */
function spider_video_player_playlists_unpublish($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_playlist}")) {
    $playlist_ids_col = db_query("SELECT id FROM {spider_video_player_playlist}")->fetchCol();
    $flag = FALSE;
    foreach ($playlist_ids_col as $playlist_id) {
      if (isset($_POST['playlists_table'][$playlist_id])) {
        $flag = TRUE;
        db_query("UPDATE {spider_video_player_playlist} SET published=:published WHERE id=:id", array(':published' => 0, ':id' => $playlist_id));
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one playlist.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('Selected playlists successfully unpublished.'), 'status', FALSE);
    }
  }
}

/**
 * Unpublish playlist.
 */
function spider_video_player_playlist_unpublish() {
  if (isset($_GET['playlist_id'])) {
    $playlist_id = check_plain($_GET['playlist_id']);
    db_query("UPDATE {spider_video_player_playlist} SET published=:published WHERE id=:id", array(':published' => 0, ':id' => $playlist_id));
  }
  drupal_set_message(t('Playlist successfully unpublished.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/playlists', array('absolute' => TRUE)));
}

/**
 * Delete selected playlists.
 */
function spider_video_player_playlists_delete($form, &$form_state) {
  if (db_query("SELECT id FROM {spider_video_player_playlist}")) {
    $playlist_ids_col = db_query("SELECT id FROM {spider_video_player_playlist}")->fetchCol();
    $flag = FALSE;
    foreach ($playlist_ids_col as $playlist_id) {
      if (isset($_POST['playlists_table'][$playlist_id])) {
        $flag = TRUE;
        db_query("DELETE FROM {spider_video_player_playlist} WHERE id=:id", array(':id' => $playlist_id));
        $ids_col = db_query("SELECT id,playlist FROM {spider_video_player_form_table}")->fetchAllKeyed();
        foreach ($ids_col as $key => $playlist) {
          if (strpos($playlist, $playlist_id . ',')) {
            db_query("UPDATE {spider_video_player_form_table} SET playlist=:playlist WHERE id=:id", array(':playlist' => str_replace($playlist_id . ',', '', $playlist), ':id' => $key));
          }
        }
      }
    }
    if ($flag == FALSE) {
      drupal_set_message(t('You must select at least one playlist.'), 'warning', FALSE);
    }
    else {
      drupal_set_message(t('Selected playlists successfully deleted.'), 'status', FALSE);
    }
  }
}

/**
 * Delete playlist.
 */
function spider_video_player_playlist_delete() {
  if (isset($_GET['playlist_id'])) {
    $playlist_id = check_plain($_GET['playlist_id']);
    db_query("DELETE FROM {spider_video_player_playlist} WHERE id=:id", array(':id' => $playlist_id));
    $ids_col = db_query("SELECT id,playlist FROM {spider_video_player_form_table}")->fetchAllKeyed();
    foreach ($ids_col as $key => $playlist) {
      if (strpos($playlist, $playlist_id . ',')) {
        db_query("UPDATE {spider_video_player_form_table} SET playlist=:playlist WHERE id=:id", array(':playlist' => str_replace($playlist_id . ',', '', $playlist), ':id' => $key));
      }
    }
  }
  drupal_set_message(t('Playlist successfully deleted.'), 'status', FALSE);
  drupal_goto(url('admin/settings/spider_video_player/playlists', array('absolute' => TRUE)));
}

/**
 * Add or edit playlist.
 */
function spider_video_player_playlist_edit() {
  drupal_add_js(drupal_get_path('module', 'spider_video_player') . '/js/spider_video_player_change_video_type.js');
  drupal_add_js(drupal_get_path('module', 'spider_video_player') . '/js/spider_video_player_move_videos.js');
  drupal_add_js(drupal_get_path('module', 'spider_video_player') . '/js/spider_video_player_check_required.js');
  if (isset($_GET['playlist_id']) && (check_plain($_GET['playlist_id']) != '')) {
    $playlist_id = check_plain($_GET['playlist_id']);
    $row = db_query("SELECT * FROM {spider_video_player_playlist} WHERE id=:id", array(':id' => $playlist_id))->fetchObject();
    $playlist_title = $row->title;
    $added_videos = $row->videos;
    $playlist_thumb = $row->thumb;
    $playlist_published = $row->published;
  }
  else {
    $playlist_id = '';
    $playlist_title = '';
    $added_videos = '';
    $playlist_thumb = '';
    $playlist_published = 1;
  }
  if (!isset($_GET['playlist_id'])) {
    variable_set('spider_video_player_videos_', '');
  }
  $added_videos .= variable_get('spider_video_player_videos_' . $playlist_id, '');
  $form = array();
  $form['playlist_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#required' => TRUE,
    '#default_value' => $playlist_title,
    '#size' => 35,
  );
  drupal_add_js(drupal_get_path('module', 'spider_video_player') . '/js/spider_video_player_open_iframe.js');
  $form['add_video_button'] = array(
    '#prefix' => '<div id="preview_iframe"></div><label><strong>' . t('Videos') . '</strong></label>',
    '#type' => 'image_button',
    '#src' => base_path() . drupal_get_path('module', 'spider_video_player') . '/images/add_but.png',
    '#attributes' => array('onclick' => 'spider_video_player_iframe("preview_iframe", "' . url('admin/settings/spider_video_player/playlists/add_video', array('query' => array('playlist_id' => $playlist_id), 'absolute' => TRUE)) . '", "' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/close.png"); return false;'),
  );
  // Remove button standart class.
  drupal_add_js('if(document.getElementById("edit-add-video-button")){document.getElementById("edit-add-video-button").className = ""}', array('type' => 'inline', 'scope' => 'footer'));
  if ($added_videos != '') {
    $added_video_array = explode(',', $added_videos);
    $video_list = '
      <table>
        <tbody id="video_list">';
    foreach ($added_video_array as $key => $added_video) {
      if ($added_video != '') {
        $video_row = db_query("SELECT * FROM {spider_video_player_video} WHERE id=:id", array(':id' => $added_video))->fetchObject();
        if ($video_row->url != '') {
          $video_url = $video_row->url;
        }
        elseif ($video_row->urlHtml5 != '') {
          $video_url = $video_row->urlHtml5;
        }
        elseif ($video_row->urlHD != '') {
          $video_url = $video_row->urlHD;
        }
        elseif ($video_row->urlHdHtml5 != '') {
          $video_url = $video_row->urlHdHtml5;
        }
        else {
          $video_url = '';
        }
        $video_list .= '
          <tr id="' . $key . '" video_id="' . $video_row->id . '">
            <td id="info_' . $key . '">
              <img height="100" align="left" src="' . $video_row->thumb . '" style="margin-right: 10px;">
              <b>' . $video_row->title . '</b>
              <p style="font-style: normal; color: rgb(102, 102, 102);">
                ' . t('Type') . ' : ' . $video_row->type . '
                <br />
                ' . t('Url') . ' : ' . $video_url . '
              </p>
            </td>
            <td id="X_' . $key . '" valign="middle" style="width: 50px;">
              <img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/delete.png" style="cursor: pointer; margin-left: 30px;" onclick=\'spider_video_player_remove_row("' . $key . '")\'>
            </td>
            <td id="up_' . $key . '" valign="middle" style="width: 20px;">
              <img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/up.png" style="cursor: pointer;" onclick=\'spider_video_player_up_row("' . $key . '")\'>
            </td>
            <td id="down_' . $key . '" valign="middle" style="width: 20px;">
              <img src="' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/down.png" style="margin: 2px; cursor: pointer;" onclick=\'spider_video_player_down_row("' . $key . '")\'>
            </td>
          </tr>';
      }
    }
    $video_list .= '
        </tbody>
      </table>';
  }
  else {
    $video_list = '<table><tbody id="video_list"></tbody></table>';
  }
  $form['added_videos'] = array(
    '#prefix' => $video_list,
    '#type' => 'hidden',
    '#value' => $added_videos,
    '#attributes' => array('id' => 'added_videos'),
  );
  $form['playlist_thumb'] = array(
    '#prefix' => '
      <div id="image_iframe" style="position:fixed; width:100%; height:100%; top:50px; left:0; display:none">
        <div id="div_black" style="position:fixed; top:0; left:0; width:100%; height:100%; background-color:#000000; opacity:0.80; z-index:10000000;"></div>
        <div id="div_content" style="position:relative; top:50px; width:570px; height:500px; margin:0 auto;z-index:10000001;background-color:#FFFFFF;">
          <iframe width="570" height="500" src="' . url('admin/settings/spider_video_player/image_upload', array('absolute' => TRUE)) . '"></iframe>
        </div>
        <div onclick=\'spider_video_player_image_upload("none")\' style=\'position:fixed; z-index:10000002; right:20%; top:100px; width:32px; height:32px; background-image:url("' . base_path() . drupal_get_path('module', 'spider_video_player') . '/images/close.png"); \'></div>
      </div>
      <br />
      <strong>' . t('Thumb') . '</strong>
      <br />',
    '#type' => 'link',
    '#href' => '',
    '#title' => t('Select Image'),
    '#attributes' => array('onclick' => 'spider_video_player_image_upload("");return false;'),
  );
  $form['thumb'] = array(
    '#type' => 'hidden',
    '#value' => $playlist_thumb,
    '#attributes' => array('id' => 'thumb'),
  );
  $form['playlist_thumb_remove'] = array(
    '#prefix' => '<br />',
    '#type' => 'link',
    '#href' => '',
    '#title' => t('Remove Image'),
    '#attributes' => array('onclick' => 'spider_video_player_remove_image(); return false;'),
    '#suffix' => '<br /><img id="imagebox" ' . (($playlist_thumb != '') ? 'height="150" src="' . $playlist_thumb . '"' : '') . '/><br />',
  );
  $form['playlist_published'] = array(
    '#type' => 'radios',
    '#title' => t('Published'),
    '#default_value' => $playlist_published,
    '#options' => array('1' => t('Yes'), '0' => t('No')),
  );
  $form['playlist_save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#submit' => array('spider_video_player_playlist_save'),
    '#attributes' => array('onclick' => 'return spider_video_player_check_required("edit-playlist-title", "", "");'),
  );
  $form['playlist_apply'] = array(
    '#type' => 'submit',
    '#value' => t('Apply'),
    '#submit' => array('spider_video_player_playlist_apply'),
    '#attributes' => array('onclick' => 'return spider_video_player_check_required("edit-playlist-title", "", "");'),
  );
  $form['playlist_cancel'] = array(
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#attributes' => array('onclick' => 'document.getElementById("edit-playlist-title").setAttribute("style", "color:rgba(255, 0, 0, 0)");document.getElementById("edit-playlist-title").setAttribute("value", "cancel");'),
    '#submit' => array('spider_video_player_playlist_cancel'),
  );
  return $form;
}

/**
 * Save playlist.
 */
function spider_video_player_playlist_save($form, &$form_state) {
  global $user;
  $playlist_title = $form_state['values']['playlist_title'];
  $added_videos = check_plain($_POST['added_videos']);
  $playlist_thumb = check_plain($_POST['thumb']);
  $playlist_published = $form_state['values']['playlist_published'];
  if (isset($_GET['playlist_id']) && (check_plain($_GET['playlist_id']) != '')) {
    $playlist_id = check_plain($_GET['playlist_id']);
    db_query("UPDATE {spider_video_player_playlist} SET 
      uid=:uid,
      title=:title,
      videos=:videos,
      thumb=:thumb,
      published=:published WHERE id=:id", array(
      ':uid' => $user->uid,
      ':title' => $playlist_title,
      ':videos' => $added_videos,
      ':thumb' => $playlist_thumb,
      ':published' => $playlist_published,
      ':id' => $playlist_id));
    variable_set('spider_video_player_videos_' . $playlist_id, '');
  }
  else {
    db_insert('spider_video_player_playlist')
      ->fields(array(
        'uid' => $user->uid,
        'title' => $playlist_title,
        'videos' => $added_videos,
        'thumb' => $playlist_thumb,
        'published' => $playlist_published,
        ))
      ->execute();
    variable_set('spider_video_player_playlist_id', '');
  }
  drupal_set_message(t('Your playlist successfully saved.'), 'status', FALSE);
  $form_state['redirect'] = url('admin/settings/spider_video_player/playlists', array('absolute' => TRUE));
}

/**
 * Apply playlist.
 */
function spider_video_player_playlist_apply($form, &$form_state) {
  global $user;
  $playlist_title = $form_state['values']['playlist_title'];
  $added_videos = check_plain($_POST['added_videos']);
  $playlist_thumb = check_plain($_POST['thumb']);
  $playlist_published = $form_state['values']['playlist_published'];
  if (isset($_GET['playlist_id']) && (check_plain($_GET['playlist_id']) != '')) {
    $playlist_id = check_plain($_GET['playlist_id']);
    db_query("UPDATE {spider_video_player_playlist} SET 
      uid=:uid,
      title=:title,
      videos=:videos,
      thumb=:thumb,
      published=:published WHERE id=:id", array(
      ':uid' => $user->uid,
      ':title' => $playlist_title,
      ':videos' => $added_videos,
      ':thumb' => $playlist_thumb,
      ':published' => $playlist_published,
      ':id' => $playlist_id));
    drupal_set_message(t('Your playlist successfully updated.'), 'status', FALSE);
    variable_set('spider_video_player_videos_' . $playlist_id, '');
  }
  else {
    db_insert('spider_video_player_playlist')
      ->fields(array(
        'uid' => $user->uid,
        'title' => $playlist_title,
        'videos' => $added_videos,
        'thumb' => $playlist_thumb,
        'published' => $playlist_published,
        ))
      ->execute();
    $playlist_id = db_query("SELECT MAX(id) FROM {spider_video_player_playlist}")->fetchField();
    drupal_set_message(t('Your playlist successfully saved.'), 'status', FALSE);
    variable_set('spider_video_player_playlist_id', '');
  }
  $form_state['redirect'] = url('admin/settings/spider_video_player/playlists/edit', array('query' => array('playlist_id' => $playlist_id), 'absolute' => TRUE));
}

/**
 * Cancel playlist save.
 */
function spider_video_player_playlist_cancel($form, &$form_state) {
  $form_state['redirect'] = url('admin/settings/spider_video_player/playlists', array('absolute' => TRUE));
}
