﻿Core.settings({site:'hbshome',
plugins:'../js/plugins'
              });

(function($){

//test comment 2/3/2011
var Hbshome = {
     ondomready:function() {
         try {
             $("#mba-panel").myCoreRotator();
             $("#video-panel").myCoreRotator();
             //$("#content a").coreLinks({icons:"http://www.hbs.edu/shared/images/framework/1.0/"});   
             
			 Hbshome.fixLinks();
             Hbshome.cutomizeShareThis();
             $(".ellipsis").ellipsis();
             Core.email_obfuscation();
             Hbshome.slider();
             Hbshome.ipadSwipe();
             Hbshome.toolTip();
			 Hbshome.smallChanges();
			 Hbshome.submitSearch();
			 Hbshome.convertTwitterDttm();
             Hbshome.analytics();
             
         } finally {
             $("#javascript").removeClass('rendering').addClass('domready');
         }
    },
    
    //SharePoint replaces certain www.hbs.edu links to prod.hbs.edu, this script reverses it back.
    fixLinks: function(){
		    var alllinks = document.getElementsByTagName("a");
			for (var i=0,il=alllinks.length;i<il;i++) {
		    var loc = $(alllinks[i]).attr("href");
		    if (/prod.hbs.edu/.test(loc)){
		        var newLoc = loc.replace("prod.hbs.edu","www.hbs.edu");
		        $(alllinks[i]).attr("href",newLoc);
		 }
		} 
    },
    
    //Converts the rendered twitter time to local time
    convertTwitterDttm: function(){

		//figure out the offset number for current browser's time zone
		var offsetNum = GrabTimeZoneOffSet();

    	$("span.twtr-timeago").each(
			function(){
				//parse the utc datetime
				var theTimeago = $(this).attr("title");
				var theTimeagoParsed = Date.parse(theTimeago);
	
				//actual time in user's browser's time zone settings
				var theTimeagoFinal = theTimeagoParsed.add(offsetNum).hours();
				
				$(this).attr("title",theTimeagoFinal.toString('yyyy-MM-ddTHH:mm:ss'));	//timeago.js relies on this to do its magic
				$(this).html(theTimeagoFinal.toString('dddd, MMMM dd, yyyy h:mm:ss tt'));  //display full date time format
				$(this).timeago();
			}
		);
    },
    
    cutomizeShareThis: function(){
    		var videoUrl = $("#hbs-video1-url").val();
            $(".sharethis").each(function(){  Core.sharethis(this, {url:videoUrl });}  );
    },
    
    submitSearch: function(){
    	$('#search_submit').click(function() {
		var searchVal = $('#search_text').val();
        document.location.href="http://search.hbs.edu:8765/hbs/?qt="+$('#search_text').val();
      });

      $('#search_text').keypress(function(e) {
		  if(e.which == 13) {
			  jQuery(this).blur();
			  $('#search_submit').click();
			  return false;
		  }
		  else{
		  	return true;
		  }
	  });

    
    },
    
    
     smallChanges: function() {
     
		$('.secondary-stories ul li:last-child').addClass("last-child");
		

		 $(".move-prev").hover(
				 	function(){$('.inside-prev').not(".inactive").addClass("prevHover")},
		         	function(){$('.inside-prev').removeClass("prevHover")}
         	
         );


	    $(".move-next").hover(
			    		function(){$('.inside-next').not(".inactive").addClass("nextHover")},
			  			function(){$('.inside-next').removeClass("nextHover")}
	  	);
	  		
	  
				
	},


    slideTo: function(panel) {
   
        Hbshome.currentPanel = panel;
        
       
        $('.inside-next, .move-next, .inside-prev, .move-prev').removeClass('inactive');

        // toggle navigation
        $(".rotate-nav .on").removeClass("on");
        var num = $(".rotate > li").not(".empty").index(panel);
        $(".rotate-nav > li").eq(num).addClass("on");

        //window.location.hash = '#'+(num+1);

        // slide to he new position
        var width = panel.width();
        var pos = $(".rotate > li").index(panel);
        var left_indent = width * pos;
        left_indent -= 35; // small indent
        $('.rotate').stop().animate({'left' : -left_indent},1000);
        
        if (Hbshome.currentPanel.next().hasClass("empty")){
            $('.inside-next, .move-next').addClass('inactive');
        }
            
        if (Hbshome.currentPanel.prev().hasClass("empty")){
            $('.inside-prev, .move-prev').addClass('inactive');
        }    
    },
    
    slider: function(){

         Hbshome.currentPanel = $('.rotate > li').not(".empty").eq(0);
         $('.rotate > li').eq(1).addClass("firstslide");
         $('.rotate > li').eq(12).addClass("lastslide");
         checkForLastAndFirst();
        
         // setup auto advance
         var slideshowSpeed = 10000;

         // allow deep linking into panels
         var startPanel = $("#panel-"+document.location.hash.replace("#",''));
         if (startPanel.size() > 0) {Hbshome.slideTo(startPanel);}

         function activateSlideshow() {
            Hbshome.slideshowRun = setInterval(function(){
                if ($(".panels.over").size() == 0) {
                  var next = Hbshome.currentPanel.next().not(".empty");
                   if (Hbshome.currentPanel.next().hasClass("empty")) {
                   clearInterval(Hbshome.slideshowRun);                
                   }
                    else {
                    Hbshome.slideTo(next);
                    }
                }
             }, slideshowSpeed);  
         }

         activateSlideshow();
        
         $(".panels, .rotate-nav, .panels a").click(function(){
            clearInterval(Hbshome.slideshowRun);
            Hbshome.slideshowRun = false
         })
         
         $(".panels").hover(function(){$(this).addClass("over")},
                            function(){$(this).removeClass("over")})
         
         function checkForLastAndFirst() {
            $('.inside-next, .move-next, .inside-prev, .move-prev').removeClass('inactive');
            
            if (Hbshome.currentPanel.next().hasClass("empty")){
                $('.inside-next, .move-next').addClass('inactive');
            }
            
            if (Hbshome.currentPanel.prev().hasClass("empty")){
                $('.inside-prev, .move-prev').addClass('inactive');
            }    
         }

         // setup click events
         $('.move-next a, .inside-next').click(function(event){
             event.preventDefault();
             event.stopPropagation();
             checkForLastAndFirst(); 
             if (!$('.move-next').hasClass("inactive")) {
                    var next = Hbshome.currentPanel.next();
                 Hbshome.slideTo(next);
             }
         });

         $('.move-prev a, .inside-prev').click(function(event){
             event.preventDefault();
               event.stopPropagation();

             var next = Hbshome.currentPanel.prev().not(".empty");
             checkForLastAndFirst(); 
             if (!$('.move-prev').hasClass("inactive")) {
                 var next = Hbshome.currentPanel.prev().not(".empty");
                 Hbshome.slideTo(next);
             }
         });

         $(".rotate-nav a").click(function(event){ 
             event.preventDefault();
               event.stopPropagation();

             pos = $(".rotate-nav a").index(this);
             var next = $(".rotate > li").not(".empty").eq(pos);
             Hbshome.slideTo(next);
             
             clearInterval(Hbshome.slideshowRun);
            Hbshome.slideshowRun = false;

         });
    },

    ipadSwipe: function() {
        
            var swipeOptions=
            {
                swipeLeft:swipeLeft,
                swipeRight:swipeRight,
                allowPageScroll:"vertical", // allow vertical page scroll so only right and left swipes actually take the action
                threshold:20, //how far the user must swipe to get the action to work (in pixels). 0 will recognize any swipe
                triggerOnTouchEnd: true
            }
            
                $(function()
                {            
                    $(".view-port").swipe( swipeOptions );
                });
            
            
            function swipeLeft(event) {
             clearInterval(Hbshome.slideshowRun);

                      event.preventDefault();
                     if (!$('.move-next').hasClass("inactive")) {
                        var next = Hbshome.currentPanel.next().not(".empty");
                         Hbshome.slideTo(next);
                     }
            }
            
            function swipeRight(event) {
             clearInterval(Hbshome.slideshowRun);

               event.preventDefault();
                 if (!$('.move-prev').hasClass("inactive")) {
                      var next = Hbshome.currentPanel.prev().not(".empty");
                      Hbshome.slideTo(next);    
                      }    
            }

    },
    
    toolTip: function() {
		
		$("ul.rotate-nav li a").hover(function(){
	
	
	
	
/* The issue is you get diferent values for width from IE and Firefox. 
Can't use width() to make this adjustment. 

			// find the width of the hover element
			var width = $(this).find('span').width();
			console.info("width = " + width);
			
			// Find the offset by taking half of the additional width - half because we are trying to center
			var parentwidth = $("ul.rotate-nav li a").outerWidth();
			var offset = (width - parentwidth )/2;			
		    console.info("offset = " + offset);

		    // offset the left 			    
			$('ul.rotate-nav li .hovertext').css('left', "-" + offset + "px");
			var currentleft = $('ul.rotate-nav li .hovertext').css('left');
			console.info(currentleft);

			*/
		},function() {
			/* do something after this happens */
		});
		
		
		
	},
    
    
        
    analytics: function(){
       if (!window.analytics) return;
      
       $(".sitemap a, .header a, .panel-item a, #superfooter a").addClass("offsite");
       
       $('.move-next a, .inside-next').click(function(event){
          analytics.event("panel-next");
       })
       
       $('.move-prev a, .inside-prev').click(function(event){
          analytics.event("panel-prev");
       })
       
       $("#box-preview .rotate-nav > li > a").click(function(){
          analytics.event($(this).parent().attr('id'));
       });
       
       $("#supernav-sitemap").click(function(){
          analytics.event("sitemap-open");
       })
       
       $("#superfooter .selector").click(function(){
          analytics.event("footer-open");
       });
       
    },
   
    last:""
     
}

//This function returns the timezone off set 
//using javascript's .getTimezoneOffset() is unreliable b/c it doesn't account for daylight savings time
//notes on: http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/
 function GrabTimeZoneOffSet() {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst;
		
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
	return std_time_offset;
}


jQuery.fn.ellipsis = function() {
    return this.each(function() {
        var el = $(this);
        var text = el.html();
        var multiline = true;

        var t = $(this.cloneNode(true)).css('overflow', 'visible').height('auto').css('max-height','none');

        el.after(t);
        
        function height() { return t.height() > el.height(); };

        while (text.length > 0 && height()) {
                text = text.substr(0, text.length - 1);
                t.html($.trim(text) + "&hellip;");
        }

        el.html(t.html());
        t.remove();
    });
}



//plugin
jQuery.fn.myCoreRotator = function(options) {

    if (!options) {options = {}};
    if (!options.style) {options.style = "standard"};
    
    return this.each(function(){
       $this = $(this);
       $(".rotate-select a",this).each(function(i){
          $(this).data('container',$this);
          $(this).click(function(){
            $this = $(this).data('container');
            $(".rotate-text li.selected",$this).removeClass('selected');
            $(".rotate-select li.selected",$this).removeClass('selected');
            $(".rotate-text > li",$this).eq(i).addClass('selected');           
            $(".rotate-pics li.selected",$this).removeClass('selected');
            $(".rotate-pics li",$this).eq(i).addClass('selected');           
            $(this).parent().addClass('selected');
            
            
            $(this).parent().parent().addClass('selected'); // for video rotator
            
            $this.corePauseMovies();
            return false;
          });
       });
       
       if (options.random) {
          var num=Math.floor(Math.random() * $(".rotate-select a",$this).size());
          $(".rotate-select a",$this).eq(num).trigger("click");
       } else {
          $(".rotate-select a",$this).eq(0).trigger("click");
       }
       
    });
    
}

window.Hbshome = Hbshome;

$(document).ready(Hbshome.ondomready);

})(jQuery)







