$('html').addClass('js');

if (typeof $.fn.ifixpng != 'undefined') {
  $.ifixpng('/assets/images/pixel.gif');
}

$(document).ready(function() {

  // $('#lang-switch').change(function() {
  //   location.href = this.value;
  // });

  $('.biglink').biglinks();

  /** ===cycle
  ************************************************************
  ************************************************************/

  if (typeof $.fn.cycle != 'undefined') {
    if ($.browser.mozilla === true && (/1\.8/.test($.browser.version))) {
	    $('body').css('-moz-opacity', '.99999');
	  }

	// newsticker cycle
  	$('#home-news ul').cycle({
      		fx:     'scrollHorzAndFade',
  	      speed:  700,
  	  		// fx:     'fade',
  	  		//         speed:  300,
  	      timeout: 5000,
  	      pause: true,
  	      next:   '#home-news-next',
  	      prev:   '#home-news-prev',
  				cleartype: true
  	  });

  	// homepage slideshow cycle
  	$('#home-slideshow').cycle({
      	// fx:     'scrollUp',
      	fx:     'fade',
        speed:  800,
        timeout: 8000,
        pause: true

    });

  	// slideshow cycle
  	$('#slideshow').cycle({
      	// fx:     'scrollUp',
      	fx:     'fade',
        speed:  800,
        timeout: 8000,
        pause: true
    });
  }
	// rounded corner and shadow for slideshow
  $('#slideshow, a.bucket').append('<b class="decor"></b>');
	if (typeof $.fn.ifixpng != 'undefined') {
    $('#slideshow b.decor').ifixpng();
  }
  if (typeof $.fn.media !== 'undefined') {
    $('#flash-banner').media({
      width: 852,
      height: 167,
      bgColor: 'transparent',
		 	params: {wmode: "transparent"}
    });
  }

	// ruled style for content-intro
	$('#content-intro').wrapInner('<span></span>');

  /** ===Navigation
  ************************************************************
  ************************************************************/

  // main nav - reveal sub-items on hover (with delay)
  $('#nav-main').superfish({
    animation: {height: 'show'},
    delay: 400,
    speed: 300
  });

  var $langMenu = $('#nav-languages > ul'),
      $activeLang = $('#nav-utility li a.active'),
      closeLangMenu;

  $('#nav-languages > a').click(function() {
    clearTimeout(closeLangMenu);
    if (!$langMenu.is(':animated')) {
      $langMenu.slideToggle(250);
    }
    return false;
  }).next('ul').hover(function() {
    clearTimeout(closeLangMenu);
    $activeLang.removeClass('active');
  }, function() {
     closeLangMenu = window.setTimeout(function() {
      $langMenu.slideUp(250);
      $activeLang.addClass('active');
    }, 350);
  });

  // main navigation sub-nav arrows

  var arrows = [
    'nav-main-sub-arrow.png',
    'nav-main-sub-arrow-hover.png'
  ];

  for (var i = arrows.length - 1; i >= 0; i--) {
    var navImg = document.createElement('img');
    navImg.src =   '/assets/images/' + arrows[i];
  }
  $('#nav-main ul li:has(ul)').addClass('arrow');

  /** ===SHADOWBOX
  ************************************************************
  ************************************************************/

  //shadowbox for image and video
  var $sb = $('a.sb');
  if (typeof Shadowbox !== 'undefined' && $sb.length) {

    // add simple rel="shadowbox" to all link with class="sb" so shadowbox will work with it
    $('ul.media-gallery').each(function(index) {
      $('a.sb', this).filter(function() {
        return !$(this).is('.sb-video') && !$(this).parents('sb-video').length;
      }).attr('rel', 'shadowbox[group' + index + ']');
    });


    // set height and width of videos
    $('.sb-video a, a.sb-video').attr({'rel': 'shadowbox[group];width=654;height=370'});

    // make link's container element clickable and add a zoom button image
    $sb.parents('.sb-link')
    .click(function() {
      $('a', this).triggerHandler('click');
    })
    .append('<span class="zoom">zoom</span>');
    if (typeof $.fn.ifixpng != 'undefined') {
    $('.sb-link span.zoom').ifixpng();
  }
    // set Shadowbox option and attach to links
    var sbOpening = false;
    var sboptions = {
      assetURL:  '/',
      loadingImage: 'assets/images/loading.gif',
      overlayBgImage:     'assets/images/overlay-85.png',
      flvPlayer: 'scripts/flvplayer.swf',
      keysClose:          ['c', 27] // c or esc
    };

    sboptions.onFinish = function() {
      if ($.browser.msie === true ) {
        $('#shadowbox_nav_close')
        .css({
          left: '-6px', 
          top: '-6px'
        });
        
        if (parseInt($.browser.version,10) < 7) {
          $('#shadowbox_nav_close')
          .find('a').ifixpng();
        }
      }
    };
      
    var shadowBoxText = {
      ja: {
        cancel:     'キャンセル',
        loading:    'ローディング',
        close:      '閉じる',
        next:       '次へ',
        prev:       '戻る',
        counter:    {
            pre: '',
            of: '/',
            post: ''
        },
        errors:     {
            single: 'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',
            shared: 'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',
            either: 'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'
        }
      },
      de: {
          cancel:     'Abbrechen',
          loading:    'Lädt...',
          close:      'Schließen',
          next:       'weiter',
          prev:       'Zurück',
          errors:     {
              single: 'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',
              shared: 'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',
              either: 'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'
          }
      },
      zh: {
        cancel:     '取消',
        loading:    '加载',
        close:      '关闭',
        next:       '下一步',
        prev:       '上一步',
        counter:    {
            pre: '第 ',
            of: ' 页，共 ',
            post: ' 页'
        },
        errors:     {
            single: 'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',
            shared: 'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',
            either: 'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'
        }

      }
    };
    $.getJSON('/global/language_code',
     function(json){
        var lang = json.lang_code;
        if (typeof shadowBoxText[lang] != 'undefined') {
          sboptions.text = shadowBoxText[lang];
        }
        Shadowbox.init(sboptions);
    });
  }

	// column lists
	if ($.fn.columns) {
	  $.fn.columns.defaults.columnClass = 'column-float';
    $('.2col').columns({columns: 2});
    $('.3col').columns({columns: 3});
    $('.4col').columns({columns: 5});
    $('#global-expert ul:not(.media-gallery)').columns({columns: 4});
  }

	// styles for buttons
	$('a.btn').wrapInner('<span></span>');

});

