$(function() {
  var domain = $('body').data('domain');
  var site_id = $('body').data('site-id');
  var page_id = $('body').data('page-id');
  var parent_id = $('body').data('parent-id');
  var root_id = $('body').data('root-id');

  // ----- site preview
  // append preview params to all links, forms, etc
  $('body.preview a[href]').each(function() {
    leading_character = $(this).attr('href').indexOf('?') == -1 ? '?' : '&'
    $(this).attr('href', $(this).attr('href') + leading_character + 'preview=true&site_id=' + site_id);
  });
  $('body.preview form').each(function() {
    $(this).attr('action', $(this).attr('action') + '?preview=true&site_id=' + site_id);
  });
  // make all links to firm's site domain relative
  $('body.preview a[href*="'+ domain +'"]').each(function() {
    var relative_url = $(this).attr('href').replace('https://www.' + domain, '');
    $(this).attr('href', relative_url);
  });

  // -----  select current page in nav
  $('nav #page_' + root_id).parent().addClass('active');
  $('nav #subnav_page_' + page_id).parent().addClass('active');
  $('nav #subnav_page_' + parent_id).parent().addClass('active');

  // -----  nav select dropdown
  var nav_select = $('.nav_select select');
  if( nav_select.length )
  {
    nav_select.find('option[data-id=' + page_id + ']').attr('selected', 'selected');
    nav_select.live('change', function() {
      var $this = $(this);
      if( $this.find('option:selected').data('id') != page_id )
      {
        window.location = $this.val();
      }
    });
  }

  // ----- nest blog comments
  $('#comments article[data-parent-id!=""]').each(function() {
    var comment = $(this);
    var parent = $('#comments article[data-id="'+ $(this).data('parent-id') +'"]');
    var children_container = parent.find('> .children_container');
    if( children_container.length == 0 )
    {
      var children_container = parent.append('<div class="children_container"></div>').find('> .children_container');
    }
    comment.appendTo(children_container);
    comment.find('.new_comment_reply').remove();
  });
  
  // reply link path for top-level comments
  $('#comments article[data-parent-id=""]').each(function() {
    var comment = $(this);
    var reply_link = $(this).find('.new_comment_reply');
    reply_link.attr('href', reply_link.attr('href').replace('parent_id', comment.data('id')));
  });
  
  // ----- cancel reply
  $('.cancel_reply').live('click', function(e) {
    e.preventDefault();
    $('.replyBox').remove();
  });

  // -----  validate forms
  $('form').submit(function(e) {
    var errors = 0;
  	$(this).find('li.required').each(function() {
      // single line
  		if( $(this).hasClass('single_line_text') && $(this).find('input').val() == '' )
  		{
  			$(this).addClass('invalid_field');
  			errors++;
  		}
      // multi line
  		else if( $(this).hasClass('multi_line_text') && $(this).find('textarea').val() == '' )
  		{
  			$(this).addClass('invalid_field');
  			errors++;
  	  }
      // dropdown
  		else if( $(this).hasClass('dropdown_menu') && $(this).find('select').val() == '' )
  		{
  			$(this).addClass('invalid_field');
  			errors++;
  	  }
      // checkboxes
  		else if( $(this).hasClass('checkboxes') && $(this).find('input[type=checkbox]:checked').length == 0 )
  		{
  			$(this).addClass('invalid_field');
  			errors++;
  	  }
  	  else
  	  {
        // no errors, set to valid
  			$(this).removeClass('invalid_field');
  	  }
  	});
    // prompt if errors
  	if( errors > 0 )
  	{
  		e.preventDefault();
  		$(this).parent().find('.warning').fadeIn();
  		return false;
  	}
  });

  // -----  track outbound clicks
  $('a[href^=http]:not([href*="'+ window.location.hostname +'"])').live("click", function(e) {
    params = { authenticity_token: $('meta[name=csrf-token]').attr('content'), click: { url: this.href, site_id: site_id, page_id: page_id } };
    $.post("/clicks", params);
    if( $(this).attr('target') != '_blank' )
    {
      setTimeout('document.location = "' + this.href + '"', 1000);
    }
    else
    {
      setTimeout('window.open("' + this.href + '", "new")', 1000);
    }
    return false;
  });

  // -----  inserted image caption
  $('.insertion.image .caption').each(function() {
    // set captions width to that of the inserted img
    var caption = $(this);
    var image = caption.prev('img');
    caption.width( image.width() );
  });
  
  // ----- inserted widgets
  $('.widget.recommendations, .widget.case_results').each(function() {
    $(this).find('span.summary').jTruncate({length: 120});
  });
  

  // -----  embedded videos
  $('div.insertion.video[data-video-url]').each(function() {
    var fv = $(this).flareVideo();
    fv.load([
      {
        src:  $(this).data('video-url'),
        type: 'video/mp4'
      },
    ]);
  });
});

$(window).load(function() {
  // -----  grid
  $('ul.grid > li').css({'overflow': 'hidden'});
  var currentTallest = 0,
       currentRowStart = 0,
       rowDivs = new Array(),
       $el,
       topPosition = 0;

   $('ul.grid > li').each(function() {

     $el = $(this);
     topPostion = $el.position().top;
   
     if (currentRowStart != topPostion) {

       // we just came to a new row.  Set all the heights on the completed row
       for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
         rowDivs[currentDiv].height(currentTallest);
       }

       // set the variables for the new row
       rowDivs.length = 0; // empty the array
       currentRowStart = topPostion;
       currentTallest = $el.height();
       rowDivs.push($el);

     } else {

       // another div on the current row.  Add it to the list and check if it's taller
       rowDivs.push($el);
       currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);

    }
   
    // do the last row
     for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
       rowDivs[currentDiv].height(currentTallest);
     }
   
   });
});