<?php

//$Id: sifr.module,v 1.7 2006/10/23 21:53:41 rz Exp $

/**
 * @file
 * sIFR Module for Drupal
 * by Jeff Robbins - www.lullabot.com
 * development sponsored by Bryght
 * Implements sIFR capabilities for all pages.
 * http://www.mikeindustries.com/sifr/
 */

function sifr_help($section){
  switch($section){
    case "admin/modules#description":
      return t('sIFR: Flash text replacement.');
  }
}

function sifr_menu($may_cache){
  $items = array();
  if($may_cache){
    $items[] = array(
      'title' => t('sIFR'),
      'path' => 'admin/settings/sifr',
      'access' => user_access('administer site configuration'), // best way?
      'callback' => 'sifr_rules',
    );
    $items[] = array(
      'title' => t('rules'),
      'path' => 'admin/settings/sifr/rules',
      'access' => user_access('administer site configuration'), // best way?
      'callback' => 'sifr_rules',
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'weight' => -2,
    );
    $items[] = array(
      'title' => t('add rule'),
      'path' => 'admin/settings/sifr/addrule',
      'access' => user_access('administer site configuration'), // best way?
      'callback' => 'sifr_add_rule',
      'type' => MENU_LOCAL_TASK,
      'weight' => -1,
    );
    $items[] = array(
      'title' => t('delete rule'),
      'path' => 'admin/settings/sifr/rules/delete',
      'access' => user_access('administer site configuration'), // best way?
      'callback' => 'sifr_delete_confirm',
      'type' => MENU_CALLBACK,
    );
    $items[] = array(
      'title' => t('manage fonts'),
      'path' => 'admin/settings/sifr/manage',
      'access' => user_access('administer site configuration'), // best way?
      'callback' => 'sifr_manage',
      'type' => MENU_LOCAL_TASK,
      'weight' => 2,
    );
    // "fake" CSS files for sIFR
    //   allow dynamic content
    $items[] = array(
      'title' => t('sifr screen css'),
      'path' => 'sifr/sifr-screen.css',
      'access' => TRUE, // all users
      'callback' => 'sifr_css_screen',
      'type' => MENU_CALLBACK,
    );
    $items[] = array(
      'title' => t('sifr print css'),
      'path' => 'sifr/sifr-print.css',
      'access' => TRUE, // all users
      'callback' => 'sifr_css_print',
      'type' => MENU_CALLBACK,
    );
    $items[] = array(
      'title' => t('download sifr file'),
      'path' => 'sifr/download',
      'callback' => 'sifr_octet_download',
      'access' => user_access('administer site configuration'),
      'type' => MENU_CALLBACK,
    );
  }
  else {
    $items[] = array(
      'title' => t('edit'),
      'path' => 'admin/settings/sifr/edit',
      'access' => user_access('administer site configuration'),
      'callback' => 'sifr_edit_rule',
      'type' => strpos($_GET['q'], 'admin/settings/sifr/edit') === 0 ? MENU_LOCAL_TASK : MENU_CALLBACK,
      'weight' => 5,
    );
    $items[] = array(
      'title' => t('delete font'),
      'path' => 'admin/settings/sifr/deletefont',
      'access' => user_access('administer site configuration'),
      'callback' => 'sifr_fontdelete_confirm',
      'type' => strpos($_GET['q'], 'admin/settings/sifr/deletefont') === 0 ? MENU_LOCAL_TASK : MENU_CALLBACK,
      'weight' => 6,
    );
    sifr_all_pages();
  }
  return $items;
}

/**
 * List the rules
 */

