<?php
add_action('admin_print_scripts','kippis_options_js'  );
add_action('admin_print_styles' ,'kippis_options_css' );
add_action('admin_menu'         ,'kippis_options_menu');

function kippis_options_js()
{
  wp_enqueue_script('farbtastic');
  wp_register_script('kippis_options_js',get_template_directory_uri() . '/options/script.js',false);
  wp_enqueue_script('kippis_options_js');
}

function kippis_options_css()
{
  wp_enqueue_style('farbtastic');
  wp_register_style('kippis_options_css',get_template_directory_uri() . '/options/style.css',false);
  wp_enqueue_style('kippis_options_css');
}

function kippis_options_menu()
{
  include get_template_directory() . '/options/init_fields.php';
  include get_template_directory() . '/options/generate_css.php';
  if (isset($_GET['page']) && $_GET['page'] == basename(__FILE__)) {
    //
    //  action: save
    //
    if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'save')) {
      $arrOptions = get_option('kippis');
      foreach ($options as $option) {
        if (($option['type'] == 'open') || ($option['type'] == 'close') || ($option['type'] == 'displayonly')) continue;
        if ($option['type'] == 'image') {
          if ((!empty($_FILES)) && (!empty($_FILES[$option['id']])) && (!empty($_FILES[$option['id']]['name']))) {
            $the_value = array();
            if (preg_match('/(jpg|jpeg|png|gif|x-icon)$/',$_FILES[$option['id']]['type'])) {
              $files_one = $_FILES[$option['id']];
              $overrides = array('test_form' => false);
              $uploaded = wp_handle_upload($files_one,$overrides);
              if (isset($uploaded['url'])) {
                $image_info = getimagesize($uploaded['file']);
                $the_value['file'  ] = $uploaded['file'];
                $the_value['url'   ] = $uploaded['url' ];
                $the_value['width' ] = $image_info[0];
                $the_value['height'] = $image_info[1];
                if (((empty($the_value['width'])) || (empty($the_value['height']))) && ($_FILES[$option['id']]['type'] == 'image/x-icon')) {
                  $the_value['width' ] = '16';
                  $the_value['height'] = '16';
                }
                $_REQUEST[$option['id']] = true;
              }
            }
          }  // upload
        }  // type == image
        else {
          if (!isset($_REQUEST[$option['id']])) {
            if (($option['type'] == 'checkbox') || ($option['type'] == 'void_checkbox')) {
              $_REQUEST[$option['id']] = '';
            }
          }
          if (!is_array($_REQUEST[$option['id']])) $the_value = stripslashes($_REQUEST[$option['id']]);
          else                                     $the_value =    serialize($_REQUEST[$option['id']]);
        }
        if (isset($_REQUEST[$option['id']])) {
          if (isset($the_value)) {
            if ($option['type'] == 'color') {
              $len = strlen($the_value);
              if ((($len != 4) && ($len != 7)) || ($the_value{0} != '#')) $the_value = '';
            }
            $arrOptions[$option['id']] = $the_value;
          }
        }
      }
      update_option('kippis',$arrOptions);
      kippis_update_options_css();
      header('Location: admin.php?page=kippis_admin.php&saved=true');
      die;
    }
    //
    //  action: reset
    //
    else if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'reset')) {
      $arrOptionsOld = get_option('kippis');
      $arrOptions = array();
      foreach ($options as $option) {
        if (($option['type'] == 'open') || ($option['type'] == 'close') || ($option['type'] == 'displayonly')) continue;
        if ((isset($option['reset']))
        &&  ($option['reset'] == false)
        &&  (!empty($arrOptionsOld[$option['id']]))) {
          $arrOptions[$option['id']] = $arrOptionsOld[$option['id']];
        }
        else $arrOptions[$option['id']] = $option['std'];
      }
      update_option('kippis',$arrOptions);
      kippis_update_options_css();
      header("Location: admin.php?page=kippis_admin.php&reset=true");
      die;
    }
    //
    //  action: delete (all oprtions table data)
    //
    else if (isset($_REQUEST['action']) && ($_REQUEST['action'] == 'delete')) {
      delete_option('kippis');
      header("Location: themes.php");
      die;
    }
    //
    //  action: the end
    //
  }
  add_theme_page(__('Kippis - Options','kippis')
                ,__('Theme Options','kippis')
                ,'edit_theme_options'
                ,basename(__FILE__)
                ,'kippis_options_menu_form'
                );
}

function kippis_options_menu_form()
{
  global $kippis_options;

  $menubar_html = '';
  $fields_html  = '';

  include get_template_directory() . '/options/init_fields.php';
  include get_template_directory() . '/options/get_fields.php';

  $the_content_width = KIPPIS_HEADER_DEFAULT_WIDTH;
  if (($kippis_options['kippis_header_image_enable'] == 'on') && (!empty($kippis_options['kippis_header_image']['width']))) $the_content_width = $kippis_options['kippis_header_image']['width' ];

  $width_left   = floor($the_content_width * ((int)$kippis_options['kippis_sidebar_left_width' ]                                                         ) / 100);
  $width_right  = floor($the_content_width * ((int)$kippis_options['kippis_sidebar_right_width']                                                         ) / 100);
  $width_middle = floor($the_content_width - $width_left - $width_right);


  $fields_html = str_replace('***LEFT_SIDEBAR_WIDTH***' ,$width_left   . 'px',$fields_html);
  $fields_html = str_replace('***CONTENT_AREA_WIDTH***' ,$width_middle . 'px',$fields_html);
  $fields_html = str_replace('***RIGHT_SIDEBAR_WIDTH***',$width_right  . 'px',$fields_html);

  $save_button = '<div class="kippis_options-actions" style="clear:both;">'
               . '  <input type="hidden" name="action" value="save" />'
               . '  <input type="submit" class="button-primary" value="Save options" />'
               . '</div>'
               ;
  ?>
  <a href="http://birchware.se/wordpress/kippis" target="_blank" title="<?php _e('Kippis home','kippis'); ?>">
    <?php echo '<img src="' . get_template_directory_uri() . '/pix/icon_menu_admin.png' . '" class="icon32" />' ?>
  </a>
  <form method="post" enctype="multipart/form-data">
    <span style="float:right;margin-right:2em;">
      <span class="kippis_options-actions">
        <input type="hidden" name="action" value="reset" />
        <input type="submit" class="button-secondary" value="<?php _e('Reset','kippis'); ?>" onclick="return confirm('<?php _e('Really reset all options to their default values?','kippis'); ?>');" />
      </span>
    </span>
  </form>
  <form method="post" enctype="multipart/form-data">
    <div id="kippis_options">
      <?php echo $save_button; ?>
      <div id="kippis_options-menubar">
        <ul>
          <?php echo $menubar_html; ?>
        </ul>
      </div>
      <div id="kippis_options-content">
        <?php echo $fields_html; ?>
      </div>
      <?php echo $save_button; ?>
    </div>
  </form>
  <?php
}

