(function($){

/**
  <p>A way to find a classname by supplying a prefix piece of a classname.
  This is used as a simple way to both have a selector and a meta string to the selector</p>

  @author <a href="dilltree.com">Jeremy Dill</a>
  @param {Object} obj The html dom object or jquery object that has class applied
  @param {String} cl The class begins with this.. example to find "lnk_test", set this param to "lnk_"
  @param {Bool} rip If true, remove the cl piece of the classname and return the remainder
*/
$.findClass = function (obj,cl,rip) {
	var jobj=$(obj);
	if(!jobj.attr('class')) return "";
	var list=jobj.attr('class').split(" ");
	for(i = 0; i < list.length; i++){
 		if(list[i].indexOf(cl) >= 0) {
			if (rip) return list[i].substr(cl.length);
			else  return list[i];
		}
	};
	return "";
};

$.es = {
  Timer : function() {
    this.delay = 3000;
    this.timerId = null;
    this.running = false;
    this.tick = null;
    this.clear = null;
    this.start = function() {
      if (this.running) this.stop();
      if (this.tick) this.timerId = setTimeout(this.tick, this.delay);
      this.running = true;
    }
    this.stop = function() {
      if (this.timerId) clearTimeout(this.timerId);
      if (this.clear) this.clear();
      this.running = false;
    }
  },

  vidRegex : /(?:\.mp4|\.mov|\.ogg|\.mkv|\.flv|\.swf|\.f4v)$/i,

  isVideo : function(url) {
    return this.vidRegex.test($.trim(url));
  }
}

/* Home Billboard
  - .bb_arrow : generic class on left right arrows.
  - .bb_right & .bb_left : next & previous arrows.
  - nav expected to have id='nav_#' starting at 0. */
$.es.hb = function(slides, copy) {
  var self = this;
  self.activeId = -1;
  self.timerDisabled = false;
  self.init = function() {
    var navHtml = '<ul>';
    for (var x in slides) {
      navHtml += '<li><a id="nav_'+ x +'"> '+ (parseInt(x)+1) +' </a></li>';
    }
    navHtml += '</ul>';

    self.imgs = [];
    self.vids = [];
    self.wrap = $('#stage_wrap').click(function() {
      var x = slides[self.activeId];
      if (x.url) {
        if (x.targ == 'external') {
          var tst = window.open(x.url);
          if (tst) return;
        }
        window.location = x.url;
      }
    });
    self.loaderImg = $('#loader');

    self.nav = $('#billboard_nav').html(navHtml).find('ul li a').click(this.navClick).end();
    $('.bb_arrow').fadeIn();
    $('.bb_left').click(function() {
      self.timerDisabled = true;
      self.getPrevSlide();
    });
    $('.bb_right').click(function() {
      self.timerDisabled = true;
      self.getNextSlide();
    });

    self.setTimer();
    $('#nav_0').click();
  }

  self.navClick = function(e) {
    var clicked = parseInt(this.id.substring(4));

    if (clicked == self.activeId) {
      self.timer.stop();
      return false;
    }

    self.nav.find('a.active').removeClass('active');
    $(this).addClass('active');

    //Stop player
    if (self.swf && typeof(self.swf.sendEvent) == 'function') self.swf.sendEvent('stop');
    if (!$.es.isVideo(slides[clicked].src)) {
      // IS IMAGE
      if(!self.imgs[clicked]) {
        self.loader.load(slides[clicked].src, clicked);
      } else {
        self.showSlide(self.imgs[clicked]);
      }
    } else {
      // IS VIDEO
      if(self.vids[clicked]) { $(self.vids[clicked]).remove(); }
      var id = 'video_'+clicked;
      self.vids[clicked] = $('<div id="vid_'+ clicked +'"><div id="'+id+'" width="940" height="400"></div></div>')[0];
      self.wrap.append(self.vids[clicked]);

      var attr = { data:"/_swf/player.swf", height:"400", width:"940", id:id, name:id };
      var par = { menu:false, wmode:'transparent', allowfullscreen:false, allowscriptaccess:'always', flashvars:"file="+slides[clicked].src+"&controlbar=none&autostart=true" };
      self.swf = swfobject.createSWF(attr, par, id);
      self.activeId = clicked;
    }

    if (!e.originalEvent && !self.timerDisabled) {
      self.timer.delay = (slides[clicked].time > 0) ? slides[clicked].time * 1000 : 5000;
      self.timer.start();
    } else {
      self.timer.stop();
    }
  }

  self.showSlide = function(obj) {
    var visible = self.wrap.find('div.billboard_item:visible').not(obj);
    var clicked = $(obj);

    if (visible.index() > clicked.index()) {
      clicked.stop(1,1).show().css('z-index','10').animate({opacity:1},10,function() {
        visible.stop(1).animate({opacity:0},'medium',function() { $(this).hide().css('z-index','0'); });
      });
    } else {
      clicked.stop(1,1).show().css('z-index','10').animate({opacity:1},'medium',function() {
        visible.stop(1).animate({opacity:0},10,function() { $(this).hide().css('z-index','0'); });
      });
    }
    self.activeId = obj.id.substring(4);
    if (slides[self.activeId].url) clicked.css('cursor','pointer');
  }

  self.loader = new function() {
    this.timer = new $.es.Timer();
    this.timer.delay = 200;
    this.timer.tick = function() {
      self.loaderImg.show();
    }
    this.load = function(url,id) {
      var img = new Image();
      img.onload = function() {
        self.loader.stop();
        this.useMap = "#map_"+(id+1);
        var newDiv = $('<div id="img_'+id+'" class="billboard_item hd_billboard no_b">');
        self.imgs[id] = newDiv.hide().css('opacity',0).append($(this))[0];
        self.addCopy(newDiv, id);
        self.wrap.append(self.imgs[id]);
        self.showSlide(self.imgs[id]);
      }
      img.onerror = function() {
        self.loader.stop();
        self.activeId = id;
        self.wrap.find('div:visible').animate({opacity:0},'medium',function() { $(this).hide(); });
      }
      this.timer.start();
      img.src = url;
    }
    this.stop = function() {
      self.loader.timer.stop();
      self.loaderImg.hide();
    }
  }

  self.getNextSlide = function() {
    if (self.activeId < slides.length - 1) var next = '#nav_'+(parseInt(self.activeId)+1);
    else var next = '#nav_0';
    $(next).click();
  }

  self.getPrevSlide = function() {
    if (self.activeId > 0) var prev = '#nav_'+(parseInt(self.activeId)-1);
    else var prev = '#nav_'+(slides.length-1);
    $(prev).click();
  }

  self.setTimer = function() {
    self.timer = new $.es.Timer();
    self.timer.tick = function() {
      self.getNextSlide();
      self.timer.stop();
      self.timer.start();
    }
  }

  self.addCopy = function(newDiv, id) {
    if (copy[id].head == "" && copy[id].copy == "") return;

    var addTo = '<div class="desc '+copy[id].head_color+'">';
    if (copy[id].head != "")   addTo += "<h1>"+copy[id].head+"</h1>";
    if (copy[id].copy != "")   addTo += "<div>"+copy[id].copy+"</div>";
    if (copy[id].button != "") addTo += copy[id].button;
    addTo += '</div>';

    newDiv.append(addTo);
  }

  self.init();
}


$.es.setEqualHeight = function(columns, padding) {
    if (padding == undefined) padding = 30;
    var tallestcolumn = 0;
    columns.each( function() {
      currentHeight = $(this).height();
      if(currentHeight > tallestcolumn){
          tallestcolumn  = currentHeight;
      }
    }
  );

  columns.height(tallestcolumn + padding);
}

})(jQuery);

