$(document).ready(function() {
   
   // register the information library pop menu
   registerILMenu();

   // clab accordion
   registerClab();

   // make external links open in a new window
   registerExternalLinks();

   // track file downloads with GA
   registerGAHandlers();

   // register videos
   registerVideos();
   
   // register suggested reading
   registerSuggestedReading();
   
   // set up ticker lists
   registerTickerLists();
});

function toggleILMenu() {

   var arrow = $('#top_nav a.il_toggle span.arrow');
   arrow.toggleClass('down');
   if (arrow.hasClass('down')) {
      
      // register the body handler
      $(document.body).bind('click', toggleILMenu);
      
      // show the menu
      $('#il_popup').fadeIn();
      
   } else {

      // unregister the body handler
      $(document.body).unbind('click', toggleILMenu);
      
      // hide the menu
      $('#il_popup').fadeOut();
   }
}

function registerILMenu() {
   
   $('#top_nav a.il_toggle').click(function() {
      
      toggleILMenu();
      return false;
   });
}


function registerExternalLinks() {
   
   $('a.external_link').attr('target', '_blank');
}

function registerTickerLists() {
   
   $('ul.ticker').each(function() {
   
      // add a back and forward link
      $(this).before('<a href="#" class="ticker_previous">&lt;</a>');
      $(this).after('<div class="clearfix">&nbsp;</div>');
      $(this).after('<a href="#" class="ticker_next">&gt;</a>');

      
      // add a class marking this ticker as active
      $(this).addClass('active');
      
      // hide all but the first li
      $(this).children('li').each(function(i) {
         if (i != 0)
            $(this).hide();
      });
   });
   
   // register handlers for previous and next buttons
   $('a.ticker_next').click(function() {

      var list = $(this).prev();
      var activated = 0;
      
      // find the currently displayed li
      list.children('li').each(function(i) {
         
         if ($(this).css('display') != 'none')
            activated = i;
      });
      
      // what will the next item be?
      var next = (activated + 1) % list.children('li').length;
      
      // hide and show
      $(list.children('li')[activated]).fadeOut('fast', function() {
         $(list.children('li')[next]).fadeIn('fast');
      });
      
      return false;
   });
   
   $('a.ticker_previous').click(function() {
      
      var list = $(this).next();
      var activated = 0;
      
      // find the currently displayed li
      list.children('li').each(function(i) {
         
         if ($(this).css('display') != 'none')
            activated = i;
      });
      
      // what will the previous item be?
      var previous = activated == 0 ? (list.children('li').length - 1) : activated - 1;
      
      // hide and show
      $(list.children('li')[activated]).fadeOut('fast', function() {
         $(list.children('li')[previous]).fadeIn('fast');
      });
      
      return false;
   });
}

function registerGAHandlers() {
   
   // we may need the domain name
   var domain = window.location.toString();
   domain = domain.match(/^http(s)?:\/\/[^\/]+/i);
   if (domain)
      domain = domain[0];
   
   $('a').each(function() {
      
      var a = $(this);
      var href = a.attr('href');
      
      // is this a file on this site that needs GA tracking?
      if (href.match(/.+\.(pdf|doc|docx|ppt|pptx|xls|xlsx)$/i)) {

         var href_domain = href.match(/^http(s)?:\/\/[^\/]+/i);
         try {
            
            if (pageTracker && (href_domain == null || (href_domain && href_domain.toLowerCase() == domain.toLowerCase()))) {
            
               a.click(function() {
                  // call GA
                  pageTracker._trackPageview($(this).attr('href'));
                  return true;
               });
            }
            
         } catch (err) {
            
            // GA not available - just ignore
         }
      }
   });
}

function registerClab() {
   
   if ($('#accordion_list').length) {
   
      // decide which panels to hide and which to mark as selected
      var sel = null;
      var url = window.location.toString();
      var urlparts = url.split('#');
      if (urlparts.length == 2) {
         sel = $('#accordion_list li h3.accordion_head a[name=' + urlparts[1] + ']');
      }
      if (!sel || !sel.length) {
         sel = $('#accordion_list li h3.accordion_head a[name=welcome]');
      }
      
      // now, sel contains the a tag in the header for a section
      if (sel.length) {
      
         // hide all but the selected panel
         $('#accordion_list li div.panel_main').each(function() {
            if ($(this).parent().find('h3.accordion_head a').attr('name') != sel.attr('name')) {
               $(this).hide();
            }
         });
         
         // mark the selected panel
         sel.parent().addClass('selected');
   
         // button handler
         $('#accordion_list li h3.accordion_head a').click(function() {
   	
         	// switch to this panel
      	   switchCLabPanel($(this).attr('name'));
	   
      	   // no default click action
            return false;
         });
      }
   }
}

