<?php

// Implementation of hook_help()
function swfobject_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      $output = t('Create Flash Movie blocks using swfobject.js');
      break;
  }
  return $output;
}

// Implementation of hook_menu()
function swfobject_menu($may_cache){
  if(!$may_cache){
    drupal_add_js(drupal_get_path('module','swfobject').'/js/swfobject.js');
  }
  return array();
}

// Implementation of hook_settings()
function swfobject_settings() {
  $form['swfobject_number'] = array(
    '#type' => 'select', 
    '#title' => t('Number of Flash Gallery Blocks'), 
    '#description' => t('The total number of independent Flash Gallery Blocks you want.'),
    '#default_value' => variable_get('swfobject_number', '1'),
    '#options' => drupal_map_assoc(array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
  );
  $form['swfobject_debug'] = array(
    '#type' => 'select', 
    '#title' => t('Debug'), 
    '#description' => t('Debug mode will display the raw html and javascript instead of using it to display the flash.'),
    '#default_value' => variable_get('swfobject_debug', 'normal'),
    '#options' => drupal_map_assoc(array('normal','debug'))
  );
  return $form;
}

// Implementation of hook_block()
function swfobject_block($op = 'list', $delta = 1, $edit = array()) {
  global $user;

  switch ($op) {
    case 'list':
      for ($i=1;$i<=variable_get('swfobject_number', '1');$i++) {
        $blocks[$i]['info'] = variable_get('swfobject_name_'. $i, 'swfobject ' . $i) . ' (swfobject)';
      }
      return $blocks;
    break;

    case 'configure':
      return swfobject_block_form($delta);
    break;

    case 'save':
      foreach($edit as $key=>$value){
        if(strpos($key, 'swfobject_') === 0){
          if($value == 'default'){
            // do not store default variables
            variable_del($key);
          }else{
            variable_set($key,$value);
          }
        }
      }
      if(isset($edit['swfobject_provide_container_'.$delta])){
        variable_set('swfobject_provide_container_'.$delta,
                     $edit['swfobject_provide_container_'.$delta]);
      }else{
        variable_set('swfobject_provide_container_'.$delta,0);
      }                              
    break;

    case 'view':
      if(variable_get('swfobject_debug', 'normal') == 'debug'){
        $block['content'] = '<pre>'.htmlspecialchars(_swfobject_block_view($delta)).'</pre>';
      }else{
        $block['content'] = theme('swfobject_block_view',$delta);
      }
      return $block; 
    break;
  }
}

function swfobject_block_form(){
  $form['swfobject_name'] = array(
    '#type' => 'textfield', 
    '#title' => t('Block Name'), 
    '#default_value' => variable_get('swfobject_name_'. $delta, 'Flash Gallery ' . $delta)
  );
  
  /**
   * Required flash movie parameters
   */
  $form['swfobject_swf'] = array(
    '#type' => 'textfield', 
    '#title' => t('Flash file (.swf) location'), 
    '#default_value' => variable_get('swfobject_swf', 'gallery.swf'),
    '#description' => t('Enter the path to the flash file (example: "flash/gallery.swf").<br />Macros:<ul><li>%h (host name: http://www.example.com/)</li><li>%t (path to theme: theme/yourtheme/)</li></ul>')        
  );
  $form['swfobject_id'] = array(
    '#type' => 'textfield',
    '#title' =>t('Id'),
    '#default_value' => variable_get('swfobject_id', 'id'),
    '#description' =>t('The ID of your object or embed tag. The embed tag will also have this value set as it’s name attribute for files that take advantage of swliveconnect.')
  );
  $form['swfobject_width'] = array(
    '#type' => 'textfield', 
    '#title' => t('Width'), 
    '#default_value' => variable_get('swfobject_width', '400'),
    '#size' => 5,
    '#description' => t('The width of the gallery in pixels, but without px')
  );
  $form['swfobject_height'] = array(
    '#type' => 'textfield', 
    '#title' => t('Height'), 
    '#default_value' => variable_get('swfobject_height', '400'),
    '#size' => 5,
    '#description' => t('The height of the gallery in pixels, but without px')
  );
  $form['swfobject_version'] = array(
    '#type' => 'textfield',
    '#title' => t('Version'),
    '#default_value' => variable_get('swfobject_version', '7'),        
    '#size' => 5,
    '#description' => t('The required player version for your Flash content. This can be a string in the format of ‘majorVersion.minorVersion.revision’. An example would be: “6.0.65”. Or you can just require the major version, such as “6”.'),
  );
  $form['swfobject_bgcolor'] = array(
    '#type' => 'textfield', 
    '#title' => t('Background color'), 
    '#default_value' => variable_get('swfobject_bgcolor', '#FFFFFF'),
    '#size' => 10,
    '#description' => t('This is the hex value of the background color of your Flash movie. (ex: #FFFFFF)')
  );
  $form['swfobject_expressinstall'] = array(
    '#type' => 'radios',
    '#title' => t('Use Express Install'),
    '#default_value' => variable_get('swfobject_expressinstall', 0),
    '#options' => array(0=>'No', 1=>'Yes'),
    '#description' => l('Macromedia Flash Player Express Install','http://blog.deconcept.com/swfobject/#expressinstall'),
  );
  $form['swfobject_wmode'] = array(
    '#type' => 'select', 
    '#title' => t('WMODE'), 
    '#description' => t('Sets the Window Mode property of the Flash movie for transparency, layering, and positioning in the browser.
                         <ul><li><b>Window</b> movie plays in its own rectangular window on a web page.</li>
                             <li><b>Opaque</b> the movie hides everything on the page behind it.</li>
                             <li><b>Transparent</b> the background of the HTML page shows through all transparent portions of the movie, this may slow animation performance.</li></ul>
                             <b>Note:</b> This property is not supported in all browsers and platforms.'),
    '#default_value' => variable_get('swfobject_wmode','default'),
    '#options' => drupal_map_assoc(array('default','window','opaque','transparent')),
  );
  
  $form['container'] = array(
    '#type' => 'fieldset',
    '#title' => 'Container Options',
  );
  $form['container']['swfobject_provide_container'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide Container?'),
    '#default_value' => variable_get('swfobject_provide_container', 1),
    '#description' => t('Check this box to provide a placeholder div for the flash movie.  It this is unchecked, you <b>must</b> specify the id of the'.
                       'container element to replace in the box below.'),
  );
  $form['container']['swfobject_container_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Container Element id'),
    '#default_value' => variable_get('swfobject_container_id', 'swfobject-container-'.$delta),
    '#description' => t('Enter a valid DOM id for the container Element. If the above checkbox is not checked, '.
                        'make sure to specify the id of an <b>existing</b> element.'),
    '#size' => 20,
  );
  $form['container']['swfobject_container_text'] = array(
    '#type' => 'textarea',
    '#title' => t('Container Placeholder Text'),
    '#default_value' => variable_get('swfobject_container_text',
                        '<a href="http://www.macromedia.com/go/getflashplayer">Get Flash Player</a>'),
    '#rows' => 4,
    '#cols' => 60,
    '#description' => t('This is the text to be shown if swfobject cannot load the flash movie.'),
  );                                                        
                       

  /**
   * Flash Variables
   */
  $form['vars'] = array(
    '#type' => 'fieldset',
    '#title' => 'Flash Variables',
    '#collapsible' => true,
    '#collapsed' => true,
  );
  $form['vars']['swfobject_flashvars'] = array(
    '#type' => 'textarea',
    '#title' => t('Flash Variables'),
    '#cols' => 40,
    '#rows' => 5,
    '#default_value' => variable_get('swfobject_flashvars',''),
    '#description' => t('Used to send root level variables to the movie.<br />
                       Specify name=>value pairs with each pair on a separate line.'),
  );
  $form['vars']['swfobject_flashvars_format'] = array(
    '#type' => 'radios',
    '#title' => 'Format',
    '#options' => array(0=>'Key:Value List',1=>'PHP Code'),
    '#default_value' => variable_get('swfobject_flashvars_format','0'),
  );
  return $form;
}

function swfobject_block_form_old($delta=0){
  $form['swfobject_name_'. $delta] = array(
    '#type' => 'textfield', 
    '#title' => t('Block Name'), 
    '#default_value' => variable_get('swfobject_name_'. $delta, 'Flash Gallery ' . $delta)
  );
  
  /**
   * Required flash movie parameters
   */
  $form['req'] = array(
    '#type' => 'fieldset',
    '#title' => t('Required Attributes'),
    '#collapsible' => false
  );
  $form['req']['swfobject_swf_'. $delta] = array(
    '#type' => 'textfield', 
    '#title' => t('Flash file (.swf) location'), 
    '#default_value' => variable_get('swfobject_swf_'. $delta, 'gallery.swf'),
    '#description' => t('Enter the path to the flash file (example: "flash/gallery.swf").<br />Macros:<ul><li>%h (host name: http://www.example.com/)</li><li>%t (path to theme: theme/yourtheme/)</li></ul>')        
  );
  $form['req']['swfobject_id_'.$delta] = array(
    '#type' => 'textfield',
    '#title' =>t('Id'),
    '#default_value' => variable_get('swfobject_id_'.$delta, 'id'),
    '#description' =>t('The ID of your object or embed tag. The embed tag will also have this value set as it’s name attribute for files that take advantage of swliveconnect.')
  );
  $form['req']['swfobject_width_'. $delta] = array(
    '#type' => 'textfield', 
    '#title' => t('Width'), 
    '#default_value' => variable_get('swfobject_width_'. $delta, '400'),
    '#size' => 5,
    '#description' => t('The width of the gallery in pixels, but without px')
  );
  $form['req']['swfobject_height_'. $delta] = array(
    '#type' => 'textfield', 
    '#title' => t('Height'), 
    '#default_value' => variable_get('swfobject_height_'. $delta, '400'),
    '#size' => 5,
    '#description' => t('The height of the gallery in pixels, but without px')
  );
  $form['req']['swfobject_version_'.$delta] = array(
    '#type' => 'textfield',
    '#title' => t('Version'),
    '#default_value' => variable_get('swfobject_version_'. $delta, '7'),        
    '#size' => 5,
    '#description' => t('The required player version for your Flash content. This can be a string in the format of ‘majorVersion.minorVersion.revision’. An example would be: “6.0.65”. Or you can just require the major version, such as “6”.'),
  );
  $form['req']['swfobject_bgcolor_'. $delta] = array(
    '#type' => 'textfield', 
    '#title' => t('Background color'), 
    '#default_value' => variable_get('swfobject_bgcolor_'. $delta, '#FFFFFF'),
    '#size' => 10,
    '#description' => t('This is the hex value of the background color of your Flash movie. (ex: #FFFFFF)')
  );
  $form['req']['swfobject_expressinstall_'.$delta] = array(
    '#type' => 'radios',
    '#title' => t('Use Express Install'),
    '#default_value' => variable_get('swfobject_expressinstall_'. $delta, 0),
    '#options' => array(0=>'No', 1=>'Yes'),
    '#description' => l('Macromedia Flash Player Express Install','http://blog.deconcept.com/swfobject/#expressinstall'),
  );
  $form['req']['swfobject_provide_container_'. $delta] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide Container?'),
    '#default_value' => variable_get('swfobject_provide_container_'. $delta, 1),
    '#description' => t('Check this box to provide a placeholder div for the flash movie.  It this is unchecked, you <b>must</b> specify the id of the'.
                       'container element to replace in the box below.'),
  );
  $form['req']['swfobject_container_id_'. $delta] = array(
    '#type' => 'textfield',
    '#title' => t('Container Element id'),
    '#default_value' => variable_get('swfobject_container_id_'. $delta, 'swfobject-container-'.$delta),
    '#description' => t('Enter a valid DOM id for the container Element. If the above checkbox is not checked, '.
                        'make sure to specify the id of an <b>existing</b> element.'),
    '#size' => 20,
  );
  $form['req']['swfobject_container_text_'. $delta] = array(
    '#type' => 'textarea',
    '#title' => t('Container Placeholder Text'),
    '#default_value' => variable_get('swfobject_container_text_'. $delta,
                        '<a href="http://www.macromedia.com/go/getflashplayer">Get Flash Player</a>'),
    '#rows' => 4,
    '#cols' => 60,
    '#description' => t('This is the text to be shown if swfobject cannot load the flash movie.'),
  );                                                        
                       
  /**
   * Optional flash movie parameters
   */
  $form['opt'] = array(
    '#type' => 'fieldset',
    '#title' => t('Optional Attributes'),
    '#collapsible' => true,
    '#collapsed' => true,
  );
  $form['opt']['swfobject_wmode_'. $delta] = array(
    '#type' => 'select', 
    '#title' => t('WMODE'), 
    '#description' => t('Sets the Window Mode property of the Flash movie for transparency, layering, and positioning in the browser.
                         <ul><li><b>Window</b> movie plays in its own rectangular window on a web page.</li>
                             <li><b>Opaque</b> the movie hides everything on the page behind it.</li>
                             <li><b>Transparent</b> the background of the HTML page shows through all transparent portions of the movie, this may slow animation performance.</li></ul>
                             <b>Note:</b> This property is not supported in all browsers and platforms.'),
    '#default_value' => variable_get('swfobject_wmode_'. $delta,'default'),
    '#options' => drupal_map_assoc(array('default','window','opaque','transparent')),
  );
  $form['opt']['swfobject_play_'. $delta] = array(
    '#type' => 'select', 
    '#title' => t('Play'), 
    '#description' => t('Specifies whether the movie begins playing immediately on loading in the browser. The default value is true if this attribute is omitted.'),
    '#default_value' => variable_get('swfobject_play_'. $delta,'default'),
    '#options' => drupal_map_assoc(array('default','true','false')),
  );
  $form['opt']['swfobject_loop_'. $delta] = array(
    '#type' => 'select', 
    '#title' => t('Loop'), 
    '#description' => t('Specifies whether the movie repeats indefinitely or stops when it reaches the last frame. The default value is true if this attribute is omitted.'),
    '#default_value' => variable_get('swfobject_loop_'. $delta,'default'),
    '#options' => drupal_map_assoc(array('default','true','false')),
  );
  $form['opt']['swfobject_menu_'. $delta] = array(
    '#type' => 'select', 
    '#title' => t('Menu'), 
    '#description' => t('<ul><li><b>True</b> displays the full menu, allowing the user a variety of options to enhance or control playback.</li>' .
        '                    <li><b>False</b> displays a menu that contains only the Settings option and the About Flash option.</li></ul>'),
    '#default_value' => variable_get('swfobject_menu_'. $delta,'default'),
    '#options' => drupal_map_assoc(array('default','true','false')),
  );
  $form['opt']['swfobject_quality_'. $delta] = array(
    '#type' => 'select',
    '#title' => t('Quality'),
    '#description' => t('<ul><li><b>Low</b> favors playback speed over appearance and never uses anti-aliasing.</li>
                         <li><b>Autolow</b> emphasizes speed at first but improves appearance whenever possible. Playback begins with anti-aliasing turned off. If the Flash Player detects that the processor can handle it, anti-aliasing is turned on.</li>
                         <li><b>Autohigh</b> emphasizes playback speed and appearance equally at first but sacrifices appearance for playback speed if necessary. Playback begins with anti-aliasing turned on. If the actual frame rate drops below the specified frame rate, anti-aliasing is turned off to improve playback speed. Use this setting to emulate the View > Antialias setting in Flash.</li>
                         <li><b>Medium</b> applies some anti-aliasing and does not smooth bitmaps. It produces a better quality than the Low setting, but lower quality than the High setting.</li>
                         <li><b>High</b> favors appearance over playback speed and always applies anti-aliasing. If the movie does not contain animation, bitmaps are smoothed; if the movie has animation, bitmaps are not smoothed.</li>
                         <li><b>Best</b> provides the best display quality and does not consider playback speed. All output is anti-aliased and all bitmaps are smoothed.</li></ul>'),
    '#default_value' => variable_get('swfobject_quality_'. $delta,'default'),
    '#options' => drupal_map_assoc(array('default','low', 'autolow', 'autohigh', 'high', 'best')),
  );
  $form['opt']['swfobject_scale_'. $delta] = array(
    '#type' => 'select',
    '#title' => t('Scale'),
    '#description' => t('<ul><li><b>Default (Show all)</b> makes the entire movie visible in the specified area without distortion, while maintaining the original aspect ratio of the movie. Borders may appear on two sides of the movie.</li>
                             <li><b>No Border</b> scales the movie to fill the specified area, without distortion but possibly with some cropping, while maintaining the original aspect ratio of the movie.</li>
                             <li><b>Exact Fit</b> makes the entire movie visible in the specified area without trying to preserve the original aspect ratio. Distortion may occur.</li></ul>'),
    '#default_value' => variable_get('swfobject_scale_'. $delta,'default'),
    '#options' => drupal_map_assoc(array('default','showall', 'noborder', 'exactfit')),
  );

  /**
   * Flash Variables
   */
  $form['vars'] = array(
    '#type' => 'fieldset',
    '#title' => 'Flash Variables',
    '#collapsible' => true,
    '#collapsed' => true,
  );
  $form['vars']['swfobject_flashvars_'.$delta] = array(
    '#type' => 'textarea',
    '#title' => t('Flash Variables'),
    '#cols' => 40,
    '#rows' => 5,
    '#default_value' => variable_get('swfobject_flashvars_'. $delta,''),
    '#description' => t('Used to send root level variables to the movie.<br />
                       Specify name=>value pairs with each pair on a separate line.'),
  );
  return $form;
}

function swfobject_load_block($delta=1){
}
  
// helper function for displaying the actual block
function theme_swfobject_block_view($delta = 1){
  // required parameter fields and defaults
  $req_params = array('swf'=>'movie.swf',
                      'id'=>'movie',
                      'width'=>'400',
                      'height'=>'400',
                      'version'=>'7',
                      'bgcolor'=>'#FFFFFF',
                      'expressinstall'=>'false');
  // fetch config values
  foreach($req_params as $key=>$val){
    $r[$key] = variable_get("swfobject_{$key}_{$delta}", $val);
  }
  // wildcard replacement for swf file
  $r['swf'] = str_replace(array('%h', '%t'), array(base_path(), path_to_theme()), $r['swf']);
  
  // container options
  $c['provide'] = variable_get('swfobject_provide_container_'. $delta, 1);
  $c['id'] = variable_get('swfobject_container_id_'. $delta, 'swfobject-container-'.$delta);
  $c['text'] = variable_get('swfobject_container_text_'. $delta, '<a href="http://www.macromedia.com/go/getflashplayer">Get Flash Player</a>');

  // optional parameter fields                      
  $opt_params = array('wmode','play','loop','menu','quality','scale');
  // fetch non-default optional config values
  $o = array();
  foreach($opt_params as $key){
    if($val = variable_get("swfobject_{$key}_{$delta}", false)){
      $o[$key] = $val;
    }
  }
  
  // js swfobject identifier
  $id = 'swfobject'.$delta;
  // join required params to make argument string
  $args = '"' . join($r,'","') . '"';
  
  // begin output
  $output = '';
  if($c['provide']){
    $output .= "<div id='{$c['id']}'>{$c['text']}</div>\n";
  }
  $output .= "<script type='text/javascript'>\n"
           . "var $id = new SWFObject($args);\n";
  // addParam all optional parameters
  foreach($o as $key=>$val){
    $output .= "$id.addParam('$key','$val');\n";
  }
  // addVariable all flashvars
  $lines = split("\n", variable_get('swfobject_flashvars_'.$delta,array()));
  foreach($lines as $line){
    list($key,$val) = split('=>',trim($line));
    if($key && $val){
      $output .= "$id.addVariable('$key','$val');\n";
    }
  }
  
  // do the replacement
  $output .= "$id.write('{$c['id']}');\n</script>\n";

  return $output;
}
