﻿//var c = console.log;


// from http://james.padolsey.com/javascript/regex-selector-for-jquery/
jQuery.expr[':'].regex = function (elem, index, match) {
  var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
          method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
          property: matchParams.shift().replace(validLabels, '')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
  return regex.test(jQuery(elem)[attr.method](attr.property));
}

$(document).ready(function () {
  /////
  // variables and initial setup
  ////
  //


  /////
  // for IE lower than 9 do various CCS modifications
  /////
  if ($.browser.msie && parseInt($.browser.version) <= 8) {
    $('.content-area.data .data-table:not(.grid) tr:not(.header):nth-child(2n)').css({ 'background': '#f2f1f1' }); // color zebra rows via JS
    $('.insights .featured-insight:nth-child(3n-2)').css({ 'margin-left': 0 });
    //		$('.team-contacts .contact:nth-child(5n)').css({'margin-right': 0});
  }

  /////
  // main menu show/hide and handle select element, this is to prevent the menu from collapsing when the funds dropdown is focused
  /////
  $('ul.main-nav li').hover(function (e) {
    $(this).children("ul:first").show();
  }, function (e) {
    if (e.relatedTarget != null) // drop down select box fix
      $(this).children("ul:first").hide();
  });
  /////
  // login drowdown in header
  /////
  $('#login-area').click(function (e) {
    var height = $('.login-dropdown li').length * 20 + 'px';
    if ($('.login-dropdown').css('height') == '20px')
      $('.login-dropdown').css({ 'height': height }, 300);
    else
      $('.login-dropdown').css({ 'height': '20px' }, 300);
    e.stopPropagation();
    e.preventDefault();
  });
  /////	
  // hide dropdown and map popup if clicked outside (anywhere in body)
  /////
  $('body').click(function (e) {
    var height = $('.login-dropdown li').length * 20 + 'px';
    if ($('.login-dropdown').css('height') == height)
      $('.login-dropdown').css({ 'height': '20px' }, 300);
  });


  $('.main-nav li:not(.audience) .sub-nav').hover(function () {
    $(this).prev('a').addClass('hover');
  }, function () {
    $(this).prev('a').removeClass('hover');
  });

  /////
  // bind "leaving site" dialog to a tags
  /////
  $('a').live('click', function (e) {
    var bumper = false;
    if ($(this).attr('href') && $(this).attr('href').indexOf('http') > -1) {
      var count = 0;
      for (var i = 0; i < whiteListDomains.length; i++) {
        if ($(this).attr('href').indexOf(whiteListDomains[i]) > -1) {
          count++;
        }
        bumper = count == 0 ? true : false;
      }
    }
    if (bumper) {
      return confirm('You are leaving Sicav.WilliamBlairFunds.com, are you sure you want to continue?');
    }
  });
  /////
  // bind print
  /////
  $('a.print').click(function (e) {
    window.print();
    e.preventDefault();
  });

  /////
  // blinds
  /////
  /*
  args:
  hasTitle: does the node have a title whose height needs to be accounted for? (default: false)
  animationDuration: how long the slide animation lasts (default: 200ms)
  special: anything else that needs to be performed on hover on/off (default: {}) or the following JSON object:
  selector: jQuery selector for element to act upon
  css: an JSON object with CSS properties to animate
  */
  (function ($) {
    $.fn.blinds = function (args) {
      var defaults = {
        hasTitle: false,
        animationDuration: 200,
        special: {}
      };
      var args = $.extend(defaults, args);
      return this.each(function () {
        var $this = $(this),
				$detail = $this.find('.detail'),
				height = $detail.outerHeight(),
				titleHeight = args.hasTitle ? $detail.find('.title').outerHeight() : 0;
        args.special = args.special || false;
        $this.hover(function () {
          $detail.stop(false, true).animate({ 'top': '-=' + (height - titleHeight) }, args.animationDuration);
          if (!$.isEmptyObject(args.special)) {
            $this.find(args.special.selector).stop(false, true).animate(args.special.cssOver, args.animationDuration);
          }
        }, function () {
          $detail.stop(false, true).animate({ 'top': '+=' + (height - titleHeight) }, args.animationDuration);
          if (!$.isEmptyObject(args.special))
            $this.find(args.special.selector).stop(false, true).animate(args.special.cssOut, args.animationDuration);
        });

      });
    }
  })(jQuery);
  /////
  // form validator
  /////
  (function ($) {
    $.fn.validator = function () {
      var defaults = {
    };
    var args = $.extend(defaults, args);
    return this.each(function () {
      var $this = $(this),
				errors,
				$required = {
				  'text': $this.find('input[type=text].required, input[type=password].required, textarea.required'),
				  'select': $this.find('select.required'),
				  'checkbox': $this.find('input[type=checkbox].required'),
				  'radio': $this.find('input[type=radio].required')
				},
				validate,
				addErrorMarker,
				removeErrorMarker;
      // add "required" marker
      for (name in $required) {
        $required[name].each(function () {
          //					c($this.find('.label[for=' + $(this).attr('name') + ']'))
          if (name == 'radio' || name == 'checkbox') {
            if ($this.find('.label[group=' + $(this).attr('name') + '] .required-mark').length == 0)
              $this.find('.label[group=' + $(this).attr('name') + ']').prepend($('<span class="required-mark">*</span>'));
          } else {
            $(this).prev('label').prepend($('<span class="required-mark">*</span>'));
          }
        });
      }
      // bind form submit
      $this.submit(function () {
        return validate();
      });
      $this.find('.submit').bind('click', function (e) {
        $this.trigger('submit');
        e.preventDefault();
      });
      addErrorMarker = function ($obj, type) {
        var errorText;
        switch (type) {
          case 'text':
            errorText = $obj.attr('err') == undefined ? 'Please complete this field' : $obj.attr('err');
            if ($obj.next('span.error').length == 0)
              $('<span class="error">' + errorText + '</span>').insertAfter($obj).fadeIn(300);
            break;
          case 'select':
            errorText = $obj.attr('err') == undefined ? 'Please select one' : $obj.attr('err');
            if ($obj.next('span.error').length == 0)
              $('<span class="error">' + errorText + '</span>').insertAfter($obj).fadeIn(300);
            break;
          case 'checkbox':
            errorText = $obj.attr('err') == undefined ? 'Please check off at least one box' : $obj.attr('err');
            if ($this.find('.label[group=' + $obj.attr('name') + ']').siblings('span.error').length == 0)
              $('<span class="error">' + errorText + '</span>').insertAfter($this.find('.label[group=' + $obj.attr('name') + ']')).fadeIn(300);
            break;
          case 'radio':
            errorText = $obj.attr('err') == undefined ? 'Please select one' : $obj.attr('err');
            if ($this.find('.label[group=' + $obj.attr('name') + ']').siblings('span.error').length == 0)
              $('<span class="error">' + errorText + '</span>').insertAfter($this.find('.label[group=' + $obj.attr('name') + ']')).fadeIn(300);
            break;
          default: ;
        }
      }
      removeErrorMarker = function ($obj, type) {
        switch (type) {
          case 'text':
          case 'select':
            $obj.next('span.error').fadeOut(300, function () {
              $(this).remove()
            });
            break;
          case 'checkbox':
          case 'radio':
            $this.find('.label[group=' + $obj.attr('name') + ']').siblings('span.error').fadeOut(300, function () {
              $(this).remove()
            });
            break;
          default: ;
        }
      }
      validate = function (args) {
        errors = 0;
        $required.text.each(function (n) {
          var $this = $(this);
          if ($this.val() == '' ||
						($this.hasClass('email') && !/.+@.+\..+/.test($this.val())) ||
						($this.hasClass('confirm') && $this.val() != $required.text.filter($this.attr('with')).val())) {
            errors++;
            addErrorMarker($this, 'text');
          } else {
            removeErrorMarker($this, 'text');
          }
        });
        $required.select.each(function (n) {
          var $this = $(this);
          if ($(this).val() == '') {
            errors++;
            addErrorMarker($this, 'select');
          } else {
            removeErrorMarker($this, 'select');
          }
        });
        $required.checkbox.each(function (n) {
          var $this = $(this);
          name = $this.attr('name');
          //						errorText = $this.attr('err') == undefined ? 'Please check off at least one box' : $this.attr('err');
          filter = $required.checkbox.filter('[name=' + name + ']:checked');
          if (filter.length == 0) {
            addErrorMarker($this, 'checkbox');
          } else {
            removeErrorMarker($this, 'checkbox');
          }
        });
        $required.radio.each(function (n) {
          var $this = $(this);
          name = $this.attr('name');
          //						errorText = $this.attr('err') == undefined ? 'Please select one' : $this.attr('err');
          filter = $required.radio.filter('[name=' + name + ']:checked');
          if (filter.length == 0) {
            addErrorMarker($this, 'radio');
          } else {
            removeErrorMarker($this, 'radio');
          }
        });
        return errors == 0;
      }
    });
  }
})(jQuery);
/////
// tabs
/////
/*
args:
currentTab: which tab is selected first (default: 0)
tabsNavWidth: custom tab width (default: 0, inherited from CSS)
*/
(function ($) {
  $.fn.tabs = function (args) {
    var defaults = {
      'currentTab': 0,
      'tabsNavWidth': 0,
      'special': function () { return false; }
    },
			args = $.extend(defaults, args);
    return this.each(function (_i) {
      // variables
      var $this = $(this),
				$wrapper = $this,
				$tabsNav = $this.find(' >.tabs-nav li') || {},
				$tabsNavLinks = $this.find(' >.tabs-nav li a') || {},
				$tabsContent = $this.find('> .tabs-content-wrapper .tabs-content') || {},
				totalTabs = $tabsNavLinks.length || 0,
				currentTab = args.currentTab || 0,
				tabsNavWidth = args.tabsNavWidth || 0,
      // navigate function
				navigate = function (n) {
				  $tabsNav.filter(':eq(' + currentTab + ')').removeClass('selected');
				  $tabsNav.filter(':eq(' + n + ')').addClass('selected');
				  $tabsContent.filter(':eq(' + currentTab + ')').addClass('hidden');
				  $tabsContent.filter(':eq(' + n + ')').removeClass('hidden');
				  currentTab = n;
				  try {
				    args.special($tabsNavLinks.eq(n).attr('title'));
				  } catch (e) {
				    // don't care if this doesn't execute since it would only be defined as needed
				  }
				};
      if (currentTab == 0) {
        var url = window.location.href;
        var anchor = url.substring(url.indexOf("#sub-tab-") + 9);
        currentTab = parseInt(anchor) - 1;
        //make sure currentTab value is valid, otherwise reset to 0
        if (isNaN(currentTab) || currentTab < 0) {
          currentTab = 0;
        };
      };
      // this should be init
      $tabsNavLinks.each(function (n) {
        $(this).attr('rel', n);
      });
      $tabsNav.filter(':eq(' + currentTab + ')').addClass('selected');
      $tabsContent.not(':eq(' + currentTab + ')').addClass('hidden');
      try {
        args.special($tabsNavLinks.eq(args.currentTab).attr('title'));
      } catch (e) {
        // don't care if this doesn't execute since it would only be defined as needed
      }
      $tabsNavLinks.click(function (e) {
        navigate($(this).attr('rel'));
        e.preventDefault();
      });
      if (tabsNavWidth != 0)
        $tabsNav.css('width', tabsNavWidth);
    });
  };
})(jQuery);
/////
// carousel
/////
/*
args:
animationDuration: time for each node to complete its animation (default: 1000ms)
orientation: 'h' for horizontal or 'v' for vertical (default: 'v')
pagination: is pagination enabled? (default: false)
specialFirstElement: does the first element have a top border and thus has to be animated an extra pixel? (default: false)
autoscroll: does the carousel scroll automatically? (default: false)
autoscrollTimeout: how long each carousel node is displayed (default: 5000ms)
visibleNodes: how many nodes are initially visible (default: 1)
*/
(function ($) {
  $.fn.carousel = function (args) {
    var defaults = {
      'animationDuration': 1000,
      'orientation': 'v',
      'pagination': false,
      'visibleNodes': false,
      'specialFirstElement': false,
      'autoscroll': false,
      'autoscrollTimeout': 5000
    };
    var args = $.extend(defaults, args);
    return this.each(function (_i, _item) {
      var $this = $(_item),
				wrapper = $this,
				navigate,
				_updateCoords,
				_autoscroll,
				_updatePagination,
				obj = wrapper.find('.carousel') || {},
				next = wrapper.find('.next') || {},
				prev = wrapper.find('.prev') || {},
				width = obj.width(),
				height = obj.height(),
				animationDuration = args.animationDuration,
				orientation = args.orientation,
				pagination = args.pagination,
				visibleNodes = args.visibleNodes,
				specialFirstElement = args.specialFirstElement,
				autoscroll = args.autoscroll,
				autoscrollTimeout = args.autoscrollTimeout,
				paginationNodes = [],
				currentPosition = 0,
				lastPosition = 0,
      //			defaultAnimationDuration = 1000,
      //			defaultTimeout = 5000,
				outOfBounds = false,
				nodes = [],
				wrapperHeight = 0,
				wrapperWidth = 0,
				carouselWidth = 0;

      this.left = 0;
      this.top = 0;


      // update coordinates function
      _updateCoords = function () {
        $this.left = obj.position().left;
        $this.top = obj.position().top;
        outOfBounds = currentPosition + 1 > lastPosition ? 'next' : currentPosition - 1 < 0 ? 'prev' : false;
        if (outOfBounds == 'next')
          next.addClass('inactive')
        else
          next.removeClass('inactive')
        if (outOfBounds == 'prev')
          prev.addClass('inactive')
        else
          prev.removeClass('inactive')
        //			c(this.outOfBounds);
        //			c('left: ' + this.left);
        //			c('top: ' + this.left);
        //				c(obj.attr('id'));

      };
      _updatePagination = function (modifier) {
        if (!pagination)
          return false;
        if (modifier == 'add')
          paginationNodes[currentPosition].obj.addClass('selected');
        else
          paginationNodes[currentPosition].obj.removeClass('selected');
      };
      // autoscroll function; accepts timeout argument or uses default from constructor or the global default
      _autoscroll = function (timeout) {
        timeout = autoscrollTimeout;
        //				c(timeout);
        window.setInterval(function () {
          if (currentPosition + 1 > lastPosition) {
            navigate({
              direction: 'jump',
              duration: animationDuration,
              jumpTo: 0
            });
          } else {
            navigate({
              direction: 'next',
              duration: animationDuration,
              specialFirstElement: specialFirstElement
            });
          }
        }, timeout);
      }
      navigate = function (args) {
        //				c(obj.attr('id'));
        var direction = args.direction,
					duration = args.duration,
					specialFirstElement = args.specialFirstElement,
					jumpTo = args.jumpTo,
					distance = 0,
					_self = this,
					params = {};
        offset = {};
        offset.top = '0';
        offset.left = '0';
        dimension = orientation == 'v' ? 'height' : 'width';
        // if carousel is in motion, do not move
        if (obj.filter(":animated").length > 0)
          return false;
        // handle navigation
        switch (direction) {
          case 'next':
            distance = outOfBounds == 'next' ? 30 : nodes[currentPosition][dimension] - (specialFirstElement && currentPosition == 0 ? 1 : 0);
            offset[orientation == 'v' ? 'top' : 'left'] = '-=' + distance;
            if (outOfBounds == 'next') {
              obj.animate(offset, 300);
              offset.left = offset.left.replace('-', '+');
              offset.top = offset.top.replace('-', '+');
              obj.animate(offset, 200);
              return false;
            }
            _updatePagination('remove')
            obj.animate(offset, duration, function () {
              _updateCoords();
            });
            currentPosition++;
            _updatePagination('add')
            break;
          case 'prev':
            distance = outOfBounds == 'prev' ? 30 : nodes[currentPosition - 1][dimension] - (specialFirstElement && currentPosition - 1 == 0 ? 1 : 0);
            offset[orientation == 'v' ? 'top' : 'left'] = '+=' + distance;
            if (outOfBounds == 'prev') {
              obj.animate(offset, 300);
              offset.left = offset.left.replace('+', '-');
              offset.top = offset.top.replace('+', '-');
              obj.animate(offset, 200);
              return false;
            }
            _updatePagination('remove')
            currentPosition--;
            obj.animate(offset, duration, function () {
              _updateCoords();
            });
            _updatePagination('add')
            break;
          case 'jump':
            if (jumpTo == currentPosition)
              break;
            if (pagination) {
              paginationNodes[currentPosition].obj.removeClass('selected');
            }
            var from = jumpTo > currentPosition ? currentPosition : jumpTo,
							to = jumpTo > currentPosition ? jumpTo : currentPosition;
            for (var i = from; i < to; i++) {
              distance += nodes[i].width;
            }
            if (jumpTo < currentPosition)
              distance = '-' + distance
            obj.animate({ left: '-=' + distance }, duration, function () { _updateCoords(); });
            currentPosition = jumpTo;
            if (pagination) {
              paginationNodes[currentPosition].obj.addClass('selected');
            }
            break;
          default:
            ;
        }
      };

      // pagination is enabled		
      if (pagination) {
        wrapper.find('.pagination a').each(function (n) {
          paginationNodes.push({
            obj: $(this),
            index: n
          });
          $(this).click(function (e) {
            navigate({
              direction: 'jump',
              duration: animationDuration,
              jumpTo: n
            });
            e.preventDefault();
          });
        });
      }
      // populate carousel nodes object
      obj.find('> li').each(function (n) {
        nodes.push({
          obj: $(this),
          index: n,
          width: $(this).outerWidth(),
          height: $(this).outerHeight()
        });
      });

      // set up carousel wrapper width/height based on orientation
      switch (orientation) {
        case 'v':
          wrapperHeight = 0;
          for (var i = 0; i < visibleNodes; i++) {
            wrapperHeight += nodes[i].height;
          }
          break;
        case 'h':
          for (var i = 0; i < nodes.length; i++) {
            carouselWidth += nodes[i].width;
          }
          obj.width(carouselWidth);
          wrapperWidth = nodes[0].width;
          break;
        default: ;
      }
      wrapperWidth = wrapperWidth != 0 ? wrapperWidth += 'px' : 'auto';
      wrapperHeight = wrapperHeight != 0 ? wrapperHeight += 'px' : 'auto';
      lastPosition = nodes.length - 1;
      obj.wrap('<div style="width: ' + wrapperWidth + '; height: ' + wrapperHeight + '; ' + (orientation == 'h' ? ' float: left;' : '') + ' overflow: hidden; position: relative;" />');

      // autoscroll
      if (autoscroll) {
        _autoscroll();
      }
      // initial update
      _updateCoords();

      // bind navigation clicks
      next.click(function (e) {
        navigate({
          direction: 'next',
          duration: $this.animationDuration,
          specialFirstElement: specialFirstElement
        });
        e.preventDefault();
      });
      prev.click(function (e) {
        navigate({
          direction: 'prev',
          duration: $this.animationDuration,
          specialFirstElement: specialFirstElement
        });
        e.preventDefault();
      });
    });

  };
})(jQuery);
/////
// datatable with sort
/////
(function ($) {
  $.fn.datatable = function (args) {
    var defaults = {
      animationDuration: 100
    };
    var args = $.extend(defaults, args);
    return this.each(function (_i, _item) {
      var $this = $(this),
				transactions = {},
				rows = [],
				sortOptions = {
				  col: 0,
				  dir: ''
				},
				ltIE9 = $.browser.msie && parseInt($.browser.version) <= 8,
				$overlay = $this.siblings('.overlay'),
				_loadData,
				_sortData,
				_showOverlay,
				_hideOverlay,
				_loadFilters,
				_zebra;
      _showOverlay = function () {
        //				$overlay = $('<div class="overlay"></div>');
        /*
        $overlay.animate({
        'opacity': 0.5,
        'z-index': '100'
        }, args.animationDuration);
        */
        $overlay.fadeTo(args.animationDuration, 0.5);
      };
      _hideOverlay = function () {
        /*
        $overlay.animate({
        'opacity': 0,
        'z-index': '-1'
        }, args.animationDuration), function() {
        //					$this.find('.overlay').remove();
        //				});
        */
        $overlay.fadeOut(args.animationDuration, 0);
      };
      _zebra = function () {
        if (ltIE9) {
          $this.find('tr:not(.header):nth-child(n)').css({ 'background': '#fff' });
          $this.find('tr:not(.header):nth-child(2n)').css({ 'background': '#f2f1f1' });
        }
      };
      _loadFilters = function (filters) {
        $('.filters').empty();
        for (var i in filters) {
          $label = $('<label for="filter-' + filters[i].name.replace(' ', '-') + '">' + filters[i].name + '</label>');
          options = '<option value="">All</option>';
          for (var j in filters[i].values) {
            options += '<option value="' + filters[i].values[j] + '"';
            options += (filters[i].selected == filters[i].values[j] ? ' selected="selected"' : '');
            options += '>' + filters[i].values[j] + '</option>';
          }
          $select = $('<select id="' + filters[i].name.replace(' ', '-') + '" name="' + filters[i].name.replace(' ', '') + '">' + options + '</select><br class="clear" />');
          $label.appendTo($('.filters:eq(' + (i % 3) + ')'));
          $select.appendTo($('.filters:eq(' + (i % 3) + ')'));
        }
        $('.filters select').unbind('change').bind('change', function () {
          dataFilters[$(this).attr('name')] = $(this).val();
          $('table#transactions').datatable({
            type: 'public',
            q: dataFilters,
            display: DATA_DISPLAY
          });
        });
      };
      _loadData = function (type, q, display) {
        DATA_DISPLAY = display;
        _showOverlay();
        $.ajax({
          // the url will change based on the Sitecore service that generates the JSON
          url: 'scripts/' + type + '-' + DATA_DISPLAY + '.js',
          data: q,
          dataType: 'json',
          error: function (jqXHR, textStatus, errorThrown) {
            alert('There was an error loading the data, please try again.');
            //						c('jqXHR: ' + jqXHR);
            //						c('textStatus: ' + textStatus);
            //						c('errorThrown: ' + errorThrown);
            _hideOverlay();
          },
          success: function (data) {
            obj = [];
            var transactions = data.rows,
							filters = data.filters,
							$label,
							$select,
							options

            $this.find('tr:gt(0)').remove();

            $this.find('#transactions-showing').text(data.transactionsShowing);
            $this.find('#transactions-total').text(data.transactionsTotal);

            _loadFilters(filters);

            if (DATA_DISPLAY == 'list') {
              var row = '<tr class="header">',
								type = data.type,
								counter = 0;
              for (var i in data.headers) {
                row += '<th style=""><a href="#" class="sort" rel="' + counter + '"><span>' + data.headers[i] + '</span></div></th>';
                counter++;
              }
              row += '</tr>'
              $(row).appendTo($this);
              $this.find('.sort').click(function (e) {
                _sortData($(this));
                e.preventDefault();
              });
              row = '';
              for (var i in transactions) {
                row += '<tr id="data-row-' + i + '">';
                for (var headerName in data.headers) {
                  if (transactions[i][headerName] != null && typeof (transactions[i][headerName]) == 'object') {
                    switch (type) {
                      case 'public':
                        row += '<td><span class="flag ' + data.rows[i][headerName].country.toLowerCase() + '"></span>';
                        row += '<p>' + transactions[i][headerName].city + ', ' + transactions[i][headerName].state + '</p></td>';
                        break;
                      case 'mergers':
                        row += '<td><span class="flag ' + transactions[i][headerName].country.toLowerCase() + '"></span>';
                        row += '<p>' + transactions[i][headerName].company + '</p></td>';
                        break;
                      default: ;
                    }
                  } else if (headerName == 'amount') {
                    if (typeof (transactions[i][headerName]) != 'string' || transactions[i][headerName] == "ND") {
                      row += '<td class="currency"><span rel="' +
													(typeof (transactions[i][headerName]) != 'string' ? transactions[i][headerName] : '0') +
													'">' +
													(typeof (transactions[i][headerName]) != 'string' ? '$' : '') +
													transactions[i][headerName].toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + '</span></td>';
                    } else {
                      row += '<td>' + transactions[i][headerName] + '</td>';
                    }
                  } else {
                    row += '<td>' + transactions[i][headerName] + '</td>';
                  }
                }
                row += '</tr>';
              }
              if ($this.find('.placeholder').length > 0)
                $this.find('.placeholder').parent().remove();
              $(row).appendTo($this);
              _zebra();
            } else if (DATA_DISPLAY == 'grid') {
              var filters = data.filters,
								tiles = data.tiles,
								tile = '<tr><td>';
              tile += '<label for="filter-stories">Show only transactions with stories</label><input type="checkbox" id="filter-stories" /><br />'

              for (var i in tiles) {
                tile += '<div class="featured-case ' + data.type + '">';
                tile += '<div class="title">' +

								(typeof (tiles[i].amount) != 'string' ? '$' : '') +
								tiles[i].amount.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

                tile += tiles[i].hasOwnProperty('story') ? '<a href="' + tiles[i].story + '" class="full-story"><span class="popup">View full story</span></a>' : '';
                tile += '</div>';
                tile += '<div class="content">';
                if (data.type == 'mergers') {
                  tile += '<div class="target">';
                  tile += tiles[i].target.hasOwnProperty('image') ? '<img src="' + tiles[i].target.image + '" />' : '';
                  tile += tiles[i].target.hasOwnProperty('description') ? '<span class="description">' + tiles[i].target.description + '</span>' : '';
                  tile += '</div>';
                  tile += '<div class="action">has been acquired by</div>';
                  tile += '<div class="acquirer">';
                  tile += tiles[i].acquirer.hasOwnProperty('image') ? '<img src="' + tiles[i].acquirer.image + '" />' : '';
                  tile += tiles[i].acquirer.hasOwnProperty('description') ? '<span class="description">' + tiles[i].acquirer.description + '</span>' : '';
                  tile += '</div>';
                } else if (data.type == 'public') {
                  tile += '<div class="company">';
                  tile += tiles[i].company.hasOwnProperty('image') ? '<img src="' + tiles[i].company.image + '" />' : '';
                  tile += tiles[i].company.hasOwnProperty('description') ? '<span class="description">' + tiles[i].company.description + '</span>' : '';
                  tile += '</div>';
                  tile += '<div class="transaction-type">' + tiles[i].transactionType + '</div>';
                }
                tile += '</div><div class="date">' + tiles[i].date + '</div></div>';
              }
              tile += '</td></tr>';
              $(tile).appendTo($this);
              $('a.full-story').unbind('hover').hover(function () {
                $(this).find('.popup').stop(false, true).fadeIn(100);
              }, function () {
                $(this).find('.popup').stop(false, true).delay(200).fadeOut(100);
              });
              $hasStory = $('.featured-case').filter(':not(:has(.popup))');
              $this.find('#filter-stories').change(function () {
                $hasStory.toggle();
              });
            }
            _hideOverlay();
          }
        });
      };
      _sortData = function ($col) {
        $this.find('tr.header th a').not($col).removeClass('desc asc');
        if ($col.hasClass('asc')) {
          $col.removeClass('asc').addClass('desc');
        } else if ($col.hasClass('desc')) {
          $col.removeClass('desc').addClass('asc');
        } else {
          $col.addClass('asc');
        }
        sortOptions.col = $col.attr('rel');
        sortOptions.dir = $col.hasClass('asc') ? 'asc' : $col.hasClass('desc') ? 'desc' : '';
        rows = [];
        $this.find('tr:not(.header, .data-display)').each(function () {
          rows.push($(this));
        });
        rows.sort(function (a, b) {
          if (a.find('td:eq(' + sortOptions.col + ')').hasClass("currency")) {
            if (sortOptions.dir == 'asc')
              return (a.find('td:eq(' + sortOptions.col + ') span').attr('rel') - b.find('td:eq(' + sortOptions.col + ') span').attr('rel'))
            else
              return -(a.find('td:eq(' + sortOptions.col + ') span').attr('rel') - b.find('td:eq(' + sortOptions.col + ') span').attr('rel'))
          } else {
            if (a.find('td:eq(' + sortOptions.col + ')').text() < b.find('td:eq(' + sortOptions.col + ')').text())
              return sortOptions.dir == 'asc' ? -1 : 1;
            else
              return sortOptions.dir == 'asc' ? 1 : -1;
          }
        });

        for (var i in rows) {
          rows[i].appendTo($this);
        }
        _zebra();
      };
      _loadData(args.type, args.q, DATA_DISPLAY);

    });
  }
})(jQuery);

/////
// replace selects
/////
(function ($) {
  $.fn.replaceSelect = function (args) {
    var defaults = {
  },
			args = $.extend(defaults, args);
  return this.each(function (_i, _item) {
    var $this = $(_item),
				$replacedSelect = $('<div class="select-replace" id="' + $this.attr('id') + '-replaced" rel="' + $this.attr('id') + '" />'),
				lis = '',
				$mainTrigger = $('<a href="#" class="selected">' + $this.find('option:selected').text() + '</a>').appendTo($replacedSelect),
				$dropdown = $('<ul />').appendTo($replacedSelect),
				_hide,
				_show;

    $this.after($replacedSelect);
    $dropdown.css('width', $replacedSelect.css('width'));
    $this.find('option').each(function () {
      lis += '<li><a href="#">' + $(this).text() + '</a></li>';
    });
    $this.hide();
    $dropdown.append(lis);
    $replacedSelect.find('> a').click(function (e) {
      if ($dropdown.filter(':animated').length > 0)
        return false;
      if ($dropdown.height() == 0) {
        _show();
      } else {
        _hide();
      }
      e.preventDefault();
      e.stopPropagation();
    });
    $dropdown.find('a').click(function (e) {
      $replacedSelect.find('> a').text($(this).text());
      $replacedSelect.find('a.selected').toggleClass('open');
      $this.val($(this).text());
      _hide();
      e.preventDefault();
      e.stopPropagation();
    });
    _show = function () {
      var h = 0;
      $dropdown.find('li').each(function () {
        h += $(this).outerHeight(true);
      });
      $dropdown.animate({
        height: h,
        opacity: 1
      }, 200);
    };
    _hide = function () {
      $dropdown.animate({
        height: 0,
        opacity: 0
      }, 200);
    };
    $('body').click(function (e) {
      $('.select-replace ul').each(function () {
        if ($(this).height() != 0) {
          $(this).animate({
            height: 0,
            opacity: 0
          }, 200);
        }
      });
    });
    //custom drop down style toggling

    $replacedSelect.find('a.selected').click(function () {
      $(this).toggleClass('open');
    });
    // debug
    /*
    $this.show();
    $this.css({
    position: 'absolute',
    right: 5,
    top: 25 * (_i) + 5,
    opacity: 0.75
    });
    */
    // end debug
  });
};
})(jQuery);

//initialize filter dropdown group custom styling
if ($('#result-filter').length > 0) {
  $('#result-filter').jqTransform();
}
$('#fb-request a.button').click(function (e) {
  // ajax call to submit the email goes here, on success will execute what's below
  $.fancybox($('#fb-confirm'));
  e.preventDefault();
});
$('#fb-confirm a.close').click(function (e) {
  $.fancybox.close();
  e.preventDefault();
});
$('a.request').click(function (e) {
  $.fancybox($($(this).attr('href')));
  e.preventDefault();
});
if ($('a.footer-popup').length > 0) {
  $('a.footer-popup').fancybox();
}
if ($('a.disclaimer-popup').length > 0) {
  $('a.disclaimer-popup').fancybox();
}

});