//--------------SITE JS--------------//
var fuor = {};

/* Resource Toggle */
fuor.toggle = function(options) {
  obj = $.extend({
    'nav':null,
    'panes':null,
    'time':null,
    'start':0
  }, options);

  if (!obj.panes) return false;
  var active = obj.start;
  var panes = $(obj.panes);
  panes.not(panes[active]).hide().css('opacity',0);
  var timer = null;

  var showPane = function(x) {
    $(x).stop(1).show().animate({'opacity':1},'medium');
    panes.not(x).stop(1).animate({'opacity':0},'medium',function() { $(this).hide(); });
  }

  var showNext = function() {
    if (timer) timer.start();
    if (active < panes.length-1) { showPane(panes[++active]); }
    else { active=0; showPane(panes[active]); }
  }

  // setup timer
  if (obj.time) {
    timer = new $.es.Timer();
    if (obj.time > 0) timer.delay = obj.time * 1000;
    else timer.delay = 5000;
    timer.tick = showNext;
  }

  // setup nav
  if (obj.nav) {
    var nav = $(obj.nav);
    $(nav[active]).addClass('active');

    nav.click(function(x) {
      if (timer) { timer.stop(); timer = null; }
      var clicked = $(x.target);
      var id = clicked.index();
      nav.removeClass('active');
      clicked.addClass('active');
      showPane(panes[id]);
      active = id;
      return false;
    });
  }

  if (timer) timer.start();
}