function switchCLabPanel(name) {
   
   var btn = $('#accordion_list li h3.accordion_head a[name=' + name + ']');
   
   // ignore if the name is invalid
   if (!btn.length)
      return;
      
   // if we're selected, duck out
   if (btn.parent().hasClass('selected'))
      return false;

   // what is the next div we're going to show?
   var nextDiv = btn.parent().siblings('div.panel_main');
   
   // initial state - select this item if nothing is selected
   if (!$('#accordion_list li h3.selected').length)	  
      nextDiv.slideDown('slow');

   // hide all of the selected h3
   $('#accordion_list li h3.selected').each(function() {

      // always remove the selected state from the h3
      $(this).removeClass('selected');

      // if we have a div to hide, hide it and chain the slide down
      if ($(this).siblings('div.panel_main').length) {

         // hide and show
         $(this).siblings('div.panel_main').slideUp('slow');
         nextDiv.slideDown('slow');

      } else {

         // no divs to hide, so just unhide the next div
         nextDiv.slideDown('slow');
      }
   });
  
   // set this h3 to selected
   btn.parent().addClass('selected');
   
   // track the pageview
   try {
      pageTracker._trackPageview(window.location.toString() + '#' + name);
   } catch (err) {
      // don't care
   }
   
}

function registerVideos() {
         
   // keep track of the shadowbox flv and dimensions as local vars
   var shadowbox_flv = "";
   var shadowbox_flv_width = 640;
   var shadowbox_flv_height = 360;

   // need a hack to keep track of the Information Library button z-index
   var il_zindex = "";   

   // register the handler
   $('a.videogeneric').click(function() {
   
      // set the flv value so shadowbox will show the correct value onFinish
      shadowbox_flv = $(this).attr('href');
      
      // default width and height
      shadowbox_flv_width = 640;
      shadowbox_flv_height = 360;
      
      // try to parse width and height from the URL
      var url_parts = shadowbox_flv.split('?');
      if (url_parts.length == 2) {
         
         // we need to strip the query string off the URL
         shadowbox_flv = url_parts[0];
         
         // have we found width and height?
         var found_width = false;
         var found_height = false;
         
         // parse out the parameters
         var params = url_parts[1].split('&');
         var w = NaN;
         var h = NaN;
         for (var i = 0; i < params.length; i++) {
            
            // parse the parameter
            var param = params[i].split('=');
            if (param.length == 2) {
               
               switch(param[0]) {
                  
                  case 'width':
                     w = parseInt(param[1]);
                     if (w)
                        found_width = true;
                     break;
                  
                  case 'height':
                     h = parseInt(param[1]);
                     if (h)
                        found_width = true;
                     found_height = true;
                     break;
                  
                  default:
                     break;
               }
            }
            
            if (found_width && found_height) {
               
               shadowbox_flv_width = w;
               shadowbox_flv_height = h;
            }
         }
      }
      
      // fix the width and height to fit the shadowbox and flv player
      var embed_width = shadowbox_flv_width + 20;
      var embed_height = shadowbox_flv_height + 48;
      
      // store the il z-index and set it to none
      il_zindex = ($('.pop').css('z-index'));
      if (!$.browser.msie)
         $('.pop').css('z-index', 'auto');
      
      // initialize shadowbox
      Shadowbox.init({
         onFinish: function() {
            
            // new player code 
            var so = new SWFObject("/elements/swf/quintiles-ovp.swf", "", embed_width, embed_height, "10.0.0", "#ffffff");
            so.useExpressInstall("/elements/swf/expressInstall.swf");
            
            so.addVariable("src", shadowbox_flv);
            so.addVariable("autostart", true);
            so.addVariable("enableFullscreen", false);
            
            so.addParam("wmode", "transparent");
            so.addParam("allowFullScreen", "true");
            so.write("flv_player");
         },
         onClose: function() {

            // restore the il z-index
            if (!$.browser.msie)
               $('.pop').css('z-index', il_zindex);
         }
      });
      
      // open a welcome message
      Shadowbox.open({
         player:     'html',
         title:      '',
         content:    '<div id="flv_player"></div>',
         width:      embed_width,
         height:     embed_height
      });
   
      return false;
   });
}

function registerSuggestedReading() {
   
   if ($('#suggested_reading').length) {
      
      // hide the reading box?
      var inactive = $.cookie('suggested_reading_active') || false;
      
      if (inactive) {
         $('#suggested_reading').removeClass('active');
         $('#suggested_reading .reading_body').hide();
      }
         
      // register the show / hide toggle
      $('#suggested_reading .header a').click(function() {
         
         $('#suggested_reading').toggleClass('active');
         if ($('#suggested_reading').hasClass('active')) {
            
            $('#suggested_reading .reading_body').slideDown();
            $.cookie('suggested_reading_active', null, { path: '/' });
            
         } else {
            
            $('#suggested_reading .reading_body').slideUp();            
            $.cookie('suggested_reading_active', true, { path: '/' });
         }
         
         return false;
      });
      
      // register the 'x' buttons to run with AJAX
      $('#suggested_reading .reading_body ul li a.remove').click(function() {
         
         // get the AJAX path to use
         var pathParts = $(this).attr('href').split('/');
         if (pathParts.length == 4)
            $.get('/tracking/ajax/' + pathParts[2] + '/');
         
         $(this).parent().fadeOut(function() {
            $(this).remove();
            $('#suggested_reading .reading_body ul li:last').addClass('last');
         });
         
         return false;
      });
   }
}
