﻿$.fn.reverse = [].reverse;

$(function () {
  function fitToWidth() {
    $( ".fit-to-width" ).each( function(){
      var width = $( this ).width();
      $( this ).find( "img" ).each( function(){
        var name = $( this ).attr( "data-id" );
        var url = "/Image/Library/" + name + "/" + width
        if( $( this ).width() != width ) {
          $( this ).attr( "src", url );
        }
      });
    });
  }
  
  function fitToHeight() {
    $( ".fit-to-height" ).each( function(){
      var height = $( this ).height();
      var liHeight = $( this ).find( ".copy-image" ).first().height();
      var parentTop = $( "#content .columns .main" ).first().offset().top;
      var top = $( this ).offset().top;
      var offset = top - parentTop;      
      
      var parentHeight = $( "#content .columns .main .paddingWrapper" ).first().height() - offset;
      
      var imageCount = $( this ).find( ".copy-image" ).length;  
      var preferredCount = Math.ceil( parentHeight / liHeight );

      if( preferredCount > imageCount ) {
        while( imageCount < preferredCount ) {
          $( this ).append( $( this ).find( ".copy-image" ).clone() );
          imageCount = $( this ).find( ".copy-image" ).length;
        }
      }
      
      $( this ).find( ".copy-image" ).each( function( index ) {
        if( index >= preferredCount ) $( this ).hide();
      } );      
    });
  }
  
  $( "blockquote, .italics-are-quotes em" ).each( function(){
    $( this ).prepend( '<span class="open-quote">“</span>' );
    $( this ).append( '<span class="close-quote">”</span>' );
  });
  
  $( ".text li" ).each( function() {
    $( this ).addClass( "bullets" );
    $( this ).html( "<span>" + $( this ).html() + "</span>" );
  });
  
  $( ".text.credential" ).each( function() {
    $( this ).find( "p" ).prevUntil( "> strong" ).reverse().wrapAll( '<div class="balloon" />' );
  });
  
  $( ".italics-are-quotes p > em" ).wrap( '<div class="balloon" />' );
  
  $( ".balloon" ).append( '<div class="shim" />' );
   
  $( ".left-column-images a" ).css({cursor:"default"}).removeAttr( "href" ).removeAttr( "rel" );
  $( ".column-header-image a" ).removeAttr( "rel" ).attr( "href", "/" );
  
  $( ".toggle-next" ).each( function() {
    $( this ).html( $( this ).html() + " <em>View More &darr;</em>" );
    $( this ).css( { cursor: "pointer" } );
    $( this ).next().hide();
    $( this ).click( function() {
      $( this ).next().toggle( 200 );
    } );
  });
  
  //fitToHeight();  
  fitToWidth();
  
  ResizeEvents.eventElement.bind(
    'x-initial-sizes x-text-resize x-window-resize x-window-width-resize x-window-height-resize',
    function( eventObj, emPixels, textHeight, windowWidth, windowHeight ){
      //fitToHeight();
      //fitToWidth();
    }
  );
});