// show another employer fieldset

$(document).ready(function() {
  if ($('body').hasClass('page-3')) {
    var $addEmployer = $('<a href="#" class="add">+ Add Another Employer</a>')
      .insertAfter('fieldset.employer:last');
    $addEmployer.click(function() {
      $('fieldset.employer:hidden:first').slideDown(400, function() {
        if (!$('fieldset.employer:hidden').length) {
          $addEmployer.hide();
        }
      });
      this.blur();
      return false;
    });
  }
});


/** =CAREER APPLICATION
************************************** */

$(document).ready(function() {
  var $positions = $('#position_of_interest').parent().hide().end();
  if ( $positions.length ) {
    var $dept = $('#department_of_interest');
    $dept.change(function() {
      var deptVal = $dept.val();
      if (deptVal) {
        $positions.attr('disabled', true).prev('label').addClass('loading').parent().slideDown();
        $.get('/careers/positions', {dept: deptVal}, function(html){
          $positions.removeAttr('disabled').html(html).prev('label').removeClass('loading');
        });

      } else {
        $positions.html('').parent().slideUp();
      }
    }).trigger('change');
  }
  var $hear_other = $("#how_did_you_hear_other").parent().hide();
  $("#how_did_you_hear").change(function() {
    var $hear = $(this);
    if ( $hear.val() == "Other" ) {
      $hear_other.slideDown();
    } else {
      $hear_other.slideUp();
    }
  });
});