function sifr_rules(){
  $rules = sifr_get_rules();
  $mypath = drupal_get_path('module', 'sifr');
  $output .= t('<h2>Current Rules</h2>');
  $header = array(t('Rule Name'), t('CSS Selector'), t('Font'), t('Colors'), '', '');
  $editimg = theme('image', $mypath .'/images/editor.png');
  $delimg = theme('image', $mypath .'/images/delete.png');
  foreach($rules as $r){
    $fontroot = substr($r->font, strrpos($r->font, '/') + 1);
    $rows[] = array(
      $r->name, $r->selector, 
      $fontroot,
      "<div style='width:90px; height:16px'>
      <div style='float:left; width:16px; height:16px; background-color:$r->color; margin: 0 3px 0 0' title='".t('font color')."'> </div>
      <div style='float:left; width:16px; height:16px; background-color:$r->linkcolor; margin: 0 3px 0 0' title='".t('link color')."'> </div>
      <div style='float:left; width:16px; height:16px; background-color:$r->hovercolor; margin: 0 3px 0 0' title='".t('hover color')."'> </div>
      <div style='float:left; width:16px; height:16px; background-color:$r->bgcolor; margin: 0 3px 0 0' title='".t('background color')."'> </div>
      </div>
      ",
      l($editimg .' '. t('edit'), 'admin/settings/sifr/edit/'.$r->rid, array(), NULL, NULL, FALSE, TRUE),
      l($delimg .' '. t('delete'), 'admin/settings/sifr/rules/delete/'.$r->rid, array(), NULL, NULL, FALSE, TRUE));
  }
  $output .= theme_table($header, $rows, array('style' => 'width:100%; clear:both;'));
  $output .=  '<p>';
  $output .= l(t('Add another rule'), 'admin/settings/sifr/addrule') .'</p>';
  $output .= sifr_version();
  $output .= l(theme('image', $mypath .'/images/sifr.png', 'sIFR', 'Link to the sIFR', array()), 'http://www.mikeindustries.com/sifr/', array(), NULL, NULL, FALSE, TRUE);
  return $output;
}

function sifr_add_rule(){
  $output .= t('<h2>Add a new sIFR rule</h2>');
  $output .= sifr_edit_rule();
  return $output;
}

/**
 * Manage the .swf files
 */
function sifr_manage(){
  $sifr = str_replace(' ', "%20", sifr_find_sifr());
  global $base_url;
  
  $output .= t('<h2>Available fonts</h2>');
  
  $delimg = theme('image', drupal_get_path('module', 'sifr') .'/images/delete.png');
  $filedir = file_directory_path().'/sifr';
  
  $header = array(t('Font'), t('Location'), '');
  foreach(sifr_get_swfs() as $file => $name){
    $editable = strpos($file, $filedir) === FALSE ? FALSE : TRUE;
    $rows[] = array(
      $name,
      $file,
      $editable ? l($delimg .' '. t('delete'), 'admin/settings/sifr/deletefont/'.urlencode($file), array(), NULL, NULL, FALSE, TRUE) : '',
    );
  }
  $output .= theme('table', $header, $rows, array('style' => 'width:100%'));
  
  $form['#attributes'] = array('enctype' => 'multipart/form-data');
  
  $instructions = t("<div><strong>To create sIFR font files:</strong></div>
    <ol>
      <li>Download these files to the same directory: %files</li>
      <li>Open the file in Macromedia Flash.</li>
      <li>Double-click the invisible textbox in the middle of the stage. If the &quot;Properties&quot; palette is not already visible, open it by selecting &quot;Window > Properties&quot;, and select which font you'd like to use from the drop down menu. If you select a TrueType font, you can also create bold and italic styles for your font by clicking on the &quot;I&quot; or &quot;B&quot; buttons. The standard sifr.fla file contains most of the English characters you will generally need. If you need to embed additional characters or languages, click the &quot;Character&quot; button and select more characters from there.</li>
      <li>To export the new file, choose &quot;File > Export&quot; and save as fontname.swf</li>
      <li>Upload the your font file below.</li>
    </ol>",
    array(
      '%files' => l('sifr.fla', 'sifr/download/sifr.fla')
        .', '. l('customize_me.as', 'sifr/download/customize_me.as')
        .', '. l('dont_customize_me.as', 'sifr/download/dont_customize_me.as')
    ));
  $form['instructions'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#title' => t('Instructions'),
    '#attributes' => array('style' => 'margin-top: 15px'),
  );
  $form['instructions']['instructions'] = array(
    '#type' => 'markup',
    '#value' => $instructions
  );
  $form['sifrfile'] = array(
    '#type' => 'file',
    '#title' => t('Upload sIFR font file'),
    '#description' => t('Select the .swf file that you created using the instructions above.'),
    '#size' => 40,
    );
  $form[] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    );
  $output .= drupal_get_form('sifr_upload', $form);
  return $output;
}

