/*
  Formium.com | Zephyr-WebDesign.com 2010
*/

var LOADING_START_TIME  = null;
var LOADING_PATH        = null;

var present_location_hash = '';
var current_main_panel_index = 0;
var current_sub_panel = '';
var completed_slide_count = 0;
var slideshow_resize_timeout = null;
var portfolio_slide_image_width = 0;
var portfolio_slide_margin_width = 0;
var current_portfolio_slide_index = 0;
var loaded_sub_panels = {};
var home_slide_idx = [];
var min_heights = {
  'contact-bg-wrapper':               1035,
  'about-why-formium-bg-wrapper':     650,
  'about-what-we-do-bg-wrapper':      885,
  'work-see-our-work-bg-wrapper':     750,
  'about-why-not-formium-bg-wrapper': 850,
  'about-how-we-work-bg-wrapper':     850,
  'about-who-we-are-bg-wrapper':      850,
  'clients-bg-wrapper':               850,
  'work-portfolio-bg-wrapper':        850
};
var white_formium_logo_hrefs = {
  'work/see-all-work': 1,
  'contact': 1
};
var main_panels = {
  home:     0,
  about:    1,
  clients:  2,
  work:     3,
  contact:  4,
  news:     5
};
// this will be true when we're ready to hide the initial overlay
var initial_panel_is_set = false;
var archive_timeout = null;

if (typeof console == 'undefined') {
  window.console = { log: function(){} };
}

$(window).error(report_error);

$(document).ready(function(){
  setup_navigation_links();

  sort_home_panel_slideshow_images();

  set_panel_sizes();

  setup_resize_event();

  fade_out_initial_overlay();

  setInterval(check_location, 50);

});