fuor.showcaseFilter = function() {
  var $ = jQuery;
  var self = this;

  var list = {};
  var wrap = $('#grid_wrap');

  wrap.find('li a').each(function() {
    list[this.id] = 0;
  });

  $('#filter_list input[type="checkbox"]').each(update).change(change);

  function update() {
   if (this.checked) {
      wrap.find('li a[class*="'+this.id.substr(3)+'"]').each(select);
    }
  }

  function change() {
    if (this.checked) {
      wrap.find('li a[class*="'+this.id.substr(3)+'"]').each(select);
    } else {
      wrap.find('li a[class*="'+this.id.substr(3)+'"]').each(deselect);
    }
  }

  function select() {
    list[this.id] ++;
    $(this).addClass('selected');
  }

  function deselect() {
    if (list[this.id] > 0) list[this.id] --;
    if (list[this.id] == 0) {
      $(this).removeClass('selected');
    }
  }

  wrap.find('.filter_reset').click(function() {
    $('#filter_list input:checked').attr('checked',false).trigger('change');
    return false;
  });
}

fuor.newsScroll = function() {
  var $ = jQuery, call;
  var content = $('#nl_wrap');
  var xload = $('#xload').css({'opacity':0.85});

  var scroll = $('#scroll').scrollable({'mousewheel':true}).find('.news_block').click(function() {
    if ($(this).is('.active')) return false;
    var url = $(this).find('.x_url').attr('href');
    window.location.hash = url;
    scroll.each(function() { if ($(this).is('.active')) $(this).removeClass('active') });
    $(this).addClass('active');
    if (call) { call.abort(); }

    if (typeof(ldr) != 'undefined') ldr.stop();
    var ldr = new $.es.Timer();
    ldr.delay = 550;
    ldr.tick = function() { xload.height(content.outerHeight(1)).show(); };
    ldr.clear = function() { xload.hide(); };
    ldr.start();

    call = $.ajax({
      type: "GET",
      url: '/resources/newsletters/bare/'+url,
      dataType: 'html',
      success: function(data) {
        content.html(data);
      },
      error: function() {
        content.html("<h3>We're Sorry</h3>The newsletter you requested was not found.  Please try again.");
      },
      complete: function() {
        ldr.stop();
      }
    });

    return false;
  });

  var hash = window.location.hash.substr(1);
  if (hash) {
    scroll.find('a[href='+hash+']').parent('.news_block').click();
  }
}

fuor.careerForm = function() {
  //--------------Career Application Form--------------//
  // auto-select the position in the drop down
  // if the url has a #hash that matches the id of an open position
  var $careerform = $('#careerform select[name=career_position]');

  // if we see an application form
  if ($careerform.length) {
    $('.x_apply').click(function() {
      var id = $.findClass(this,'job_',0);
      $careerform.children("option."+id).attr('selected', 'selected'); // select that option
    });

    if(window.location.hash) {
      var id = window.location.hash.substr(1); // trim the # from the hash (e.g. #61 = 61)
      $careerform.children("option."+id).attr('selected', 'selected'); // select that option
    };
  }
}

fuor.setHome = function() {
  var tallest = 0;

  function check(ht) { 
    if (ht > tallest) tallest = ht;
  }

  var hs = $('#home_shelf');

  var first = hs.find('.first_col');

  hs.find('.toggled_pane').each(function(){ check($(this).height() + first.height()); });
  hs.find('.home_col').each(function(){ check($(this).height()); });

  first.find('.gen_col').height(tallest);

  var mid = hs.find('.mid_col');
  var callout = mid.find('.callout').outerHeight(1) || 0;
  mid.find('.bbriefs').height(tallest - callout);

  var last = hs.find('.last_col');
  var lastlast = last.find('div:last');
  lastlast.height(tallest - (last.height() - lastlast.height()) + 2);
}

fuor.sideNavActive = function() {
  var bg = "/_img/bg_bionav.png";
  var nav = $('#nav-sub');
  if (nav.length > 0) {
    var here = nav.find('.here');
    if (here.length > 0) {
      var img = new Image();
      var a = here.find('a');
      img.onload = function() {
        var html = "<img src='"+bg+"' class='bg' style='width:"+a.outerWidth()+"px;height:"+a.outerHeight()+"px;' />";
        here.prepend(html);
      }
      img.src = bg;
    }
  }
}

fuor.fixBriefs = function() {
  var leadership = $('.c_leadership');
  var max = 0;
  
  function check() {
    var x = $(this).height();
    if (x > max) max = x;
  }
  
  leadership.find('.toggled_pane').each(check);
  
  leadership.height(max + $('#toggle_nav').outerHeight(1));
  
}

// global load
jQuery(function() {
  $('.external').attr('target','_blank');
  $('ul.sf-menu').superfish({ delay: 0, autoArrows: false, speed: 200, dropShadows: true});
  $('#search input').click(function() {
    if (this.value == 'Search') this.value = '';
  }).blur(function() {
    if (this.value == '') this.value = 'Search';
  });

});