function sifr_upload_validate($form_id, &$form_values){
  // check that it's a swf file
}

function sifr_upload_submit($form_id, $form_values){
  $dir = file_create_path('sifr');
  if (file_check_directory($dir, 1)) { // creates directory if needed
    if ($file = file_save_upload('sifrfile', 'sifr')) {
      drupal_set_message(t('New font file uploaded.'));
    }
    else {
      drupal_set_message(t('File could not be saved.'), 'error');
    }
  }
  else {
    drupal_set_message(t('Cannot create sifr directory in files.'), 'error');
  }
}

/**
 * Edit or create a new rule
 *
 * @param $edit
 * an array or object of rule parameters
 * @return
 * the rendered form
 */

function sifr_edit_rule($edit = NULL){
  if(is_numeric($edit)){
    if($_POST['op'] == t('Delete')){
      drupal_goto('admin/settings/sifr/rules/delete/'.$edit);
    }
    else {
      $edit = sifr_load_rule($edit);
    }
  }
  $edit = (array)$edit;
  if ($edit['rid']){
    $form['rid'] = array('#type' => 'hidden', '#value' => $edit['rid']);
  }
  $form['basics'] = array(
    '#type' => 'fieldset',
    '#title' => t('Basics'),
  );
  $form['basics']['name'] = array(
    '#type' => 'textfield', 
    '#title' => t('Rule Name'),
    '#default_value' => $edit['name'],
    '#required' => TRUE,
    '#description' => t('The human readable name for this rule.')
  );
  
  $form['basics']['selector'] = array(
    '#type' => 'textfield', 
    '#title' => t('CSS Selector'),
    '#default_value' => $edit['selector'],
    '#description' => t('<div>CSS selector for the elements you want to replace.
    </div>'),
    '#required' => TRUE,
  );
  $form['basics']['selectorhelp'] = array(
    '#type' => 'fieldset',
    '#title' => t('CSS Selector Help'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,  
  );
  $form['basics']['selectorhelp']['contents'] = array(
    '#type' => 'markup',
    '#value' => t('<div>The supported CSS selectors are <code>#</code>, <code>&gt;</code> and <code>.</code>. Whitespace is used to select descendants. Please use whitespace only for this, so instead of <code>#foo &gt; p</code> use <code>#foo&gt;p</code>. You can use multiple selectors by seperating them with a comma ("<code>,</code>").</div>
    <div style="margin-top:5px">Example presets based on Bluemarine default elements:
    <div> - <a href="" onclick="document.getElementById(\'edit-selector\').value = \'#main .title\';return false;">page title</a></div>
    <div> - <a href="" onclick="document.getElementById(\'edit-selector\').value = \'.node .title\';return false;">node titles</a></div>
    <div> - <a href="" onclick="document.getElementById(\'edit-selector\').value = \'.block .title\';return false;">block titles</a></div>
    <div> - <a href="" onclick="document.getElementById(\'edit-selector\').value = \'.comment .title\';return false;">comment titles</a></div>
    Selectors may be dependent on your theme. Examine html source to find appropriate classes and ids being output by your current theme.
    </div>'),
    );
  
  $form['basics']['font'] = array(
    '#type' => 'fieldset'
  );  
  $form['basics']['font']['font'] = array(
    '#title' => t('Font'),
    '#type' => 'item',
    '#description' => t("Select a font to use for this rule."),
    '#required' => TRUE,
  );
  $swfs = sifr_get_swfs();
  $rule->color = '#000000';
  $rule->linkcolor = '#000000';
  $rule->hovercolor = '#000000';
  $rule->bgcolor = '#FFFFFF';
  $myrules = array();
  foreach($swfs as $path => $name){
    $form['basics']['font']['font'][]['font'] = array(
      '#type' => 'radio',
      '#title' => "<span id='font-". str_replace(array(' ', '_'), '-', $name) ."' class='sifr-font'>". $name .'</span>',
      '#return_value' => $path,
      '#default_value' => $edit['font'], 
    );
    $rule->selector = "#font-". str_replace(array(' ', '_'), '-', $name);
    $rule->font = $path;
    $myrules[] = sifr_render_rule_js($rule);
  }
  drupal_set_html_head(sifr_wrap_rules($myrules));
  
  $form['colors'] = array(
    '#type' => 'fieldset',
    '#title' => t('Colors'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('Each rule defines the colors for replaced text. Use six-character hexadecimal (CSS-style) color values preceeded by &quot;<code>#</code>&quot; to define text color, linked text color, hover-over link color, and text background color.'),
  );
  $form['colors']['color'] = array(
    '#type' => 'textfield',
    '#title' => t('Text Color'),
    '#size' => 12,
    '#default_value' => $edit['color'] ? $edit['color'] : '#000000',
  );
  $form['colors']['linkcolor'] = array(
    '#type' => 'textfield',
    '#title' => t('Link Color'),
    '#size' => 12,
    '#default_value' => $edit['linkcolor'] ? $edit['linkcolor'] : '#000000',
  );
  /*$form['colors']['hovercolor'] = array(
    '#type' => 'textfield',
    '#title' => t('Hover Color'),
    '#size' => 12,
    '#default_value' => $edit['hovercolor'] ? $edit['hovercolor'] : '#666666',
  );*/
  //LukeM:I removed the default value because the hover was making flash 9 not interpret the link properly.
  $form['colors']['hovercolor'] = array(
    '#type' => 'textfield',
    '#title' => t('Hover Color'),
    '#size' => 12,
    '#default_value' => $edit['hovercolor'] ? $edit['hovercolor'] : '',
  );  
  $form['colors']['bgcolor'] = array(
    '#type' => 'textfield',
    '#title' => t('Text Background Color'),
    '#size' => 12,
    '#default_value' => $edit['bgcolor'] ? $edit['bgcolor'] : '#FFFFFF',
  );
  $form['colors']['transparent'] = array(
    '#type' => 'checkbox',
    '#title' => t('Use transparency'),
    '#default_value' => $edit['transparent'],
    '#return_value' => 1,
    '#description' => t('<strong>Warning:</strong> Flash transparency is not well supported in all browsers and therefore not recommended.'),
  );
  $form['tweaks'] = array(
    '#type' => 'fieldset',
    '#title' => t('Tweaks'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  );
  $form['tweaks']['letterspacing'] = array(
    '#type' => 'textfield',
    '#title' => t('Letter Spacing'),
    '#description' => t('A CSS value to adjust letter spacing on replaced text. Examples: &quot;-5px&quot;, &quot;-.2em&quot;'),
    '#size' => 12,
    '#default_value' => $edit['letterspacing'],
  );
  $form['tweaks']['fontsize'] = array(
    '#type' => 'textfield',
    '#title' => t('Font Size'),
    '#description' => t('A CSS value to adjust font size on replaced text. Examples: &quot;55px&quot;, &quot;2em&quot;'),
    '#size' => 12,
    '#default_value' => $edit['fontsize'],
  );
  $form['tweaks']['padding'] = array(
    '#type' => 'fieldset',
    '#title' => t('Padding'),
    '#description' => '<div style="display:block">'. t('If you use padding in the elements you want to replace, you have to set the amount of padding here (in pixels, but without the px part)') .'</div>',
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  theme('add_style', drupal_get_path('module', 'sifr') .'/sifr.css');
  $form['tweaks']['padding']['paddingtop'] = array(
    '#type' => 'textfield',
    '#title' => t('top'),
    '#size' => 6,
    '#default_value' => $edit['paddingtop'],
  );
  $form['tweaks']['padding']['paddingright'] = array(
    '#type' => 'textfield',
    '#title' => t('right'),
    '#size' => 6,
    '#default_value' => $edit['paddingright'],
  );
  $form['tweaks']['padding']['paddingbottom'] = array(
    '#type' => 'textfield',
    '#title' => t('bottom'),
    '#size' => 6,
    '#default_value' => $edit['paddingbottom'],
  );
  $form['tweaks']['padding']['paddingleft'] = array(
    '#type' => 'textfield',
    '#title' => t('left'),
    '#size' => 6,
    '#default_value' => $edit['paddingleft'],
  );
  $form['tweaks']['textalign'] = array(
    '#type' => 'select',
    '#title' => t('Text Alignment'),
    '#default_value' => $edit['textalign'],
    '#options' => array(
      'left' => t('Left'),
      'center' => t('Center'),
      'right' => t('Right'),
    ),    
  );
  $form['tweaks']['lettercase'] = array(
    '#type' => 'select',
    '#title' => t('Case Transform'),
    '#default_value' => $edit['lettercase'],
    '#options' => array(
      'normal' => t('Normal'),
      'upper' => t('Upper-Case'),
      'lower' => t('Lower-Case'),
    ),
    '#description' => t('You can transform the text to be all upper-case or all lower-case'),
  );
  $form['tweaks']['underline'] = array(
    '#type' => 'checkbox',
    '#title' => t('Underline Links on Hover?'),
    '#default_value' => $edit['underline'],
    '#return_value' => 1,
  );
  
  // weight may not be necessary
  $form['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#description' => t('You can adjust the order in which the rules are executed by changing their weights. Lighter items execute before heavier.'),
    '#delta' => 10,
    '#default_value' => $edit['weight'],
  );
  $form['submits'] = array(
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $form['submits'][] = array('#type' => 'submit', '#value' => t('Submit'));
  if($edit['rid']){
    $form['submits'][] = array('#type' => 'button', '#value' => t('Delete'));
  }
  return drupal_get_form('sifr_rule', $form);
}

function sifr_rule_submit($form_id, $form){
  sifr_save_rule($form);
  return 'admin/settings/sifr';
}

function sifr_delete_confirm($rid){
  if (!($rule = sifr_load_rule($rid))){
    drupal_goto('admin/settings/sifr');
  }
  if($_POST['op'] == t('Confirm')){
    sifr_rule_delete($rid);
    drupal_goto('admin/settings/sifr');
  }
  return confirm_form('sifr_rule_delete', array(), t("Are you sure you want to delete the rule: "). $rule->name, 'admin/settings/sifr');
}

function sifr_fontdelete_confirm($fontfile = FALSE){
  if (!$fontfile){
    drupal_goto('admin/settings/sifr/manage');
  }
  else {
    $fontfile = urldecode($fontfile);
  }
  if($_POST['op'] == t('Confirm')){
    sifr_font_delete($fontfile);
    drupal_goto('admin/settings/sifr/manage');
  }
  return confirm_form('sifr_delete_font', array(), t("Are you sure you want to delete the file &quot;%fontfile&quot;?", array('%fontfile' => $fontfile)), 'admin/settings/sifr/manage');
}

/**
 * Scans both files/sifr and modules/sifr/sifr for .swf font files
 *
 * @return array
 * keyed array for select field
 */

function sifr_get_swfs(){
  // scan files/sifr
  $dir = file_create_path('sifr');
  $listings = file_scan_directory($dir, '.*\.(swf)', array('.', '..', 'CVS', '.svn'), 0, FALSE);
  foreach ($listings as $listing) {
    $selects[$listing->filename] = $listing->name;
  }
  // scan modules/sifr/sifr
  $dir = sifr_find_sifr();
  $listings = file_scan_directory($dir, '.*\.(swf)', array('.', '..', 'CVS', '.svn'), 0, FALSE);
  foreach ($listings as $listing) {
    $selects[$listing->filename] = $listing->name;
  }
  return $selects;
}

/**
 * Get list of rules from db
 *
 * @return
 * array of rule objects
 */
function sifr_get_rules(){
  $rules = array();
  $result = db_query('SELECT * FROM {sifr} ORDER BY weight');
  while($r = db_fetch_object($result)){
    $rules[$r->name] = $r; 
  }
  return $rules;
}

/**
 * Get an individual rule
 *
 * @return object
 * the rule
 */
function sifr_load_rule($rid){
  return db_fetch_object(db_query('SELECT * FROM {sifr} WHERE rid = %d', $rid));
}

/**
 * Save a rule into the db
 *
 * @param array $edit
 * the edit array from the rule add/edit form
 */
function sifr_save_rule($edit){
  $edit = (array)$edit;
  if($edit['rid']){
    db_query('DELETE FROM {sifr} WHERE rid = %d', $edit['rid']);
  }
  else {
    $edit['rid'] = db_next_id('sifr');
  }
  foreach($edit as $key => $val){
    if(in_array($key, _sifr_fields())){
      // only save keyed values
      if(!is_numeric($key)){
        if(is_numeric($val)){
          if(is_float(0+$val)){
            $valsubs[] = '%f';
          }
          else {
            $valsubs[] = '%d';
          }
        }
        else {
          $valsubs[] = '\'%s\'';
        }
        $vals[] = $val;
        $keys[] = $key;
      }
    }
  }
  $keys = implode(', ', $keys);
  $valsubs = implode(', ', $valsubs);
  db_query("INSERT INTO {sifr} ($keys) VALUES ($valsubs) ", $vals);
  drupal_set_message($edit['name'] .' '. t('saved.'));
}

function sifr_rule_delete($rid){
  db_query('DELETE FROM {sifr} WHERE rid = %d', $rid);
  drupal_set_message(t('Rule deleted.'));
}

function sifr_font_delete($fontfile){
  if(file_delete($fontfile)){
    drupal_set_message(t('File deleted.'));
  }
  else {
    drupal_set_message(t('There was a problem deleting the file.'), 'error');
  }
}

/**
 * Find the sIFR directory and save its location as a variable
 * 
 * This removes the need for admins to rename the sIFR directory
 * when they place it in the module directory
 * 
 * recurses the directory for this module to find the shallowest
 * file called sifr.js
 *
 * @return unknown
 */

function sifr_find_sifr(){
  $moddir = drupal_get_path('module', 'sifr');
  $files = file_scan_directory($moddir, 'sifr\.js', array('.', '..', 'CVS', '.svn'), 0, TRUE, 'filename', 1);
  // the first one is the shallowest, return that one
  $file = array_shift($files);
  $file->dir = substr($file->filename, 0, strlen($file->filename) - strlen($file->basename) - 1);
  variable_set('sifr_dir', $file->dir);
  return $file->dir ? $file->dir : FALSE;
}

function sifr_all_pages(){
  static $done;
  if (!$done){
    $sifrdir = variable_get('sifr_dir', FALSE);
    if (!$sifrdir){ // no variable set? scan the dir
      $sifrdir = str_replace(' ', "%20", sifr_find_sifr());
    }
    if(!$sifrdir){ // still can't find it? display an error
      drupal_set_message(t('The sIFR library is in not installed correctly. Please download from <a href="http://www.mikeindustries.com/sifr/">http://www.mikeindustries.com/sifr/</a> and place in Drupal\'s modules/sifr/ directory.'), 'error');
    }
    else {
      $path = $sifrdir .'/'; // convert spaces
      theme('add_style', 'sifr/sifr-screen.css', 'screen');
      theme('add_style', 'sifr/sifr-print.css', 'print');
      drupal_add_js($path .'sifr.js');
      drupal_set_html_head(sifr_render_rules_js());
    }
    $done = true;
  }
}

function sifr_version(){
  return str_replace(array('$RCSf'.'ile:', ',v', '$Re'.'vision: ', '$Da'.'te: ', '$'), '', '<p style="font-size:x-small">$RCSfile: sifr.module,v $ version: <b>$Revision: 1.7 $</b>, $Date: 2006/10/23 21:53:41 $</p>');
}

function sifr_render_rules_js(){
  $rules = array();
  foreach(sifr_get_rules() as $rule){
    $rules[] = sifr_render_rule_js($rule);
  }
  $output = sifr_wrap_rules($rules);
  return $output;
}

function sifr_render_rule_js($rule){
  $base = base_path();
  $fontpath = str_replace(' ', "%20", $base.$rule->font); // convert spaces
  //sIFR.replaceElement("h1", named({sFlashSrc: "./vandenkeere.swf", sColor: "#000", sCase: "upper"}));
  //$output .= "  sIFR.replaceElement(\"$rule->selector\", \"$base$rule->font\");\n";
  $padding = is_numeric($rule->paddingtop) ? ", nPaddingTop: $rule->paddingtop" : '';
  $padding .= is_numeric($rule->paddingright) ? ", nPaddingRight: $rule->paddingright" : '';
  $padding .= is_numeric($rule->paddingbottom) ? ", nPaddingBottom: $rule->paddingbottom" : '';
  $padding .= is_numeric($rule->paddingleft) ? ", nPaddingLeft: $rule->paddingleft" : ''; 
  $wsmode = $rule->transparent ? ", sWmode: 'transparent'" : '';
  $case = in_array($rule->lettercase,array('upper','lower')) ? ", sCase: \"$rule->lettercase\"" : '';
  if($rule->underline){
    $vars[] = 'underline=true';
  }
  if( in_array($rule->textalign,array('left','center','right'))){
    $vars[] = "textalign=$rule->textalign";
  }
  $flashvars = is_array($vars) ? ', sFlashVars: "'.join($vars, '&').'"' : '';
  //LukeM only show hover color if it has a set value
   if($rule->hovercolor != ''){
   	//$thover='sHoverColor: \"$rule->hovercolor\",';
   }
   else{
   	//$thover='';
   } 
  $output .= "  sIFR.replaceElement(\"$rule->selector\", named({sFlashSrc: \"$fontpath\",  sColor: \"$rule->color\", sLinkColor: \"$rule->linkcolor\",".$thover." sBgColor: \"$rule->bgcolor\" $padding$wsmode$case$flashvars}));\n";
  return $output;
}

function sifr_wrap_rules($rules){
  if (is_array($rules)){
    $output .= "<script type=\"text/javascript\">\n";
    $output .= "if(typeof sIFR == \"function\") {\n";
    $output .= implode("  ", $rules);
    $output .= "};\n";
    $output .= "</script>";
  }
  return $output;
}

function sifr_css_screen(){
  header("Content-type: text/css");
  print "/* These are standard sIFR styles... do not modify */

.sIFR-flash {
	visibility: visible !important;
	margin: 0;
}

.sIFR-replaced {
	visibility: visible !important;
}

span.sIFR-alternate {
	position: absolute;
	left: 0;
	top: 0;
	width: 0;
	height: 0;
	display: block;
	overflow: hidden;
}


/* These \"decoy\" styles are used to hide the browser text before it is replaced... the negative-letter spacing in this case is used to make the browser text metrics match up with the sIFR text metrics since the sIFR text in this example is so much narrower... your own settings may vary... any weird sizing issues you may run into are usually fixed by tweaking these decoy styles */

";

  foreach(sifr_get_rules() as $rule){
    $fontsize = trim($rule->fontsize) ? "font-size: $rule->fontsize;\n" : '';
    $letterspacing = trim($rule->letterspacing) ? "letter-spacing: $rule->letterspacing;\n" : '';
    print "
.sIFR-hasFlash $rule->selector {
  visibility: hidden;
  $fontsize  $letterspacing
}
";
  }

}

function sifr_css_print(){
  header("Content-type: text/css");
  print "/* This is the print stylesheet to hide the Flash headlines from the browser... regular browser text headlines will now print as normal */

.sIFR-flash, .sIFR-flash object, .sIFR-flash embed {
	display: none !important;
	height: 0;
	width: 0;
	position: absolute;
	overflow: hidden;
}

span.sIFR-alternate {
	visibility: visible !important;
	display: block !important;
	position: static !important;
	left: auto !important;
	top: auto !important;
}";
}

/**
 * Downloads files using applictation/octet-stream mime type 
 * Makes txt files download rather than appearing in browser
 * 
 * @param string $file
 * The file to be downloaded
 */

function sifr_octet_download($file){
  $filepath = sifr_find_sifr() .'/'. $file;
  if (is_file($filepath)){
    header('Content-type: application/octet-stream');
    ob_start();
    include $filepath;
    $contents = ob_get_contents();
    ob_end_clean();
    print $contents;
  }
  else {
    return t('File not found.');
  }
}

function _sifr_fields(){
  return array('rid', 'name', 'font', 'selector', 'color', 'linkcolor', 'hovercolor', 'bgcolor', 'transparent', 'weight', 'letterspacing', 'fontsize', 'paddingtop', 'paddingright', 'paddingbottom', 'paddingleft','textalign','underline','lettercase');
  
}