// validate job application forms
$(document).ready(function() {
  if (typeof $.fn.tinyvalidate != 'undefined') {
    $('#application, #complete-application, .validate').tinyvalidate({
      positionElement: ['inline','form'],
      primaryEvent: 'submit',
      secondaryEvent: null,
      submitDetails: false
    });
    $('div.month-year').each(function(index) {
      var $monthYear = $(this);
      if ($monthYear.next().val()) {
        var dateParts =  $(this).next().val().split('/');
        $monthYear.find('.month').val(dateParts[0]);
        $monthYear.find('.year').val(dateParts[2] || '');
      }
    });
    $('div.month-year select').bind('change', function(event) {
      var $monthYear = $(this).parent(),
          $input = $monthYear.next();
      var day = /end/.test($input[0].id) ? '/28/' : '/01/';
      var fullDate = ($monthYear.find('.month').val() || '01') + day + $monthYear.find('.year').val();
      $input.val(fullDate);
    });
    
    $('input.optional, textarea.optional')
      .prev('label, div.label').add('legend.optional')
      .each(function() {
        $(this).append(' <span class="aside">(optional)</span>');
    });
    function toggleDivs() {
      var $conditional = $('.conditional');
      var els = [
          {
              eltype: 'select',
              eltest: function(el) {
               return el.val() == '[other]';
              },
              binder: 'change'
          },
          {
              eltype: 'input:radio',
              eltest: function(el) {
                return el.is(':checked');
              },
              binder: 'click'
          }
      ];
      $conditional.each(function() {
        var $this = $(this),
          $toggler = $this.prev().find('.toggler:first');

        for (var i=0; i < els.length; i++) {
          if ($toggler.is(els[i].eltype)) {
            var thisel = els[i];
            if (thisel.eltest($toggler)) {
              $this.show();
            } else {
              $this.hide()
                .find('input:text').val('')
                .end()
                .find('input:radio').attr('checked', false);
            }

            $this.prev().find(thisel.eltype).bind(thisel.binder, function() {
              if (thisel.eltest($toggler)) {
                $this.slideDown('fast');
              } else {
                $this.slideUp('fast')
                  .find('input:text, textarea').val('')
                  .end()
                  .find('input:radio').attr('checked', false);
              }
            });
          }
        }
      });
    }

    toggleDivs();
  }

});

// row striping for application review
$(document).ready(function() {
  $('#application tbody tr:has(td):nth-child(odd)').addClass('alt');
});


// define scrollHorzAndFade transition
(function($) {
$.fn.cycle.transitions.scrollHorzAndFade = function($cont, $slides, opts) {
    $cont.css('overflow','hidden').width();
    opts.before.push(function(curr, next, opts, fwd) {
        $(this).show();
        var currW = curr.offsetWidth, nextW = next.offsetWidth;
        opts.cssBefore = fwd ? { left: -nextW } : { left: nextW };
        opts.animIn.left = 0;
        opts.animOut.left = fwd ? currW : -currW;
        $slides.not(curr).css(opts.cssBefore);
    });
    opts.cssFirst = { left: 0 };
    opts.animIn  = { opacity: 1 };
    opts.animOut  = { opacity: 0 };
    opts.cssAfter = { display: 'none' };
};

})(jQuery);

$(document).ready(function() {
	$('.accordion li').addClass('collapsed');
	$('.accordion-body:first').slideDown('fast').parent().toggleClass('collapsed');
	$('.accordion .accordion-head').click(function() {
		$(this).next().stop(false, true).slideToggle('fast').parent().toggleClass('collapsed');
		return false;
	});
});

/** =form toggle
************************************************************/
$(document).ready(function() {
	$('.form-toggle a').click(function() {
		var formId = $(this).attr('href');
			$(formId).slideToggle(400);
		return false;
	});
});
