/* --- LOGGING ---------------------------------------------------------------- */

window.log = function() { 
  log.history = log.history || [];
  log.history.push(arguments);
  window.console && console.log[console.firebug ? 'apply' : 'call'](console,Array.prototype.slice.call(arguments));
};
 
window.logargs = function(context) {
  log(context,arguments.callee.caller.arguments);
};

jQuery.fn.doOnce = function(func){ 
  this.length && func.apply(this);
  return this; 
}


/* --- BASE ---------------------------------------------------------------- */

var Radiometer = {
  init: function() {
    Radiometer.navigation();
    Radiometer.carousel.init();
    Radiometer.cufonInit();
    Radiometer.tabs();
    Radiometer.quickpoll();
    Radiometer.pager();
    
    if($.tablesorter) {
      // add new sorting for "bytes"
      $.tablesorter.addParser({ 
        id: 'filesize',
        is: function(s) {
          return s.match( new RegExp( /[0-9]+(\.[0-9]+)?\ (KB|B|GB|MB|TB)/ ) );
        },
        format: function(s) {
          var suf = s.match( new RegExp( /(KB|B|GB|MB|TB)$/ ) )[1];
          var num = parseFloat( s.match( new RegExp( /^[0-9]+(\.[0-9]+)?/ ) )[0] );

          switch( suf ) {
            case 'B':
              return num;
            case 'KB':
              return num * 1024;
            case 'MB':
              return num * 1024 * 1024;
            case 'GB':
              return num * 1024 * 1024 * 1024;
            case 'TB':
              return num * 1024 * 1024 * 1024 * 1024;
          }
        },
        // set type, either numeric or text 
        type: 'numeric' 
      });
      
      $(".tablesort").tablesorter({
        sortList: [[0,0]]
      });
    }
    
    // eCard landing page spots
    /*$('.spot-video a.spot-video-player').hover(function() {
      $(this).find(' .inner').stop().animate( { bottom: '-88px' }, 150);
      $(this).find('h3').stop().animate( { height: '45px' }, 150 );
    },
    function() {
      $(this).find(' .inner').stop().animate( { bottom: '-149px' }, 150 );
      $(this).find('h3').stop().animate( { height: '59px' }, 150 );
    });*/
    $('.spot-video a.spot-video-player').click(function(e) {
      var windowheight = 468;
      videoelm = $(''+$(this).attr('href'));
      videoelm.dialog({
        height: windowheight,
        width: 750,
        open: Radiometer.ecardVideoShow,
        close: Radiometer.videoStop,
        cancel: Radiometer.videoStop,
        modal: true
      });
      return false;
    });
  },
  videoStop: function() {
    // remove former flash movie. This makes IE restart the movie, including sound
    $('.ui-dialog-content div#video1, .ui-dialog-content div#video2, .ui-dialog-content div#video3').html('');
    if (videoelm && videoelm.pause) {
      videoelm.stop();
    }
  },
  
  ecardVideoShow: function(event) {
  try
    {
      switch(event.target.id) {       
        case 'dialog-modal-video01':
          insertvideo1();
          break;
        case 'dialog-modal-video02' :
          insertvideo2();
          break;
        case 'dialog-modal-video03' :
          insertvideo3();
          break;
      }
    } catch(err)
    {
    //Handle errors here
    }
  },
  
  navigation: function() {
    $('#primary-nav').doOnce(function() {
      $(this)
      .supersubs({ 
        minWidth: 9,
        maxWidth: 27,
        extraWidth: 1
      })
		.find('ul').parent().addClass('branch').hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
    });
	$('#primary-nav > li > a, #header, #nav, #content').hover(Radiometer.navigationCufonUpdater, Radiometer.navigationCufonUpdater);
	Radiometer.navigationCufonUpdater();
  },
  
  navigationCufonUpdater: function() {
	if(! ($.browser.msie && Number($.browser.version) <= 7.0)) {
		Cufon.replace('#primary-nav > li > a', { color: '#7a95a2', background: '#fff'  });
		Cufon.replace('#primary-nav > li > a:hover, #primary-nav > li.hover > a, #primary-nav > li.hover.active > a', { color: '#fff', background: '#fa9119' });
		Cufon.replace('#primary-nav > li.active > a', { color: '#fff' }); 
		//window.setTimeout(Radiometer.navigationCufonUpdater, 10);
	}
  },
  
  tabs: function() {
    $('div.tabs').doOnce(function() {
      $(this).tabs();
    });
  },
  
  /*
  * Animate Quick Poll votes
  */
  quickpoll: function() {
    $('.scPollOptionItemResult').each(function() {
      var $this = $(this);
      var _width = $this.find('.scPollVisualisation img').css('width');
      $this.find('img').width('0px').animate({'width':_width}, 2000);
    });
  },
  
  pager: function() {
	if(!$.pager) 
		return false;
    $('#search-results').pager('li', {
      highlightClass: 'active',
      prevText: '&laquo; Back',
      nextText: 'Forward &raquo;',
      linkWrapInner: '<span />',
      navId: 'pager',
      navClass: 'search-result-pagination'
    });
  },
  
  cufonInit: function() {		
	Cufon.replace('#primary-nav > li > a', { color: '#7a95a2', background: '#fff' });
	Cufon.replace('#primary-nav > li.hover > a', { color: '#fff', background: '#fa9119' });
	if( ($.browser.msie && Number($.browser.version) > 7.0)) {
		Cufon.replace('#primary-nav > li > a:hover', { color: '#fff', background: '#fa9119' });
		Cufon.replace('#in-your-department h3 a:hover, #in-your-department h3 a.active', { color: '#fff' });
	}
	else {
		Cufon.replace('#primary-nav > li > a', { color: '#7a95a2', background: '#fff', hover: true });
		Cufon.replace('#in-your-department h3 a, #in-your-department h3 a.active', { color: '#fff', background: '#fff', hover: true });
	}
	Cufon.replace('#primary-nav > li.active > a', { color: '#fff' }); 
	
	Cufon.replace('#in-your-department h3 a', { color: '#4f6a7b', hover: true });
	Cufon.replace('#in-your-department h3 a.active', { color: '#fff' });
	Cufon.replace('.scButtons a', { color: '#fff', hover: true });
	Cufon.replace('h1, .block h3, .block.quote p, .cufon-me, div.overlay-content h2, .cufon-my-h2 h2, blockquote p, blockquote cite, .office-list h2, .teaser, .overlay-content p, .spot h3, .news-and-events h3, .in-your-department-sub li a' );
	/* eCard page */
	Cufon.replace('.spot-video-player h3, .spot-video-player p', { color: '#fff', hover: { color: '#fff' } });
	Cufon.replace('.spot-video-bottom', { color: '#fff', hover: { color: '#fff' } });
	Cufon.replace('.highlight-bg h2', { color: '#4f6a7b' });
  }
};

