$(document).ready(function() {
   
   // 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 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() {
   
   // NOTE: If you don't want to track events, but only preserve the
   // enterprise/rollup cookie, change this to 0. Its default is/was 1.
   var extras = 1;
   
   // local URLs are blank or begin with a '/' or '#'
   var rxLocalURL = /(^$)|(^#.*$)|(^\/.*$)/;
   var rxMailtoURL = /^mailto:(.*)$/;
   var rxDocURL = /^.+\.(pdf|doc|docx|xls|xlsx|ppt|pptx|txt)$/i;
   var loc_hostname = window.location.hostname;
   
   // Track outbound links automatically.
   $('a').each(function() {
      var href = $(this).attr('href');
      if (href) {
         
         // Does this link stay on the same [sub]domain?
         var isLocal = href.search(loc_hostname) > -1;
         isLocal = isLocal || rxLocalURL.test(href);
         
         // If not, does it at least stay within Quintiles sites?
         // If it links to quintiles.com, it musn't already be on one of its
         // subdomains...
         var href_index = href.search('.quintiles.com');
         var lochost_index = loc_hostname.search('.quintiles.com');
         // This allows us to give the link a class that will leave it out of
         // having the cross-domain tracking. This is useful when the query
         // params contain quintiles.com or some other domain.
         var doNotPass = $(this).hasClass('doNotPass');
         var switchingDomains = !isLocal && !doNotPass &&
            (
               href.search('.clinicalresearch.com') > -1 ||
               href.search('quintiles.taleo.net') > -1 ||
               (
                  href_index > -1 &&
                  (
                     href_index <= lochost_index ||
                     href.substring(href_index-lochost_index, href_index) != loc_hostname.substring(0, lochost_index)
                  )
               )
            );

         /*
         alert("local? "+isLocal+'\n'+
            "switching domains? "+switchingDomains+'\n'+
            '   clinical research? '+href.search('.clinicalresearch.com')+'\n'+
            '   taleo? '+href.search('quintiles.taleo.net')+'\n'+
            '   href index: '+href_index+'\n'+
            '   loc index: '+lochost_index+'\n'+
            '   href match: '+href.substring(href_index-lochost_index,href_index)+'\n'+
            '   loc match: '+loc_hostname.substring(0,lochost_index)
            );
         */
         
         // Is it a mailto link?
         var isMailto = rxMailtoURL.test(href);
         
         // Is it a link to a typical type of document?
         var isDoc = rxDocURL.test(href);
         
         // If it's a email link, track that.
         if (isMailto) {
            if (extras) {
               $(this).click(function() {
                  // track a mailto event
                  _gaq.push(["pageTracker._trackEvent", "mailto", "Click", $(this).attr('href').replace(/mailto:/, "")]);
                  _gaq.push(["rollupTracker._trackEvent", "mailto", "Click", $(this).attr('href').replace(/mailto:/, "")]);
                  return true;
               });
            }
         }
         // If it's a locally hosted document, track that.
         else if (isDoc && isLocal) {
            if (extras) {
               $(this).click(function() {
                  // track an event and a pageview for local downloads
                  _gaq.push(["pageTracker._trackEvent", "Downloads", "Click", $(this).attr('href')]);
                  _gaq.push(["rollupTracker._trackEvent", "Downloads", "Click", $(this).attr('href')]);
                  _gaq.push(["pageTracker._trackPageview", "/downloads" + $(this).attr('href')]);
                  _gaq.push(["rollupTracker._trackPageview", "/downloads" + $(this).attr('href')]);
                  return true;
               });
            }
         }
         // If it's not a Quintiles.com link, track that.
         else if (!isLocal) {
            // If it's a Quintiles-related site.
            if (switchingDomains) {
               $(this).click(function() {
                  // Only fire the outbound link event for the old-fashioned
                  // account.
                  _gaq.push(["pageTracker._trackEvent", "Outbound", "Click", $(this).attr('href')]);
                  // Manually pass the cookie and let GA redirect us to the
                  // new page.
                  _gaq.push(['rollupTracker._link', $(this).attr('href')]);
                  return false;
               });
            }
            // If it's a truly external site.
            else {
               if (extras) {
                  $(this).click(function() {
                     // Fire an outbound link event for both trackers.
                     _gaq.push(["pageTracker._trackEvent", "Outbound", "Click", $(this).attr('href')]);
                     _gaq.push(["rollupTracker._trackEvent", "Outbound", "Click", $(this).attr('href')]);
                     return true;
                  });
               }
            }
         }
         else {
            // don't need to do anything else to track local links
         }
      }
   });
}

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 {
      _gaq.push(["pageTracker._trackPageview", window.location.toString() + '#' + name]);
      _gaq.push(["rollupTracker._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').length) {
      
      // register the 'x' buttons to run with AJAX
      $('.suggested ul li a.hide').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();
         });
       
         return false;
      });
      
      // track impressions for suggested reading
      /*
      $('.suggested ul li a[class!="hide"]').each(function() {
         
         try {
            _gaq.push(['pageTracker._trackEvent', "Suggested Reading", "Impression", $(this).attr('href')]);
         } catch (e) {
            // ignore
         }
      });
      */
      
      // register GA tracking for clicks on suggested reading
      $('.suggested ul li a[class!="hide"]').click(function() {
         
         try {
            _gaq.push(['pageTracker._trackEvent', "Suggested Reading", "Click", $(this).attr('href')]);
         } catch (e) {
            // ignore
         }
         
         // allow the click to work
         return true;
      });
   }
}