function sort_home_panel_slideshow_images() {
  var idx = $.cookie('home-panel-slideshow-first-image-index');

//  console.log('cookie: ' + idx);

  var slide_count = $('div#home-slideshow img.background').length;

  if (!/^\d$/.test(idx) || idx > slide_count) {
    idx = 0;
  }

//  console.log('cookie: ' + idx);

  for (var i = 0; i < idx; i++) {
    $('div#home-slideshow').append( $('div#home-bg-wrapper-' + i) );
  }

  // lower the initial overlay when the second slide is loaded
  //  but only if we're looking for the home panel
  var $second_slide = $('div#home-slideshow img.background').eq(1);
  $second_slide.load(function(){
    console.log('second slide loaded');

    // we're starting up and wanting to see the home panel
    if ((present_location_hash == '' || present_location_hash == '#home') && (location.href.replace(/^[^#]+/, '') == '' || location.href.replace(/^[^#]+/, '') == '#home')) {
      initial_panel_is_set = true;
    }
  });

  var $window = $(window);
  var window_width = $window.width();
  $('div#home-slideshow').
    width( window_width * $('div#home-slideshow img.background').size() ).
    height( $window.height() );
  $('div#home-slideshow div.bg-wrapper').each(function(i){
    var $this = $(this);
    var div_id = $this.attr('id').replace(/\D/g, '');
    console.log('i: ' + i + '; div_id: ' + div_id);
    home_slide_idx[ div_id ] = i;
    $this.css('left', i * window_width);
  });

  var next_val = parseInt(idx, 10) + 1;
  slide_count--;
  if (next_val > slide_count) {
    next_val = 0;
  }

//  console.log('cookie: ' + next_val);

  $.cookie('home-panel-slideshow-first-image-index', next_val, { expires: 60 * 60 * 24 * 365 }); // 1y

  // force the reloading of the second slide in case somehow it's been loaded already
  var src2 = $second_slide.attr('src');
  $second_slide.attr('src', '');
  $second_slide.attr('src', src2);

  // force loading of the page if the second slide never loads - 5 seconds
  setTimeout(function(){ initial_panel_is_set = true; }, 5000);

}

function home_slideshow_do_slide() {

  var old_left = parseInt($('div#home-slideshow').css('left'), 10);
  var new_left = old_left - $(window).width();
  var slide_count = $('div#home-slideshow img.background').length;
  slide_count--;

//  console.log('new_left: ' + new_left);

  if (completed_slide_count < slide_count) {
    completed_slide_count++;
    $('div#home-slideshow').animate({
      left: new_left
    }, 900, 'easeout', function(){
      setTimeout(home_slideshow_do_slide, 3000);
    });
  }

}

function fade_out_initial_overlay() {

  if (initial_panel_is_set) {
    $('div#initial-overlay').fadeTo(1000, 0, function(){
      $('div#initial-overlay').hide().css('background-color', 'white');
      $('#loading-gif').attr('src', 'img/ajax-loader.gif');
      $('div#nav, div#logo').css('zIndex', 20);
      setTimeout(home_slideshow_do_slide, 3000);
    });
  }
  else {
    setTimeout(fade_out_initial_overlay, 25);
  }

}

function set_panel_sizes() {
  var $window       = $(window);
  var window_width  = $window.width();
  var window_height = $window.height();

  if (!initial_panel_is_set) {
    $('img#loading-gif').css({
      top:  (window_height / 2) - 12,
      left: (window_width  / 2) - 12
    }).show();
  }

  // all "background" images must be 1920x1200
  var BG_IMG_WIDTH  = 1920;
  var BG_IMG_HEIGHT = 1200;

  var screen_aspect_ratio = window_width / window_height;
  var image_aspect_ratio  = BG_IMG_WIDTH / BG_IMG_HEIGHT;
  var overflow_sides      = screen_aspect_ratio < image_aspect_ratio;
  var size_data           = {
    window_width:         window_width,
    window_height:        window_height,
    screen_aspect_ratio:  screen_aspect_ratio,
    image_aspect_ratio:   image_aspect_ratio,
    overflow_sides:       overflow_sides
  };

  var image_size = set_background_image_sizes(size_data);

  // needed for left-content sub-panels
  size_data.image_width   = image_size.width;
  size_data.image_height  = image_size.height;

  // set panel sizes + positions
  $('div#panels-container').width(window_width).height(window_height * $('div#panels-container > div').size());
//  $('div.panel, div.sub-panel, div.sub-panel > div.not(.left-sub-panel-container)').width(window_width).height(window_height);
  $('div.panel').width(window_width).height(window_height);
  $('div.sub-panel, div.sub-panel > div.not(.left-sub-panel-container)').width(window_width);
  set_panel_positions(size_data);

  // hack
//  $('#about-panel .blog-container .header-image, #about-panel .blog-container .header-message').css({
//    left: Math.round(( size_data.window_width / 2 ) - ( 902 / 2 )),
//    bottom: size_data.window_height - 380
//  });

  return Math.min(image_size.height, window_height);
}

function set_background_image_sizes(size_data) {
  var window_width  = size_data.window_width;
  var window_height = size_data.window_height;

  /**
   * do the home slides as a separate thing
   * they need left values as well
   */
  $('#home-panel div.bg-wrapper').each(function(){
    var $this = $(this);
    if (/^home-bg-wrapper-(\d)$/.test($this.attr('id')) ) {
      $this.css('left', window_width * home_slide_idx[RegExp.$1] ).height(window_height).width(window_width);

      var image_aspect_ratio = 1920 / 1200;
      var overflow_right = ( window_width / window_height ) < image_aspect_ratio;
      if (overflow_right) {
        var image_height  = window_height;
        var image_width   = image_aspect_ratio * image_height;
      }
      // overflow bottom
      else {
        var image_width   = window_width;
        var image_height  = window_width / image_aspect_ratio;
      }


      $this.find('img.background').css({
        width:  image_width,
        height: image_height,
        left: 0
      });
    }
  });


  var div_width = window_width;

  $('div.panel:not(#home-panel) img.background, img.tiled-background').
    parent('div.bg-wrapper').
    width(Math.round(window_width)).
    each(function(){

      var $this = $(this);

      /**
       * now determine the sizes of the normal background images, which rely on the height of the div,
       * which may be taller than the height of the window
       */
      var div_height = Math.round( Math.max( window_height, min_heights[$this.attr('id')] ) );

      if ($this.attr('id') == 'about-incubator-bg-wrapper') {
        var $blog_content = $('#about-panel .blog-content');
        div_height = $blog_content.offset().top + $blog_content.height() + $('#about-panel').scrollTop() + 50;
        div_height = Math.max(div_height, window_height);
      }

      if ($this.attr('id') == 'news-bg-wrapper') {
        var $blog_content = $('#news-panel .blog-content');
        div_height = $blog_content.offset().top + $blog_content.height() + $('#news-panel').scrollTop() + 50;
        if (div_height == 50) {
          var $news_wrapper = $this;
          setTimeout(function(){
            var $blog_content = $('#news-panel .blog-content');
            var div_height = $blog_content.offset().top + $blog_content.height() + $('#news-panel').scrollTop() + 50;
            if (div_height == 50) {
              setTimeout(arguments.callee, 10);
            }
            div_height = Math.max(div_height, $(window).height());

            $news_wrapper.height(div_height);

            var iw = 1920;
            var ih = 1200;

            if (size_data.window_width > iw) {
              iw = size_data.window_width;
              ih = 1200 * ( iw / 1920 );
            }

            $news_wrapper.find('img').width(iw).height(ih);
          }, 10);
        }
        div_height = Math.max(div_height, $(window).height());
      }

      if ($this.attr('id') == 'news-past-bg-wrapper') {
        var $blog_content = $('#news-panel div[id^=news-sub-].sub-panel .blog-content');
        div_height = $blog_content.offset().top + $blog_content.height() + $('#news-panel').scrollTop() + 50;
        div_height = Math.max(div_height, window_height);
      }

      $this.height(div_height);

      /**
       * now set the sizes of the blog bg images - the rules are different
       * because these are tiled - they do not rely on the height of the div
       */
      if ($this.attr('id') == 'about-incubator-bg-wrapper') {

        var iw = 1920;
        var ih = 1200;

        if (size_data.window_width > iw) {
          iw = size_data.window_width;
          ih = 1200 * ( iw / 1920 );
        }

        $this.find('img').width(iw).height(ih);

        return;
      }

      if ($this.attr('id') == 'news-bg-wrapper' || $this.attr('id') == 'news-past-bg-wrapper') {

        var iw = 1920;
        var ih = 1200;

        if (size_data.window_width > iw) {
          iw = size_data.window_width;
          ih = 1200 * ( iw / 1920 );
        }

        $this.find('img').width(iw).height(ih);

        return;
      }

      /*
       * now we know the width and height of the div
       * we can find out if there's overflow to the right or bottom
       */

      var image_aspect_ratio  = 1920 / 1200;
      var div_aspect_ratio    = div_width / div_height;
      var overflow_right      = div_aspect_ratio < image_aspect_ratio;

      if (overflow_right) {
        var image_height  = div_height;
        var image_width   = image_aspect_ratio * image_height;
      }
      // overflow bottom
      else {
        var image_width   = div_width;
        var image_height  = div_width / image_aspect_ratio;
      }

      $this.find('img.background').width(Math.round(image_width)).height(Math.round(image_height));

    }
  );

  return {
    width:  window_width,
    height: window_height
  };
}

function XX_GOOD_set_background_image_sizes(size_data) {
  var image_w = size_data.window_width;
  var image_h = size_data.window_height;

  if (size_data.overflow_sides) {
    image_w = size_data.image_aspect_ratio * size_data.window_height;
  }
  // overflow bottom
//  else {
//    image_h = ( 1 / size_data.image_aspect_ratio ) * size_data.window_width;
//  }

  $('div.panel img.background, img.tiled-background').parent('div.bg-wrapper').width(Math.round(size_data.window_width)).each(function(){
    var $this = $(this);
    var height = Math.round( Math.max( image_h, min_heights[$this.attr('id')] ) );

    if ($this.attr('id') == 'about-incubator-bg-wrapper') {
      var $blog_content = $('#about-panel .blog-content');
      height = $blog_content.offset().top + $blog_content.height() + $('#about-panel').scrollTop() + 50;
    }

    if ($this.attr('id') == 'news-bg-wrapper') {
      var $blog_content = $('#news-panel .blog-content');
      height = $blog_content.offset().top + $blog_content.height() + + $('#news-panel').scrollTop() + 50;
    }

    if ($this.attr('id') == 'news-past-bg-wrapper') {
      var $blog_content = $('#news-panel div[id^=news-sub-].sub-panel .blog-content');
      height = $blog_content.offset().top + $blog_content.height() + + $('#news-panel').scrollTop() + 50;
    }

    $this.height(height);

    // now set the sizes of the blog bg images - the rules are different
    // because these are tiled
    if ($this.attr('id') == 'about-incubator-bg-wrapper') {

      var iw = 1920;
      var ih = 1200;

      if (size_data.window_width > iw) {
        iw = size_data.window_width;
        ih = 1200 * ( iw / 1920 );
      }

      $this.find('img').width(iw).height(ih);

      return;
    }

    if ($this.attr('id') == 'news-bg-wrapper' || $this.attr('id') == 'news-past-bg-wrapper') {

      var iw = 1920;
      var ih = 1200;

      if (size_data.window_width > iw) {
        iw = size_data.window_width;
        ih = 1200 * ( iw / 1920 );
      }

      $this.find('img').width(iw).height(ih);

      return;
    }


    var i_w = image_w;
    var i_h = height;

    var BG_IMG_WIDTH  = 1920;
    var BG_IMG_HEIGHT = 1200;

    var div_aspect_ratio    = image_w / height;
    var image_aspect_ratio  = BG_IMG_WIDTH / BG_IMG_HEIGHT;
    var overflow_sides      = div_aspect_ratio < image_aspect_ratio;

    if (overflow_sides) {
  //    i_w = size_data.image_aspect_ratio * size_data.window_height;
      i_w = image_aspect_ratio * height;
    }
    // overflow top and bottom
    else {
  //    i_h = ( 1 / size_data.image_aspect_ratio ) * size_data.window_width;
      i_h = ( 1 / image_aspect_ratio ) * image_w;
    }

    $('div.panel img.background').width(Math.round(i_w)).height(Math.round(i_h));

  });

  // meaningless, really
  return { // really the wrapper size
    height: image_h,
    width:  image_w
  };
}

function XXset_background_image_sizes(size_data) {
  var image_w = size_data.window_width;
  var image_h = size_data.window_height;

  if (size_data.overflow_sides) {
    image_w = size_data.image_aspect_ratio * size_data.window_height;
  }
  // overflow top and bottom
  else {
    image_h = ( 1 / size_data.image_aspect_ratio ) * size_data.window_width;
  }

  $('div.panel img.background').width(Math.round(image_w)).height(Math.round(image_h));

  return {
    height: image_h,
    width:  image_w
  };
}

function set_about_sub_panel_sizes(size_data) {

  $('#about-panel .left-header').height(125).width(665);
//  $('#about-panel .white-stripe').height('auto');
  var $headline = $('#about-panel #about-sub-why-not-formium .white-stripe img');
  if ($headline.size() > 0) {
    var $table = $('#about-panel #about-sub-why-not-formium table');
    $table.css('margin-left', $headline.offset().left );
  }

  $('#about-panel .left-side-mask').height();

  // incubator loaded?
  if ($('#about-panel .blog-container').size() > 0) {

    var HEADER_IMAGE_HEIGHT = 380;

//    $('#about-panel .blog-container').css({
//      height: size_data.window_height
//      left: Math.round(( size_data.window_width / 2 ) - ( 902 / 2 ))
//    }).height(size_data.window_height);
//    $('#about-panel .blog-wrapper').css({
//      height: size_data.window_height - HEADER_IMAGE_HEIGHT
//      left: Math.round(( size_data.window_width / 2 ) - ( 902 / 2 ))
//    });
//    $('#about-panel .blog-content').css({
//      height: size_data.window_height - HEADER_IMAGE_HEIGHT - 30
//    });
//    $('#about-panel .blog-container .header-image, #about-panel .blog-container .header-message').css({
//      left: Math.round(( size_data.window_width / 2 ) - ( 902 / 2 )),
//      bottom: size_data.window_height - HEADER_IMAGE_HEIGHT
//    });
//    $('#about-panel .scroll-pane').width(870);
//    $('#about-panel .blog-content').height(size_data.window_height - HEADER_IMAGE_HEIGHT - 30).jScrollPane();
  }

}

function set_panel_positions(size_data) {

  $('img#loading-gif').css({
    top:  (size_data.window_height/ 2) - 12,
    left: (size_data.window_width / 2) - 12
  });

  $('div#about-panel').css({
    top: size_data.window_height
  });
  set_about_or_work_panel_sizes('about', size_data);
  set_about_sub_panel_sizes(size_data);


  $('div#clients-panel').css({
    top: size_data.window_height * 2
  });
  set_clients_panel_sizes(size_data);

  $('div#work-panel').css({
    top: size_data.window_height * 3
  });
  set_about_or_work_panel_sizes('work', size_data);
  set_portfolio_panel_sizes(size_data);
  set_see_all_work_panel_sizes(size_data);

  $('div#contact-panel').css({
    top: size_data.window_height * 4
  });
  $('div#news-panel').css({
    top: size_data.window_height * 5
  });
  set_news_panel_sizes(size_data);
}

function set_clients_panel_sizes(size_data) {
/*
  var $clients_list = $('#clients-list');
  $clients_list.css({
    top: 259 + ( 250 - ( $clients_list.height() / 2 ) ),
    left: ( size_data.window_width / 2 ) - ( $clients_list.width() / 2 )
  });
*/
//  var width = Math.max( size_data.window_width, 1920 );
//  var left  = width < 1920 ? 0 : width - 860;
  $('img#clients-white-stripe').width(size_data.window_width).css('left', 0);
  var $clt = $('#clients-list-text');
  $clt.width(size_data.window_width).css('left', 0);

  var $clients = $('#clients-list-text div');
  var clients_list_length = $clients.length;
  var num_steps = Math.round(clients_list_length / 2);
  for (var i = 0; i < clients_list_length; i = i + 2) {
    var $first = $clients.eq(i);
    $first.css('float', 'right');
    var mr = size_data.window_width / 2;
    mr -= ( (clients_list_length/2) - i ) * 4;
    $first.css('margin-right', size_data.window_width - mr + 14);
    if (i + 1 < clients_list_length) {
      var $second = $clients.eq(i + 1);
      $second.css('float', 'left');
      $second.css('margin-left', mr + 14);
    }
  }

  // set the position of #clients-list-text
  $clt.css({
    top:  509 - ( $clt.height() / 2 )
  });
/*
  var $clients_list = $('#clients-list');
  $clients_list.css({
    top: 259 + ( 250 - ( $clients_list.height() / 2 ) ),
    left: ( size_data.window_width / 2 ) - ( $clients_list.width() / 2 )
  });

//  var width = Math.max( size_data.window_width, 1920 );
//  var left  = width < 1920 ? 0 : width - 860;
  $('img#clients-white-stripe').width(size_data.window_width).css('left', 0);
*/
}

function set_news_panel_sizes(size_data) {

  var HEADER_IMAGE_HEIGHT = 262;

//  $('#news-panel .blog-container').css({
//    height: size_data.window_height
//    left: Math.round(( size_data.window_width / 2 ) - ( 902 / 2 ))
//  }).height(size_data.window_height);
//  $('#news-panel .blog-wrapper').css({
//    height: size_data.window_height - HEADER_IMAGE_HEIGHT
//    left: 0
//  });
//  $('#news-panel .blog-content').css({
//    height: size_data.window_height - HEADER_IMAGE_HEIGHT - 30
//  });
//  $('#news-panel .blog-container .header-image, .blog-container .header-message').css({
//    left: Math.round(( size_data.window_width / 2 ) - ( 902 / 2 )),
//    bottom: size_data.window_height - HEADER_IMAGE_HEIGHT
//  });
//  $('#news-panel .scroll-pane').width(870);
//  $('#news-panel .blog-content').height(size_data.window_height - HEADER_IMAGE_HEIGHT - 30).jScrollPane();
}

function set_about_or_work_panel_sizes(panel_name, size_data) {

  // first, we need to calculate whether we're going to overlfow the sides or the top/bottom
  var PADDING_TOP             = 201;
  var DEFAULT_CONTENT_WIDTH   = 1507;
  var DEFAULT_CONTENT_HEIGHT  = 754;
  var usable_screen_height        = size_data.window_height - PADDING_TOP;
  var usable_screen_aspect_ratio  = size_data.window_width / usable_screen_height;
  var content_aspect_ratio        = DEFAULT_CONTENT_WIDTH / DEFAULT_CONTENT_HEIGHT;
  var fill_width                  = true; // usable_screen_aspect_ratio < content_aspect_ratio;

  var DEFAULT_CONTAINER_LEFT    = 216;
  var DEFAULT_CONTAINER_WIDTH   = 1488;
  var DEFAULT_CONTAINER_HEIGHT  = 734;
  var percent_size = fill_width ?
        .78 * size_data.window_width  / DEFAULT_CONTAINER_WIDTH
      : .75 * usable_screen_height    / DEFAULT_CONTAINER_HEIGHT;

  // set containing div height, width, and position
  var width = Math.round(percent_size * DEFAULT_CONTAINER_WIDTH);
  $('div#' + panel_name + '-container').css({
    top:    PADDING_TOP,
    left:   Math.round((size_data.window_width - width) / 2) - 13,
    width:  width,
    height: Math.round(percent_size * DEFAULT_CONTAINER_HEIGHT)
  });

  // set sub div height, and width
  var DEFAULT_DIV_WIDTH       = 468;
  var DEFAULT_DIV_HEIGHT      = 346;
  var image_holder_div_width  = Math.round(percent_size * DEFAULT_DIV_WIDTH);
  var image_holder_div_height = Math.round(percent_size * DEFAULT_DIV_HEIGHT);
  $('#' + panel_name + '-container div.image-holder').css({
    width:  image_holder_div_width,
    height: image_holder_div_height
  })

  // set sub image position, height, and width
  var DEFAULT_IMG_WIDTH   = 468;
  var DEFAULT_IMG_HEIGHT  = 346;
  var image_width  = Math.round(percent_size * DEFAULT_IMG_WIDTH);
  var image_height = Math.round(percent_size * DEFAULT_IMG_HEIGHT);
  $('#' + panel_name + '-container div.image-holder img.sub').css({
    width:  image_width,
    height: image_height
  });

  // position of sub divs
  var DEFAULT_MARGIN_WIDTH    = 51;
  var DEFAULT_MARGIN_HEIGHT   = 59;
  var margin_width            = Math.round(percent_size * DEFAULT_MARGIN_WIDTH);
  var margin_height           = Math.round(percent_size * DEFAULT_MARGIN_HEIGHT);
  var second_column_left  = image_holder_div_width + margin_width;
  var third_column_left   = 2 * second_column_left;
  var second_row_top      = image_holder_div_height + margin_height;
  $('#' + panel_name + '-container div#' + panel_name + '-holder-1').css({ top: 0,              left: 0                  });
  $('#' + panel_name + '-container div#' + panel_name + '-holder-2').css({ top: 0,              left: second_column_left });
  $('#' + panel_name + '-container div#' + panel_name + '-holder-3').css({ top: 0,              left: third_column_left  });
  $('#' + panel_name + '-container div#' + panel_name + '-holder-4').css({ top: second_row_top, left: 0                  });
  $('#' + panel_name + '-container div#' + panel_name + '-holder-5').css({ top: second_row_top, left: second_column_left });
  $('#' + panel_name + '-container div#' + panel_name + '-holder-6').css({ top: second_row_top, left: third_column_left  });

  // set box image margin-top
  $('div#' + panel_name + '-panel img.black-box, div#' + panel_name + '-panel span.black-box-div').css({top: Math.max((image_height / 2) - 50, 0)});

  if (panel_name == 'work') {
    var $see_all_work_popover = $('#see-all-work-popover');
    $see_all_work_popover.css({
      top: 0,
      left: Math.round((size_data.window_width - width) / 2),
      width: Math.max(third_column_left - margin_width - 13, 512),
      height: 201 + ( ( ( image_height / 2 ) - 50 ) / 2 )
    });
    $('#see-all-work-popover-background').css({
      top: 0,
      left: 0,
      width: Math.max(third_column_left - margin_width - 14, 511),
      height: 201 + ( ( ( image_height / 2 ) - 50 ) / 2 )
    });
    var $all_work_links = $('#all-work-links');
    $all_work_links.css({
      left: ($see_all_work_popover.width() - $all_work_links.width() ) / 2,
      top: ($see_all_work_popover.height() - $all_work_links.height() ) / 2
    });

    var left = $('#work-panel img.sub').offset().left;
    if (left != 0) {
      $('#work-see-our-work-link').css('left', left + 2 );
    }
  }
}

/* if the portfolio panel is loaded */
function set_portfolio_panel_sizes(size_data) {
  var portfolio_panel = $('#work-sub-portfolio');

  if (portfolio_panel.size() > 0) { // we are loaded

    // set slide content in controls div
    var new_slide_content     = $('#portfolio-slide-content-1').html();
    $('div.portfolio-content').html( new_slide_content );

    // set slides left px
    var $slides = portfolio_panel.find('.portfolio-slide');
    var slide_count = $slides.size();
    for (var i = 0; i < slide_count; i++) {
      $slides.eq(i).css({
        left:   portfolio_slide_left_pixels($slides, i)
      });
    }

  }
}

function portfolio_slide_left_pixels($slides, idx) {

  var MARGIN_PIXELS = 115;
  var left = 79; // initial left margin for the first slide

  for (var i = 0; i < idx; i++) {
    left += parseInt($slides.eq(i).width(), 10) + MARGIN_PIXELS;
  }

  return left;
}

/* if the see_all_work panel is loaded */
function set_see_all_work_panel_sizes(size_data) {
  var see_all_work_panel = $('#work-sub-see-all-work');

  if (see_all_work_panel.size() > 0) { // we are loaded

    $('#work-panel #by-type-panel > div').css(
      'padding-left', $('#work-panel li.by-type').offset().left - $('#work-panel .left-sub-panel-container').offset().left
    );
/*
    var LEFT_PANEL_MIN_WIDTH        = 392;
    var LEFT_SIDE_PERCENT           = .44;
    var RIGHT_HEADER_MARGIN_PIXELS  = 78;
    var LEFT_HEADER_MARGIN_PIXELS   = 137;
    var left_header_width = Math.round( ( size_data.image_width * LEFT_SIDE_PERCENT) - ( RIGHT_HEADER_MARGIN_PIXELS + LEFT_HEADER_MARGIN_PIXELS ));
    see_all_work_panel.find('div.left-header').width(left_header_width).height(125);
    see_all_work_panel.find('div.left-sub-panel-content').width(left_header_width + RIGHT_HEADER_MARGIN_PIXELS);
    see_all_work_panel.find('div.left-sub-panel-container').width(left_header_width + RIGHT_HEADER_MARGIN_PIXELS);
*/
  }

}

function work_sub_all_work_show_by(what) {

  var other = what == 'client' ? 'type' : 'client';

  if ($('#work-panel #by-' + what  + '-panel:visible').size() > 0) {
    return;
  }

  $('#work-panel li.by-' + other).removeClass('active');
  $('#work-panel li.by-' + what).addClass('active');

  $('#work-panel #by-' + other + '-panel').fadeTo(450, 0, function(){
    $('#work-panel #by-' + other + '-panel').hide();
    $('#work-panel #by-' + what  + '-panel').fadeTo(450, 1);
  })

}

function show_portfolio_slide(idx, quick) {

  var portfolio_slides = $('div#work-panel div.portfolio-slides');

  if (portfolio_slides.is(':animated')) {
    return;
  }

  var $slides   = portfolio_slides.find('.portfolio-slide');
  var new_left  = parseInt($slides.eq(idx).css('left'), 10) - 79; // left margin

  var duration = quick ? 0 : 900;
  portfolio_slides.animate({
    left: - new_left
  }, duration, 'easeout');

  current_portfolio_slide_index = idx;

  /* change slide content? */
  var slide_content_div     = $('div.portfolio-content');
  var current_slide_content = slide_content_div.html();
  var new_slide_content     = $('#portfolio-slide-content-' + (idx + 1)).html();

  if (current_slide_content != new_slide_content) {

    slide_content_div.fadeOut(450, function(){
      slide_content_div.html( new_slide_content ).fadeIn(450);
    });

  }
}

function portfolio_arrow_left() {
  var portfolio_slides = $('div#work-panel div.portfolio-slides');

  if (portfolio_slides.is(':animated')) {
    return;
  }

  var $slides = portfolio_slides.find('.portfolio-slide');
  if (current_portfolio_slide_index != 0) {
    show_portfolio_slide( current_portfolio_slide_index - 1 );
  }
  else {
    var main_panel_name = current_main_panel_name();
    var $links = $('#work-panel div.portfolio-all-work a');
    var link_count = $links.size();
    var $prev_link = '';
    for (var i = 0; i < link_count; i++) {
      var $link = $links.eq(i);
      var href = '#' + main_panel_name + '/' + current_sub_panel;
      if ($link.attr('href') == href) {
        if ($prev_link != '') {
          location.href = $prev_link.attr('href');
        }
        else {
          location.href = $links.last().attr('href');
        }
        return;
      }
      else {
        $prev_link  = $link;
      }
    }
  }

}

function portfolio_arrow_right() {
  var portfolio_slides = $('div#work-panel div.portfolio-slides');

  if (portfolio_slides.is(':animated')) {
    return;
  }

  var $slides = portfolio_slides.find('.portfolio-slide');
  var max_slide_index = $slides.size() - 1;
  if (current_portfolio_slide_index != max_slide_index) {
    show_portfolio_slide( current_portfolio_slide_index + 1 );
  }
  else {
//    alert("You're trying to see the next portfolio, aren't you?");

    var main_panel_name = current_main_panel_name();
    var $links = $('#work-panel div.portfolio-all-work a');
    var link_count = $links.size();
    for (var i = 0; i < link_count; i++) {
      var $link = $links.eq(i);
      var href = '#' + main_panel_name + '/' + current_sub_panel;
      if ($link.attr('href') == href) {
        if (i < link_count - 1) {
          location.href = $links.eq(i + 1).attr('href');
        }
        else {
          location.href = $links.first().attr('href');
        }
        return;
      }
    }

  }
}

function current_main_panel_name() {
  for (var prop in main_panels) {
    if (main_panels[prop] == current_main_panel_index) {
      return prop;
    }
  }
}

function portfolio_see_all_work() {
  var controls = $('#portfolio-arrow-controls');
  var all_work = $('#portfolio-all-work-container');
  var divs = controls.is(":visible") ? [controls, all_work] : [all_work, controls];
  $(divs[0]).fadeOut(450, function(){
    $(divs[1]).fadeIn(450);
  });
}

function setup_resize_event() {
  $(window).resize(on_window_resize);
}

function on_window_resize() {
  // set the panel sizes
  var new_div_height = set_panel_sizes();

  // set the scroll for the panels container
  var new_scroll_to = current_main_panel_index * new_div_height;
  $('div#panels-container').css('top', - new_scroll_to);

  // make sure the home slideshow images are correct
  var $window = $(window);
  var width   = $window.width();
  var height  = $window.height();
  var $slides = $('div#home-slideshow img.background');
  $('div#home-slideshow').stop().
    width( width * $slides.size() ).
    height( $window.height() ).
    css('left', - width * completed_slide_count);
/*
  $slides.each(function(i){
    $(this).css({
      left:   i * width
    });
  });
*/
  // restart the slideshow
  if (slideshow_resize_timeout) {
    clearTimeout(slideshow_resize_timeout);
  }
  slideshow_resize_timeout = setTimeout(home_slideshow_do_slide, 3000);

}

function setup_navigation_links() {

  $('#nav a').
    mouseover(function(){
      var $img = $(this).find('img');
      $img.attr('src', $img.attr('src').replace(/(-hover)?\.gif$/, '-hover.gif'))
    }).mouseout(function(){
      var $img = $(this).find('img');
      $img.attr('src', $img.attr('src').replace(/-hover/, ''))
    });

  /* hover image state */
  $('.about-subnav img').live('mouseover', function(){
    var $this = $(this);
    $this.attr('src', $this.attr('src').replace(/(-hover)?\.png$/, '-hover.png'))
  }).live('mouseout', function(){
    var $this = $(this);
    $this.attr('src', $this.attr('src').replace(/-hover/, ''))
  });

  /* show/hide subnav on mouseover/out */
  $('#nav, .about-subnav, #about-panel .headline').live('mouseover', function(){
    $('.about-subnav').stop().fadeTo(450, 1);
  }).live('mouseout', function(){
    $('.about-subnav').stop().fadeTo(450, 0);
  });

  $('.news-blog-archive, .news-blog-archive-pulldown').
    live('mouseover', function(){
      $('.news-blog-archive-pulldown').show();
    }).
    live('mouseout', function(){
      $('.news-blog-archive-pulldown').hide();
    });

  // setup portfolio + see all work pane links so if they click on self, they see controls again
  $('#work-panel #portfolio-all-clients a').live('click',function(){
    var $this = $(this);
    if ($this.attr('href') == location.href.replace(/^[^#]+/, '').replace(/^([^\/]+\/[^\/]+)\/.*$/, '$1')) {
      // they clicked this same page, let them see the controls
      $('#portfolio-see-all-work-link').click();
    }
  });

  // form focus events
  $('tr#contact-input-from-tr').click(function(){$('input[name=from]').focus()})
  $('tr#contact-input-email-tr').click(function(){$('input[name=email]').focus()})
  $('tr#contact-input-message-tr').click(function(){$('textarea').focus()})

  /* See All Work link */
  $('#work-see-our-work-link').click(function(){
    $('#see-all-work-popover').css({
      display: 'block',
      opacity: .01
    });
    set_panel_sizes();
    var $all_work_links = $('#all-work-links');
    $all_work_links.css({
      left: ($('#see-all-work-popover').width() - $all_work_links.width() ) / 2,
      top:  ($('#see-all-work-popover').height() - $all_work_links.height() ) / 2
    });
    setTimeout(function(){
      set_panel_sizes();
      var $all_work_links = $('#all-work-links');
      $all_work_links.css({
        left: ($('#see-all-work-popover').width() - $all_work_links.width() ) / 2,
        top:  ($('#see-all-work-popover').height() - $all_work_links.height() ) / 2
      });
      $('#see-all-work-popover').css({
        opacity: 1
      });
    }, 10);
    $('body').one('click',function(){
      $('#see-all-work-popover').hide();
    })
    return false;
  });

  return;
}

function go_to_main_panel(main_panel_index) {

  // show this main panel (really the container), in case it's hidden
  // I don't think that this is necessary
  //   this function is run only when we want to go from a subpanel of
  //   a different main panel to a different main panel, so it should never be hidden
//  $('#' + main_panel_name(main_panel_index) + '-container').show();

  if (main_panels.work == main_panel_index) {
    var left = $('#work-panel img.sub').offset().left;
    if (left != 0) {
      $('#work-see-our-work-link').css('left', left );
    }
  }

  var pixel_top = - main_panel_index * $(window).height();

  $('div#panels-container').stop().animate({top: pixel_top}, 0, 'easeout', function(){

    remove_previous_subpanel();
    current_main_panel_index = main_panel_index;

    set_logo_color();

    $('div.sub-panel').hide();
  });

}

function main_nav_link_clicked(hash) {

  var $this = $(this);
  var this_main_panel_index = main_panels[ hash.substring(1) ];

  // nonesuch panel (404)?
  if (typeof this_main_panel_index == 'undefined') {
    sub_nav_link_clicked('#' + current_main_panel_name() + '/nonesuch');

    halt_load_testing();

    return;
  }

  // if we're looking at a sub-panel, and they clicked on the main panel nav link ...
  if (current_main_panel_index == this_main_panel_index) {
    if (current_sub_panel != '') {
      // fade to overlay, hide sub-panel, fade out overlay
      $('div#initial-overlay').fadeTo(0, 0).css('display', '').fadeTo(1000, 1, function(){

        show_all_main_panels();

        if (main_panels.work == this_main_panel_index) {
          var left = $('#work-panel img.sub').offset().left;
          if (left != 0) {
            $('#work-see-our-work-link').css('left', left );
          }
        }

        $('div.sub-panel').hide();
        $('div#initial-overlay').fadeTo(1000, 0, function(){
          $('div#initial-overlay').hide();
          remove_previous_subpanel();
          set_logo_color();
        });
      });
    }

    // we are already on that page
    halt_load_testing();
    return;

  }

  var pixel_top = - this_main_panel_index * $(window).height();

//  $('#nav a').removeClass('active');
//  $this.addClass('active');

  if (initial_panel_is_set) {
    $('div#panels-container').stop().animate({top: pixel_top}, 1000, 'easeout', function(){

      show_all_main_panels();

      remove_previous_subpanel();
      current_main_panel_index = this_main_panel_index;

      // strange bug where the news page scrolling div is way too tall - recalculate it
      if (main_panels.news == this_main_panel_index) {
        var $blog_content = $('#news-panel .blog-content');
        var div_height = $blog_content.offset().top + $blog_content.height() + $('#news-panel').scrollTop() + 50;
        $('#news-bg-wrapper').height(div_height);
      }

      set_logo_color();

      $('div.sub-panel').hide();
    });
    finish_panel_loading(false);

  }
  // initial panel has not yet been set, snap-to where we're going
  // this is the first page to be shown
  else {
    $('div#panels-container').stop().css({top: pixel_top});

    current_main_panel_index = this_main_panel_index;
    set_logo_color();

    initial_panel_is_set = true;
    finish_panel_loading(true);

  }

}

function sub_nav_link_clicked(hash) {

  var $this = $(this);
  var href  = hash.substring(1);

  var main_panel_name = href.replace(/\W.+$/,  ''); // in the form: "mainpanelname/sub-panel-name.html"
  var sub_panel_name  = href.replace(/^\w+\W/, '').replace(/\.html$/, '');

  // let's see if this is just another subcategory
  // if it is, just shift the slides and return
  if (main_panel_name == 'work' && /([^\/]+)\/(.+)/.test(sub_panel_name)) {
    var sub_panel_name    = RegExp.$1;
    var subcategory_name  = decodeURI(RegExp.$2).replace(/\+/g, ' ');

    // are we already on this panel and sub-panel?
    if (main_panels[main_panel_name] == current_main_panel_index && current_sub_panel.replace(/\/.+/, '') == sub_panel_name) {
      var subcats = current_subcategories();
      for (var i = 0; i < subcats.length; i++) {
        if (subcategory_name == subcats[i].name) {
          show_portfolio_slide(subcats[i].idx);
          halt_load_testing();
          return;
        }
      }
    }
  }

  // if we're already on that portfolio, just show slide 0
  if (main_panels[main_panel_name] == current_main_panel_index && current_sub_panel.replace(/\/.+/, '') == sub_panel_name) {
    show_portfolio_slide(0);
    halt_load_testing();
    return;
  }

  // they clicked on self
  if (main_panels[main_panel_name] == current_main_panel_index && current_sub_panel == sub_panel_name) {

    // they may have clicked on the link in the See All Work panel of the portfolio page
    // if that's the case, show the controls and hide the list of work
//    if (main_panel_name == 'work' && $('#work-panel #portfolio-all-work-container:visible').size() > 0) {
//      $('#portfolio-see-all-work-link').click();
//    }

    halt_load_testing();
    return;
  }

  // 404 situation
  if (/nonesuch/.test(href) && typeof loaded_sub_panels[main_panel_name + '/nonesuch'] == 'undefined') {
    loaded_sub_panels[main_panel_name + '/nonesuch'] = $('div#panels-container > div.nonesuch-panel').clone()[0];
  }

  // fetch the page and load it into place, then hide the overlay
  window.overlay_fade_done = false;

  if (typeof loaded_sub_panels[href] != 'undefined') {
    fade_in_sub_panel(href, null);
  }
  else {

    $.ajax({
      type: 'GET',
      url: ( /local/.test(location.href) ? '/' : '/index.php/' ) + href,
      error: function(){
        // 404 situation
        if (typeof loaded_sub_panels[main_panel_name + '/nonesuch'] == 'undefined') {
          loaded_sub_panels[main_panel_name + '/nonesuch'] = $('div#panels-container > div.nonesuch-panel').clone()[0];
        }
        fade_in_sub_panel(main_panel_name + '/nonesuch', null);
      },
      success: function(html){
        fade_in_sub_panel(href, html);
      }
    });

  }

  if (initial_panel_is_set) {
    $('div#initial-overlay').fadeTo(0, 0).hide().fadeTo(1000, 1, function(){

      remove_previous_subpanel();

      window.overlay_fade_done = true;

      console.log('overlay faded in');
    });
  }
  else {
      window.overlay_fade_done = true;
  }

}

function remove_previous_subpanel() {
  // and make sure this isn't sticky
  $('.news-blog-archive').mouseout();

  // remove previous sub-panel, if it exists
  if (current_sub_panel != '') {
    var main_panel_name = '';
    for (var prop in main_panels) {
      if (main_panels[prop] == current_main_panel_index) {
        main_panel_name = prop;
        break;
      }
    }
    // get rid of the sub-panel and any sub-category subpanels
    $('#' + main_panel_name + '-panel div[id^=' + main_panel_name + '-sub-' + current_sub_panel + ']').remove();
  }
  else {
    console.log('there was no sub-panel to remove');
  }

  current_sub_panel = '';

}

function show_all_main_panels() {
  hide_main_panel('');
}

// this will actually just hide the containers, not the panels
function hide_main_panel(panel_name_to_hide) {
  for (var this_panel_name in main_panels) {
    if (this_panel_name == panel_name_to_hide) {
      $('#' + panel_name_to_hide + '-container').hide();
    }
    else {
      $('#' + this_panel_name + '-container').show();
    }
  }
}

/* the html param is null when the div is already loaded into the DOM */
function fade_in_sub_panel(href, html) {
  // failed to get html
  if (typeof window.overlay_fade_done !== 'boolean') {
    console.log('error fetching html; exiting');
    halt_load_testing();
    return;
  }

  // wait until after the overlay fades in
  if (!window.overlay_fade_done) {
    console.log('fade in of overlay not yet complete...');
    setTimeout(function(){ fade_in_sub_panel(href, html); }, 100);
    return;
  }

  console.log('fade in of overlay complete. continuing...');

  var main_panel_name = href.replace(/\W.+$/,  ''); // in the form: "mainpanelname/sub-panel-name.html"
  var sub_panel_name  = href.replace(/^\w+\W/, '').replace(/\.html$/, '');

  if (main_panel_name != current_main_panel_name()) {
    go_to_main_panel(main_panels[main_panel_name]);
  }

  // hide the main panel and its scrollbars
  //   this will also show all other main panels
  hide_main_panel(main_panel_name);

  // append it to the current main panel
  if (html !== null) {
    var div = document.createElement('div');
    div.className = 'sub-panel';
    div.id = main_panel_name + '-sub-' + sub_panel_name;
    div.style.width   = $(window).width();
    div.style.height  = $(window).height();
    div.innerHTML = html;

    //console.log( 'images: ' + $(div).find('img').size() );
    var imgs = $(div).find('img');
    var img_count = imgs.size();
    if (img_count == 0) {
      fade_in_sub_panel_finish(sub_panel_name);
      return;
    }

    var images_left_to_load = img_count;
    for (var i = 0; i < img_count; i++) {
      imgs.eq(i).bind('load', function(){
        if (--images_left_to_load == 0) {
          fade_in_sub_panel_finish(sub_panel_name);
        }
      });
      imgs.eq(i).bind('error', function(){
        if (--images_left_to_load == 0) {
          fade_in_sub_panel_finish(sub_panel_name);
        }
      });
    }

    $('div#' + main_panel_name + '-panel').append(div);
  }
  else {
    div = loaded_sub_panels[href];
    $('div#' + main_panel_name + '-panel').append(div);
    $(div).show().find('.sub-panel').show();

    fade_in_sub_panel_finish(sub_panel_name);
  }

  // in case the portfolio slides didn't get set to their lefts
//  var $slides = $('img.portfolio-slide');
//  if ($slides.length && $slides.eq(0).css('left') == 0) {
//    set_portfolio_panel_sizes();
//  }

  loaded_sub_panels[href] = div;

}

function fade_in_sub_panel_finish(sub_panel_name) {

  on_window_resize();

  // for portfolio pages, make sure things line up right
  var $slide_content = $('#work-panel #portfolio-slide-content-1');
  if ($slide_content.size() > 0) { // the portfolio panel is loaded
    var html = $slide_content.html();
    $('#work-panel .portfolio-content').html( html );
    if (/#work\/[^\/]+\/(.+)/.test(location.href)) {
      var requested_subcat = decodeURI(RegExp.$1).replace(/\+/g, ' ');
      var current_subcats = current_subcategories();
      for (var i = 0; i < current_subcats.length; i++) {
        if (requested_subcat == current_subcats[i].name) {
          show_portfolio_slide(current_subcats[i].idx, true); // instantly
          break;
        }
      }
/*
      var portfolio_panel = $('#work-sub-portfolio');
      var $slides = portfolio_panel.find('.portfolio-slide');
      var ps_left = portfolio_slide_left_pixels($slides, idx);
      $('#work-panel .portfolio-slides').css('left', 79 - ps_left);
*/
    }
    else {
      $('#work-panel .portfolio-slides').css('left', 0);
      current_portfolio_slide_index = 0;
    }
    $('#work-panel #portfolio-all-work-container').hide();
    $('#work-panel #portfolio-arrow-controls').show();
    var subcats = current_subcategories();
    // do not show just a single jump menu item - that would inhibit sharing slides between portfolios ...
    if (subcats.length > 1) {
      var subcat_html = '<span class="jump-to">JUMP TO:</span><br/>';
      for (var i = 0; i < subcats.length; i++) {
        subcat_html += '<a href="#" onclick="subcat_clicked(' + i + '); return false;">' + subcats[i].name + '</a><br/>';
      }
      $('#work-panel div#portfolio-subcategories').html(subcat_html);
    }
  }

  // insane bug
  if ($.browser.msie) {
    self.resizeBy(0, 1);
    setTimeout(function(){ self.resizeBy(0, -1); }, 100);
  }

  set_logo_color(sub_panel_name);

  $('div#initial-overlay').fadeTo(1000, 0, function(){
    $('div#initial-overlay').hide();
    current_sub_panel = sub_panel_name;
    console.log('sub panel should now be visible.');

    finish_panel_loading(!initial_panel_is_set);
    initial_panel_is_set = true;

  });

}

function set_logo_color(sub_panel_name) {
  if (arguments.length == 0) {
    sub_panel_name = current_sub_panel;
  }

  var main_name = current_main_panel_name();
  var href = main_name;
  if (sub_panel_name) {
    href += '/' + sub_panel_name;
  }

//console.log(main_name + ":" + sub_panel_name + ":" + href);

  // logo should be red
  var logo_color = '';
  var $logo_color = $('#work-portfolio-bg-wrapper .logo-color');
  if ($logo_color.size() > 0) {
    if ($logo_color.html() == 'White') {
      logo_color = 'White';
    }
    else {
      logo_color = 'Red';
    }
  }

  if ( logo_color != 'White' && typeof white_formium_logo_hrefs[href] == 'undefined') {
    if (/white/.test( $('div#logo img').attr('src') )) {

      var $logo = $('div#logo');
      $logo.fadeOut(500, function(){
        $logo.find('img').attr('src', 'img/logo-red.png');
        $logo.find('#logo-links a').css('color', 'red');
        $logo.fadeIn(500);
      });
/*
      $('div#logo img').fadeOut(500, function(){
        $('div#logo img').attr('src', 'img/logo-red.png').fadeIn(500);
      });
*/
    }
  }
  // logo should be white
  else {
    if (/red/.test( $('div#logo img').attr('src') )) {

      var $logo = $('div#logo');
      $logo.fadeOut(500, function(){
        $logo.find('img').attr('src', 'img/logo-white.png');
        $logo.find('#logo-links a').css('color', 'white');
        $logo.fadeIn(500);
      });
/*
      $('div#logo img').fadeOut(500, function(){
        $('div#logo img').attr('src', 'img/logo-white.png').fadeIn(500);
      });
*/
    }
  }

}

function subcat_clicked(idx) {
  var subcats = current_subcategories();
  var subcat = subcats[idx];

  show_portfolio_slide(subcat.idx);
}

function current_subcategories() {

  var data = [];
  var found = {};
  var $subs = $('div#work-panel div.portfolio-slides div[id^=portfolio-slide-subcategory-]');

  var count = $subs.size();
  for (var i = 0; i < count; i++) {
    var subcat = $subs.eq(i).html();
    if (subcat != '' && !found[subcat]) {
      found[subcat] = true;
      data.push({
        name: subcat,
        idx:  i
      });
    }
  }

  return data;
}

function contact_send() {

  var errors = false;

  if ($('#contact-input-from').val() == '') {
    errors = true;
    $('label[for=contact-input-from]').addClass('error');
  }
  else {
    $('label[for=contact-input-from]').removeClass('error');
  }

  if (!emailCheck($('#contact-input-email').val())) {
    errors = true;
    $('label[for=contact-input-email]').addClass('error');
  }
  else {
    $('label[for=contact-input-email]').removeClass('error');
  }

  if ($('#contact-input-message').val() == '') {
    errors = true;
    $('label[for=contact-input-message]').addClass('error');
  }
  else {
    $('label[for=contact-input-message]').removeClass('error');
  }

  if (errors) {
    $('p.contact-messages').addClass('error').html('PLEASE FILL OUT ALL FIELDS THEN CLICK SEND.');
    return;
  }

  $('p.contact-messages').removeClass('error').html('LOADING...');

  $.ajax({
    type: 'post',
    url: ( /local/.test(location.href) ? '/' : '/index.php/' ) + 'contact/form',
    data: $('form').serialize(),
    error: function(){
      $('p.contact-messages').addClass('error').html('THERE WAS AN ERROR. PLEASE TRY AGAIN LATER.');
    },
    success: function(data){
      if (data) {
        window.contact_response = data;
        $('p.contact-messages').removeClass('error').html('THANK YOU. YOUR MESSAGE HAS BEEN SENT.');
      }
      else {
        $('p.contact-messages').addClass('error').html('THERE WAS AN ERROR. PLEASE CHECK YOUR INPUT AND TRY AGAIN.');
      }
    }
  });
}

function halt_load_testing() {
  LOADING_START_TIME = null;
  LOADING_PATH = null;
}

var timeout_timeout = null;
function finish_panel_loading(is_initial) {
  if (LOADING_START_TIME && LOADING_PATH) {
    set_page_title(LOADING_PATH);
    save_loading_duration(is_initial);
    clearTimeout(timeout_timeout);
  }
  halt_load_testing();
}

function throw_error() {
  this_isnotdefined();
}

function set_page_title(path) {

  var PAGE_TITLES = {
    '/about': 'About',
    '/about/why-formium': 'Why Formium',
    '/about/why-not-formium': 'Why Not Formium',
    '/about/how-we-work': 'How We Work',
    '/about/who-we-are': 'Who We Are',
    '/about/what-we-do': 'What We Do',
    '/about/incubator': 'Incubator',
    '/clients': 'Clients',
    '/work': 'Work',
    '/work/see-our-work': 'Work | See Our Work',
    '/contact': 'Contact',
    '/news': 'News'
  };

  var $a = $('#portfolio-all-work-container a[href="#' + path.substring(1) + '"]');
  // "static" panel
  if (typeof PAGE_TITLES[path] !== 'undefined') {
    document.title = 'FORMIUM | ' + PAGE_TITLES[path];
  }
  // portfolio
  else if ($a.size()) {
    document.title = 'FORMIUM | Work | ' + $a.html();
  }
  else //if (path == '/' || path == '/home')
    {
      document.title = 'FORMIUM';
  }

}
var error_was_reported = false;
function report_error(msg) {
  if (!error_was_reported) {
    LOADING_PATH = msg + ":" + LOADING_PATH;
    save_loading_duration(!initial_panel_is_set, true);
    error_was_reported = true;
  }
}

function save_loading_duration(is_initial, is_error) {

  if (is_error) {
    if (!LOADING_PATH) {
      LOADING_PATH = 'error path';
    }
    if (!LOADING_START_TIME) {
      LOADING_START_TIME = new Date().getTime();
    }
    is_error = 1;
  }
  else {
    is_error = 0;
  }

  if (LOADING_PATH) {

    var duration = new Date().getTime() - LOADING_START_TIME;
    var data = {
      duration:   duration,
      useragent:  navigator.userAgent,
      os:         navigator.platform,
      is_initial: ( is_initial ? '1' : '0' ),
      panel:      LOADING_PATH,
      is_error:   is_error
    };

    console.log(data);
    $.post('/index.php/Formium/track-loading-times', data, function(txt){
      console.log(txt);
    });

    LOADING_PATH        = null;
    LOADING_START_TIME  = null;
  }
}

function check_location() {
  var location_hash = location.href.replace(/[^#]*/, '');

  if (location_hash == '') {
    location.href = '#home';
    return;
  }

//  if (location_hash == '#news' && $('#news-panel .jspTrack').size() == 0) {
//    set_panel_sizes(); // hack to invoke jScrollPane on that panel
//  }

  if (location_hash == present_location_hash) {
    return;
  }

  /* let google analytics know that we're browsing to a page */
  var path = "/" + location_hash.substring(1);
  console.log('ga: ' + path);
  try {
    pageTracker._trackPageview(path);
  } catch (err) {
    console.log('ga failure: ' + err);
  }

  /* mark the start loading time */
  LOADING_START_TIME  = new Date().getTime();
  LOADING_PATH        = path;

  /* if this takes longer than 30 seconds, it's an error */
  timeout_timeout = setTimeout(report_error, 30000);

  $('#see-all-work-popover').hide();

  // change the current panel
  if (!/\/+/.test(location_hash)) { // main panel
    main_nav_link_clicked(location_hash);
  }
  // sub-panel
  else {
    sub_nav_link_clicked(location_hash);
  }

  present_location_hash = location_hash;
}

function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
return false;
   }
}

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
return false;
}

if (len<2) {
return false;
}

return true;
}

