//*****Replace align attribute with class**************************************************//
function replaceAlign() {
  if (!document.getElementsByTagName('img')) return false;
  $('img[align="left"]').addClass('left').removeAttr('align');
  $('img[align="right"]').addClass('right').removeAttr('align');
  $('img[align="middle"]').addClass('middle').removeAttr('align');
}
//*****Replace target attribute with class**************************************************//
function replaceTarget(){
	$('a[target]').not('a[target=_self]').removeAttr('target').addClass('newwindow');
  $('a[target]').removeAttr('target');
}
//*****The following function make it possible to have web standard popups**************************************************//
function strictNewWindow() {
  $('a.newwindow').live('click', function(){
    window.open($(this).attr('href'));
    return false;
  });
}
//*****jQuery clear value from july 21st 2009 comment on http://www.joesak.com/2008/11/19/a-jquery-function-to-auto-fill-input-fields-and-clear-them-on-click*****//
function clearDefaultValue() {
  $(':input').focus(function() {
    if($(this).val() == $(this).attr('title')) {
      $(this).val('');
    }
  }).blur(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('title'));
    }
  });
  $('input[type="submit"]').mousedown(function() {
	  $(':input').each(function (i) {
      if($(this).val() == $(this).attr('title')) {
        $(this).val('');
      }
    });
  });
}
//*****Home scrollable div*************************************************//
function homeScroller(){
	if($('#home').length){
		var settings = {
			showArrows: true,
			arrowScrollOnHover: true,
			verticalGutter: 16
		};
		var pane = $('#main div.announcements');
		if(pane.length != 0){
  		pane.jScrollPane(settings);
  		var api = pane.data('jsp');
		
  		$('#scroll-up').click(function(e)
  			{
  				// Note, there is also scrollByX and scrollByY methods if you only
  				// want to scroll in one dimension
  				api.scrollByY(-30);
  				e.preventDefault();
  			}
  		);
  		$('#scroll-down').click(function(e)
  			{
  				// Note, there is also scrollByX and scrollByY methods if you only
  				// want to scroll in one dimension
  				api.scrollByY(30);
  				e.preventDefault();
  			}
  		);
		}
	}
}
function homeRotationControls(){
	if($('#home').length && $('#slider ul').length){
		$('#slider ul').cycle({
			fx:			'fade',
			pause:	1,
			speed:	'slow',
			timeout: 5000,
			pager: 	'#slideshow-controls',
			before:  onBefore,
			pagerAnchorBuilder: function(idx, slide) { 
					// return selector string for existing anchor 
					return '#slideshow-controls li:eq(' + idx + ') a'; 
			},
			activePagerClass: 'active'
		});
		
		$('#slide-hitbox').mouseenter(function() {                  
			//pause anim  
			$('#slider ul').cycle('pause');
		});
		
		$('#slide-hitbox').mouseleave(function() {       
			//start anim  
			$('#slider ul').cycle('resume');
		});
	}
  function onBefore() {
    $('#slide-hitbox').attr('href',this.firstChild.href);
  }
}
function sportPageControls(){	
	$('#right ul.controls li a').click(function() {       
		$('#right ul.controls li a').removeClass('active');
		$(this).addClass('active');
		$selected = $(this).parent('li').attr('class');
		
		$('table').removeClass('active');
		$('table.' + $selected).addClass('active');
		
		return false;
	});
}
//**************************************************Toggle Question/Answer**********************************************************//
function toggle() {
  if (!$('ul.toggle,ol.toggle').length > 0) return false;
	$('ul.toggle,ol.toggle h5').addClass('inactive');
	$('ul.toggle div.toggle,ol.toggle div.toggle').hide();
  $('ul.toggle h5,ol.toggle h5').click(function () {
		$(this).toggleClass('active');
		$(this).toggleClass('inactive');
    $($(this).next('div.toggle')).slideToggle();
  });
}
function operaFix(){
	if (window.opera && $('#home #footerWrap #foot-right').length)     
	{
		 $('#foot-right').css('right','2px');
	}
}
function mediaGalleries(){
	if($('#media-galleries').length){
		
		$('#header #close-btn').click(function() {       
			window.close();
			return false;
		});
		
		// handle redirects from the dropdown
		$('select[name=VideoCategory]').change(function(){
		  var value = $(this).val();
		  // format the url so we have [host, "gallery", site ID, ...]
		  var url = window.location.href.replace('http://', '').split(/\//g);
		  window.location = "/gallery/" + url[2] + "/" + url[3] + "/" + value;
		})
		
		//Math to layout photo grids properly
		$('.photo-box').each(function(index) {
			var row_count = 3;
			if($(this).find('div').hasClass('meta-info')){
				row_count = 2;
			}
			var thumb_count = $(this).find('ul.thumbs li').length;
			var item_width = $(this).find('ul.thumbs li').outerWidth(true);
			var box_width = (thumb_count / row_count) * item_width;
			
			//adjust thumb sizes and re-center to fill the square area
			$('.photo-box').find('ul.thumbs li .centeredImage img').each(function(index) {
				if($(this).attr('width') < 128){
					$(this).attr('width', 128);
					$(this).removeAttr('height');
					var adjust_for_center = '-' + [(($(this).height() - 128) / 2)] + 'px';
					$(this).css('margin-top', adjust_for_center);
				}else if($(this).attr('height') < 128){
					$(this).attr('height', 128);
					$(this).removeAttr('width');
					var adjust_for_center = '-' + [(($(this).width() - 128) / 2)] + 'px';
					$(this).css('margin-left', adjust_for_center);
				}
			});
			
			if(row_count == 3 && thumb_count < 15){
				$(this).find('ul.thumbs').css('width','685px');
			}else{
				$(this).find('ul.thumbs').css('width',box_width);
				$('.scroll').jScrollPane();
			}
		});
		
		//Math to layout docs grids properly
		$('.docs-box').each(function(index) {
			var row_count = 3;
			if($(this).find('div').hasClass('meta-info')){
				row_count = 1;
			}
			var thumb_count = $(this).find('ul.thumbs li').length;
			var item_width = $(this).find('ul.thumbs li').outerWidth(true);
			var box_width = (thumb_count / row_count) * item_width;
			
			if(row_count == 3 && thumb_count < 15){
				$(this).find('ul.thumbs').css('width','690px');
			}else{
				$(this).find('ul.thumbs').css('width',box_width);
				$('.scroll').jScrollPane();
			}
		});
		
		//Math to layout video grids properly
		$('.video-box').each(function(index) {
			var row_count = 3;
			if($(this).find('div').hasClass('meta-info')){
				row_count = 1;
			}
			var thumb_count = $(this).find('ul.thumbs li').length;
			var item_width = $(this).find('ul.thumbs li').outerWidth(true);
			var box_width = (thumb_count / row_count) * item_width;
			
			//adjust thumb sizes and re-center to fill the square area
			$('.video-box').find('ul.thumbs li .centeredImage img').each(function(index) {
				if($(this).attr('width') < 221){
					$(this).attr('width', 221);
					$(this).removeAttr('height');
					var adjust_for_center = '-' + [(($(this).height() - 221) / 2)] + 'px';
					$(this).css('margin-top', adjust_for_center);
				}else if($(this).attr('height') < 124){
					$(this).attr('height', 124);
					$(this).removeAttr('width');
					var adjust_for_center = '-' + [(($(this).width() - 124) / 2)] + 'px';
					$(this).css('margin-left', adjust_for_center);
				}
			});
			
			if(row_count == 3 && thumb_count < 15){
				$(this).find('ul.thumbs').css('width','690px');
			}else{
				$(this).find('ul.thumbs').css('width',box_width);
				$('.scroll').jScrollPane();
			}
		});
		
	}
}
function toggleGoogleDirections(){
	$('#slick-slidetoggle').click(function(){
		$('#map_directions').toggle();
		return false;
	});
}
//*****Load all functions**************************************************//
$(document).ready(function(){
  replaceAlign();
  replaceTarget();
  clearDefaultValue();
	homeScroller();
	homeRotationControls();
	sportPageControls();
	toggle();
	operaFix();
	mediaGalleries();
	toggleGoogleDirections();
	
	if($('#directory-listing').length > 0){
  	$('#directory-listing').tablesorter();
  }
  
  // convert embedded mp3 to flowplayer
  $('embed[src$="mp3"]').each(function(){
    var me = $(this);
    var id = me.attr('src').split('/');
    id = "audio" + id[id.length - 1].replace('.mp3', '');
    me.wrap('<a id="' + id+ '"class="flowaudio" href="'+ me.attr('src') +'" style="display:block;width:350px;height:30px;"></a>');
    if(typeof($f) != 'undefined'){
      $('#'+ id).empty();
      $f(id, "http://releases.flowplayer.org/swf/flowplayer-3.2.5.swf", {
        plugins: { controls: { fullscreen: false, height: 30, autoHide: false}},
        clip: {autoPlay: false}
      });
    }
  });
});
/*
  jQuery External Links Tracker Plugin
  Copyright (C) 2010 Paradigm New Media Group
  http://pnmg.com | http://github.com/pnmg/jquery-external-links-tracker
  GPL v2 license. See source file for more info.
*/
(function(a){a(document).ready(function(){var b=window.location.hostname;b=b.split(".");if(b.length==1){b=b[0]}else{if(b.length==4&&window.location.hostname.match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)){b=window.location.hostname}else{b=b[b.length-2]+"."+b[b.length-1]}}a("a[href*='"+b+"'],a[href^='/'],a[href^='./'],a[href^='../']").live("click",function(c){if(a(this).hasClass("newwindow")){c.preventDefault();if(window.console){window.console.log("Internal link not tracked as outging: "+a(this).attr("href"))}window.open(a(this).attr("href"))}});a("a[href^='http']:not([href*='"+b+"'])").live("click",function(f){f.preventDefault();var c=this.href.replace(/^(http|https):\/\//,"").replace(/www\./i,"").replace(/\./gi,"_");var d="/outgoing/"+c;if(typeof(pageTracker)!="undefined"){pageTracker._trackPageview(d);if(window.console){window.console.log("Tracked external link: "+d)}}else{if(typeof(_gat)=="object"){_gaq.push(["_trackPageview",d]);if(window.console){window.console.log("Tracked external link: "+d)}}else{if(window.console){window.console.log("Could not track external link: "+d)}}}window.open(a(this).attr("href"))})})})(jQuery);
/*
  This plugin will work for the "thumbnail panel" on the side of gallery pages
*/
(function($){
  var thumbnailPanel = {
    /*
      Debug messages
    */
    debug: function(message){
      if(window.console){ window.console.log(message) }
    },
    
    /*
      Get the thumbnails and display them on the page
      
      This method will be called, but not get thumbnails if:
        - There are not already 30 thumbnails on the screen
      
      Params:
        - $this: the panel list
        - data: the panel list data (using jQuery's data functionality)
    */
    getThumbs: function($this, data){
      if(data['debug']){ thumbnailPanel.debug('thumbnailPanel.getThumbs'); }
      
      var images = $this.find('li').length;
      if(images != 30 && images != 0){ return; }
      
      $.getJSON(data['source'], {page: data['page']}, function(data){
        panelData = $this.data('thumbnailPanel');
        if(data.length == 0){
          panelData['page']--;
          $this.data('thumbnailPanel', panelData);
          if(panelData['debug']){ thumbnailPanel.debug('No images. Page: '+ panelData['page']); }
          return;
        }
        $this.empty();
        if(panelData['debug']){ thumbnailPanel.debug('Images: '+ data.length); }
        for(i=0; i<data.length; i++){
          $this.append('<li><a href="../'+ data[i]['id'] +'/"></a>'+ data[i]['html'] +'</li>');
        }
				//adjust thumb-nav sizes and re-center to fill the tiny square area, different logic for rectangle thumb-nav
				if($('body').hasClass('photos') && $('body').hasClass('single')){
					window.console.log('started');
					$('#sidebar #thumb-nav li img').each(function(index) {
						window.console.log('running');
						if($(this).attr('width') < 41){
							$(this).attr('width', 41);
							$(this).removeAttr('height');
							var adjust_for_center = '-' + [(($(this).height() - 41) / 2)] + 'px';
							$(this).css('margin-top', adjust_for_center);
						}else if($(this).attr('height') < 41){
							$(this).attr('height', 41);
							$(this).removeAttr('width');
							var adjust_for_center = '-' + [(($(this).width() - 41) / 2)] + 'px';
							$(this).css('margin-left', adjust_for_center);
						}
					});
				}
      });
    },
    
    /*
      Navigate to the next page
    */
    next: function(e){
      e.preventDefault();
      var data = $(this).data('thumbnailPanel');
      var panelData = data['panel'].data('thumbnailPanel');
      if(panelData['debug']){ thumbnailPanel.debug('thumbnailPanel.next: '+ data['panel']) }
      panelData['page']++;
      thumbnailPanel.getThumbs(data['panel'], panelData);
    },
    
    /*
      Navigate to the previous page of thumbnails
    */
    previous: function(e){
      e.preventDefault();
      var data = $(this).data('thumbnailPanel');
      var panelData = data['panel'].data('thumbnailPanel');
      if(panelData['debug']){ thumbnailPanel.debug('thumbnailPanel.previous: '+ data['panel']) }
      if(panelData['page'] != 1){
        panelData['page']--;
        thumbnailPanel.getThumbs(data['panel'], data);
        return;
      }
      if(panelData['debug']){ thumbnailPanel.debug('On first page'); }
    }
  }
  
  /*
    Initalize the thumbnail panel
  */
  $.fn.thumbnailPanel = function(options){
    // default values
    var settings = {
      'thumbnailList': $(this),
      'nextLink': '#next',
      'previousLink': '#previous',
      'source': 'images/',
      'debug': false
    }
    
    return this.each(function(){
      if(options){ $.extend(settings, options); }
      
      var $this = $(this),
        data = $this.data('thumbnailPanel');
      
      if(!data){
        $this.data('thumbnailPanel', {page: 1, source: settings['source'], debug: settings['debug']});
        data = $this.data('thumbnailPanel');
      }
      
      thumbnailPanel.getThumbs($this, settings, data);
      
      $(settings['nextLink']).data('thumbnailPanel', {panel: $this});
      $(settings['nextLink']).click(thumbnailPanel.next);
      
      $(settings['previousLink']).data('thumbnailPanel', {panel: $this});
      $(settings['previousLink']).click(thumbnailPanel.previous);
    });
    
  }
})(jQuery);
