/**
 * Processes a template file by inserting the provided data.  Tokens in the template
 * use the format '{{name}}' where 'name' refers to a field name in the data array.
 *
 * Example:
 *   pData      = { field1: 'Some value', field2: 'Another value' }
 *   pTemplate  = '<h3>{{field1}}</h3><p>{{field2}}</p>'
 *   result     = '<h3>Some value</h3><p>Another value</p>'
 */
function processTemplate ( pTemplate, pData ) {
  var html = pTemplate;
  for( var i in pData ) {
    var regex = new RegExp( '\{\{' + i + '\}\}', 'g' );
    html = html.replace( regex, pData[i] );
  }
  return html;
}

function carouselDynamicItemLoadCallback ( pCarousel, pState ) {

  // figure out the root name for all the variable references
  var carouselName = pCarousel.list.attr( 'id' );
  carouselName = carouselName.replace( /\-/, '' );

  if( eval( 'typeof ' + carouselName + 'ItemList == "undefined"' ) ) {
    alert( 'no ItemList defined for carousel \'' + carouselName + '\'' );
    return;
  }

  for( var i = pCarousel.first; i <= pCarousel.last; i++ ) {

    // if the item is already in the carousel, go to the next one
    if( pCarousel.has( i ) ) {
      continue;
    }

    // if we're out of range of the list, stop iterating
    if( i > eval( carouselName + 'ItemList.length' ) ) {
      break;
    }

    // if a function named <carouselname>GetItemHTML exists, use it for getting the html
    var html = ''
    if( eval( 'typeof ' + carouselName + 'GetItemHTML == \'function\'' ) ) {
      html = eval( carouselName + 'GetItemHTML( ' + carouselName + 'ItemList[i-1] )' );
    }
    // if a template is defined for the carousel, use it
    else if( eval( 'typeof ' + carouselName + 'Template != "undefined"' ) ) {
      var itemData = eval( carouselName + 'ItemList[i-1]' );
      var template = eval( carouselName + 'Template' );
      html = processTemplate( template, itemData );
    }
    // if no template is defined, generate some default html
    else {
      html = '<div>no GetItemHTML function defined and no template found for carousel \'' + carouselName + '\'</div>';
    }

    var item = jQuery( html ).get( 0 );

    // Apply thickbox
    tb_init( item );

    pCarousel.add( i, item );
  }
}

/**
 * Initialize all 'tbutton' images on the page to have an over action to replace the
 * image source with the "over" image when the mouse enters and to return to the
 * original image when the mouse leaves.  This works by replacing the '_on' or
 * '_off' in the original image name with '_over'.
 */
function initializeButtons ( ) {
  jQuery( '.tbutton' ).each( function( ) {
    if( this.src != null ) {
      this.srcOrig = this.src;
      this.onmouseover = function ( ) {
        this.src = this.src.replace( /_on/, "_over" );
        this.src = this.src.replace( /_off/, "_over" );
      };
      this.onmouseout = function ( ) {
        this.src = this.srcOrig;
      }
    }
  } );
}
