/**
 * Utility functions
 * 
 * @version $Id$
 * @author M.Olszewski
 * @since 27 Mar 2009
 * @copyright Copyright (c) 2009 M.Olszewski. All rights reserved.
 */

/**
 * Adds redirection to the page.
 * 
 * Redirection happens after specified delay (or 5 seconds if not specified), rendering the number of
 * seconds left till redirection if span identifier is given. 
 * 
 * @param url   Target URL of redirection.
 * @param delay Delay specifying how long page will be shown before redirection occur.
 * @param spanId Identifier of the <code>&lt;span&gt;</code> section that will render time left till
 * redirection.
 */
function addRedirection(url, delay, spanId)
{
  if (!url)
  {
    throw 'Fatal error: redirection URL not specified!';
  }
  
  delay = parseInt(delay);
  if (!delay)
  {
    delay = 5;
  }
  
  if (delay <= 0)
  {
    throw 'Fatal error: delay must be positive integer!';
  }
  
  
  if (spanId)
  {
    Event.observe(window, 'load', function redirect() {
      // input correct number of seconds at start
      Element.replace(spanId, '<span id="' + spanId + '">'  + delay + '</span>');
      
      new PeriodicalExecuter(function(pe) {
        if (delay > 1)
        {
          delay -= 1;
          Element.replace(spanId, '<span id="' + spanId + '">'  + delay + '</span>');
        }
        else
        {
          pe.stop();
          window.location.href = url;
        }
      }, 1);
    });
  }
  else
  {
    Event.observe(window, 'load', function redirect() {
      new PeriodicalExecuter(function(pe) {
          pe.stop();
          window.location.href = url;
      }, delay);
    });
  }
}

/**
 * Simple function changing style of all children of given element and selected by specified selector.
 * 
 * @param element Parent element.
 * @param selector Children selector.
 * @param style Style to change.
 */
function changeChildrenStyle(element, selector, style)
{
  var elm = $(element);
  var children = elm.select(selector);
  children.each(function(node) {
    node.setStyle(style);
  });
  
  return false;
}