Radiometer.carousel = {
  activeSlide: 0,
  itemWidth: null,
  autoSlideInterval: false, /* if false, auto slide is aborted */
  
  init: function() {
    var $slides = $('#carousel-slides li');
    if ($slides.length) {
      Radiometer.carousel.itemWidth = $slides.first().width();
      $('#carousel-slides').width(Radiometer.carousel.itemWidth * $slides.length);
      this.createNavigation($slides);
	  if($('body').is('.front')) {
		//Radiometer.carousel.autoSlideInterval = 10000;
		Radiometer.carousel.updateNavigation();
		Radiometer.carousel.autoSlideInit();
		$('#in-your-department h3 a').hover(function() {
			var num = $(this).parent().prevAll('h3').length;
			Radiometer.carousel.slideTo(num);
			Radiometer.carousel.autoSlideStop();
			Radiometer.carousel.updateNavigation();
		});
		$slides.find('img').addClass('clickable').click(function() {
			window.location = $(this).parent().find('.overlay-content .scButtons a').attr('href');
		});
	  }
    }
  },
  
  createNavigation: function($slides) {
    var $nav = $('<ul></ul>').attr('id', 'carousel-navigation');
    $slides.each(function(i) {
      var text = $(this).find('h2').text();
      var $li = $('<li></li>').append('<a title="Go to slide ' + (i + 1) + '" href="#">' + text + '</a>');
      $li.data('num', i+1);
      if (i === Radiometer.carousel.activeSlide) {
        $li.addClass('active');
      }
      $nav.append($li);
    });
	$nav.find('li:last-child a').addClass('last');
    
    $nav.find('a').click(Radiometer.carousel.clickHandler);
    $('#carousel').append($nav);
  },
  
  clickHandler: function() {
    // Trigger custom event.
    var oldSlideNum = Radiometer.carousel.activeSlide;
	var $this = (this.tagName && this.tagName.toLowerCase() == 'a') ? $(this) : $('#carousel-navigation li.active a');
    var newSlideNum = $this.parent().data('num');
    $('#carousel').trigger('slideChange', [newSlideNum, oldSlideNum]);
    
    Radiometer.carousel.activeSlide = newSlideNum;
	if(this.tagName && this.tagName.toLowerCase() == 'a') {
		Radiometer.carousel.autoSlideStop();
		if ($this.hasClass('last')) {
			var num =  $('#carousel-navigation li.active a').parent().prevAll('li').length + 1;
		  if (num >= $('#carousel-slides li').length) {
			num = 0;
		  }
		}
		else {
		  var num = $this.parent().prevAll('li').length;
		}
	}
	else {
		var num = newSlideNum;
		if(num == 0)
			num++;
		if(isNaN(num) || num > $('#carousel-navigation li').length-1)
			num = 0;
	}
    var pos = -Radiometer.carousel.itemWidth * num + 'px';
    $('#carousel-slides').stop().animate({marginLeft: pos}, 250);
    
    Radiometer.carousel.updateNavigation();
    return false;
  },
  
  slideTo: function(newSlideNum) {
    var oldSlideNum = Radiometer.carousel.activeSlide;
    $('#carousel').trigger('slideChange', [newSlideNum, oldSlideNum]);
	
	Radiometer.carousel.activeSlide = newSlideNum;
	
    var pos = -Radiometer.carousel.itemWidth * newSlideNum + 'px';
    $('#carousel-slides').stop().animate({marginLeft: pos}, 250);
  },
  
  updateNavigation: function() {
	$('#carousel-navigation li').removeClass('active').filter(':eq('+Radiometer.carousel.activeSlide+')').addClass('active');
	$('.front #in-your-department h3 a').removeClass('active').filter(':eq('+Radiometer.carousel.activeSlide+')').addClass('active');
	if(! ($.browser.msie && Number($.browser.version) <= 7.0)) {
		Cufon.replace('#in-your-department h3 a', { color: '#4f6a7b' });
		Cufon.replace('#in-your-department h3 a:hover, #in-your-department h3 a.active', { color: '#fff' });
	}
  },
  
  getActiveSlide: function() {
    var $slide = $('#carousel-slides li:eq('+ Radiometer.carousel.activeSlide + ')');
    return $slide; 
  },
  
  hideSlideContent: function() {
    var $slide = Radiometer.carousel.getActiveSlide();
    $slide.find('div.overlay-content').hide();
    $slide.find('div.complete-content').hide();
  },
  
  showSlideContent: function() {
    $('#carousel-slides').find('div.overlay-content').show();
    $('#carousel-slides').find('div.jwplayer').show();
    $('#carousel-slides').find('div.complete-content').hide();
  },
  
  autoSlideInit: function() {
	if(Radiometer.carousel.autoSlideInterval != false) {
		var $autoClock = $('<div><div></div></div>').attr('id', 'carousel-clock');
		$autoClock.find('div').attr('id', 'carousel-clock-inner');
		$('#carousel').append($autoClock);
		Radiometer.carousel.updateNavigation();
		Radiometer.carousel.autoSlide();
	}
  },
  
  autoSlide: function() {
	var $autoClock = $('#carousel-clock-inner').css('width', '0');
	$autoClock.animate({width:'100%'}, Radiometer.carousel.autoSlideInterval, function() {
		Radiometer.carousel.activeSlide++;
		if(Radiometer.carousel.activeSlide >= $('#carousel-slides li').length) {
			Radiometer.carousel.activeSlide = 0;
		}
		Radiometer.carousel.slideTo(Radiometer.carousel.activeSlide);
		Radiometer.carousel.updateNavigation();
		Radiometer.carousel.autoSlide();
	});
	//Radiometer.carousel.clickHandler();
  },
  
  autoSlideStop: function() {
	$('#carousel-clock-inner').stop().parent().remove();
  }
  
};

$(document).ready(Radiometer.init);

//closes the dialog window if the user clicks outside of the window.
$(".ui-widget-overlay").live("click", function() { 
	$(":ui-dialog").each(function(){
		var $this = $(this);
		if($this.dialog("isOpen")){
      Radiometer.videoStop();
			$this.dialog("destroy");
		}
	}); 
});