/* = RESULTS FILTER - simulate HTML5 placeholder attr
--------------------------------------------------------------------------------------------*/
$(document).ready(function () {
  $('.filter-group input').each(function () {
    $(this).val($(this).attr('placeholder'));
  });
  $('.filter-group a.resetBtn').closest('tr').find('input').focus(function () {
    $('.filter-group a.resetBtn').show();
    $('.filter-group a.resetBtn').css('display', 'block');
    if ($(this).val() == $(this).attr('placeholder')) {
      $(this).val('');
    }
  });
  $('.filter-group input').blur(function () {
    if ($(this).val() == '') {
      $('.filter-group a.resetBtn').hide();
      $(this).val($(this).attr('placeholder'));
    }
  });

  $('.filter-group a.resetBtn').click(function () {
    var targetInput = $(this).closest('tr').find('input');
    (targetInput).val($(targetInput).attr('placeholder'));
    $(this).hide();
  })
  $('.filter-group a.submit').click(function () {
    $(this).closest('form').submit()
  })

  /* = RESULTS FILTER - date picker
  --------------------------------------------------------------------------------------------*/
  if ($("#datepicker").length > 0) {
    $("#datepicker").datepicker();
  }


});

/////
// Investor Annex cookies
/////
function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  }
  else {
    begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) {
    end = dc.length;
  }
  return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}
function iaLogin(theForm) {
  if (theForm.rememberLogin.checked == true) {
    var now = new Date();
    now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365);
    setCookie("un", escape(theForm.loginId.value), now);
  } else {
    deleteCookie("un");
  }
  return (true);
}
