/*
** alumni.js - Alumni Javascript Library
** jgriffith
**
*/

Core.settings({site:'alumni',
               plugins:'/js/plugins'
               });



(function($){

if (window.Alumni) return;

var Alumni = {
  
   ondomready: function() {
      try {
         Alumni.ifloggedin();
         Alumni.topnav();
         Alumni.leftnav();
         Alumni.lightbox();
         Alumni.renderVideos();
         Alumni.render480Videos();
         Alumni.renderGivingVideos();
         Alumni.expandable_uls();
         Alumni.expandable_tables();
         Alumni.csstweak();
         Alumni.ifs();
         Alumni.outage();
         Alumni.autofill_forms();
         Alumni.set_input("jsmith@mba1967.hbs.edu","login-username");
         Alumni.set_input("Name","directory-lastname");
         Alumni.carousel(); 
         Alumni.giveHereImgRotator();
         $(".sharethis").each(function(){  Core.sharethis(this);}  );        
         $("#rotator1").coreRotator({random:1});
         $("#rotator2").coreRotator({random:1});
         $("a[href$='.jpg'],a[href$='.png']").fancybox();
         Alumni.fancyvideo();
         // temp fix until the app is patched
         // if (!Alumni.year) {
         //   $("#directory p a").css({color:"black",cursor:"default"}).click(function(){return false;});
         //}
      } catch (e) {
         Core.log.error(e);
         throw(e);
      } finally {
         Alumni.showbody();
      }
   },
   
   onload: function() {
      try {
         Alumni.gallery();
         //Alumni.homepage();
         Alumni.facultysearch();
         Alumni.clubsearch();
         Alumni.reunionsearch();
         Alumni.bulletin();
         Alumni.ebaker();
         Alumni.printthispage();
         Alumni.sendtofriend();
         Alumni.loginform();
         Alumni.tooltips();
         Alumni.links();
         Alumni.tabs();
         Alumni.rendervideos();
         Alumni.home_resources_hover();
         Alumni.home_tabs();
         Alumni.setscroll();
         Alumni.ifloggedin();

       } catch (e) {
         Core.log.error(e);
         throw(e);
       }
   },
   
   
   loggedin: false,

   // hide the body until the DOM is finished being altered
   hidebody: function() {
      document.write('<style type="text/css">.expandable {visibility:hidden;}</style>')
   },
   
   showbody: function() {
      $(".expandable").css('visibility','visible');
   },
   
   fancyvideo: function() {  	
     	$(".video").click(function() {
		$.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'			: 640,
			'height'		: 330,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
			'wmode'				: 'transparent',
			'allowfullscreen'	: 'true'
			}
		});

		return false;
		});
   },

   
   topnav: function() {
        function sethere(id) {
            var a = document.getElementById(id+'-nav');
            if (!a){return};
            a.parentNode.className += ' on';
            a.className += ' on';
        }
        var loc = document.location.href;
        if (loc.indexOf('hbs.edu/careers/') > -1) {
            sethere('career');
        } else if (loc.indexOf('hbs.edu/events/') > -1) {
            sethere('events');
        } else if (loc.indexOf('hbs.edu/travel/') > -1) {
            sethere('travel');
        } else if (loc.indexOf('hbs.edu/reunions/') > -1) {
            sethere('reunions');
        } else if (loc.indexOf('hbs.edu/giving/') > -1) {
            sethere('giving');
        } else if (loc.indexOf('hbs.edu/faq/') > -1) {
            sethere('faqs');
        } else if (loc.indexOf('hbs.edu/volunteers/') > -1) {
            sethere('volunteers');
        } else if (loc.indexOf('hbs.edu/bulletin/') > -1 && $("body").hasClass('bulletin-home')) {
            sethere('bulletinhome');                     
        } else if (loc.indexOf('hbs.edu/bulletin/pastissues.html') > -1) {
            sethere('past');                     
        } else if (loc.indexOf('hbs.edu/bulletin/aboutus.html') > -1) {
            sethere('about');                     
        } else if (loc.indexOf('hbs.edu/bulletin/blog/') > -1 && document.title.indexOf("Last Look") == -1) {
            sethere('blog');               
        } else if (loc.indexOf('hbs.edu/bulletin/') > -1 && $("img[src~='currentissue.gif']").size() > 0) {
            sethere('current');                     
        } else if (loc.indexOf('hbs.edu/bulletin/') > -1 && $("img[src~='pastissue.gif']").size() > 0) {
            sethere('past');                     
        }            
   },
   
   clean_comments: function(form) {
       $("#commentform form").submit(function() {
          $(this.C).val(Alumni.clean_chars($(this.C).val()));
          return true;
       });
   },
   
   clean_chars: function(text) {
       var replacements = {
           "\xa0": " ",
           "\xa9": "(c)",
           "\xae": "(r)",
           "\xb7": "*",
           "\u2018": "'",
           "\u2019": "'",
           "\u201c": '"',
           "\u201d": '"',
           "\u2026": "...",
           "\u2002": " ",
           "\u2003": " ",
           "\u2009": " ",
           "\u2013": "-",
           "\u2014": "--",
           "\u2122": "(tm)"};
           for (key in replacements) {
             var rx = new RegExp(key, 'g');
             text = text.replace(rx,replacements[key])
           }
       return text
   },
   
   leftnav: function() {
         var nav = document.getElementById('subnav');
         if (!nav) return;
         var links = nav.getElementsByTagName('a');
         var thisurl = Alumni.thisurl();
         for (x=0,total=links.length;x<total;x++) {
             if (Alumni.sameurl(thisurl,links[x])) {
                  links[x].className = 'on current';
                  var li = links[x].parentNode;
                  li.className = 'open';
                  
                  node = li
                  var at_top = false;
                  while (!at_top) {
                    node = node.parentNode;
                    $(node).addClass('open');
                    if (node.tagName == 'LI') {
                      $(">a",$(node)).addClass('on').removeClass('off');
                    }
                    if ($(node).hasClass("expandable") || node.tagName == 'DIV') {
                       at_top = true;
                    }
                 
                  }
             }
          }
          
          $("#subnav .expandable>li").each(function(){
	              var li = $(this);
	              if (!li.hasClass("open")) li.addClass("closed");
	              if (!$("ul",li).not(".hidden").size()) li.addClass("nochildren");
          });
          
   },

	//rotates images on this page: /giving/classof2011.html
   giveHereImgRotator: function() {
        var images = ['givehere_1.gif', 'givehere_2.gif'];  
        
        $('<img src="/images/site/' + images[Math.floor(Math.random() * images.length)] + '" width="208" height="267" border="0" alt="Give Here" align="right" />').appendTo('#give_here_img');
   },   
   
   lightbox: function() {
          $("a.lightbox").click(function() {
              var a = this;          
              //if (!/\/videos\//.test(this.href)) {
              //   return;
              //}              
              //Alumni.getScript("/framework/js/plugins/fancybox/jquery.fancybox-1.3.1.pack.js",function(){   
   		   $.ajax({
   			      type: 'GET',
   			      url: a.href,
   			      cache: true,
   			      success: function(html) {
   			         //alert(html);
				 //var $content = $(html).find("#content>.inner");
				 //$("body").append('<div id=lightboxtmp></tmp>');
				 //$("#lightboxtmp").css("visibility","hidden").append($content);
				 //Alumni.rendervideos();
				 Alumni.renderVideos(true);
				 //Core.lightbox($("#lightboxtmp").html());
				 Core.lightbox(html);
				 //$("#lightboxtmp").remove();
   			      },
   			      error: function(req,text,error) {
   				 alert("error "+error);
   			      },
   			      dataType: 'html',
   			      data: null
   		      });
              //})
              
              return false;
          });
    },
    
    renderVideos: function(autoplay) {
        //alert("bla"); 	
        var num = 0;
        $("object[class='video']").each( function(i,v) {
              var vid = $(v);
              var src = $("param[name='source']",vid).attr('value');
              var img = $("param[name='image']",vid).attr('value');
              vid.replaceWith('<div id="video-embed-'+num+'" class="video"></div>');
              fo = new SWFObject("/flash/player.swf", "flash"+num, 320, 230+30, "8", "#000000");
              if (img) {fo.addVariable("image",img);}
              fo.addVariable("source",src);
              if (autoplay) {fo.addVariable("autoplay",true);}
              fo.addVariable("allowFullScreen", "true");
              fo.addVariable("analytics", "true");
              fo.addParam("allowFullScreen", "true");
              fo.addParam("wmode", "opaque");
              if (!fo.installedVer.versionIsValid(fo.getAttribute('version'))) {
                 $("#video-embed-"+num).append('<p class="noflash">Adobe Flash is required.  <a href="http://www.adobe.com/go/getflashplayer"><br /><img src="/images/site/get_flash_player.gif" height="31" width="88" /></a></p>');
              } else {
                 fo.write("video-embed-"+num);
              }
              num += 1;
         });
    }, 

    renderGivingVideos: function(){
       $("a.btn-play").click(function(){
              fo = new SWFObject("/flash/player.swf", "flash", 480, 270+30, "8", "#000000");
              fo.addVariable("source",this.href);
              fo.addVariable("autoplay",true);
              fo.addVariable("allowFullScreen", "true");
              fo.addVariable("analytics", "true");
              fo.addParam("allowFullScreen", "true");
              fo.addParam("wmode", "opaque");
              if (!fo.installedVer.versionIsValid(fo.getAttribute('version'))) {
                 var fallback = $(this).attr('fallback')
                 if (fallback) {
                     document.location.href = fallback;
                 } else {
                     $(this).parent().html("<div id=video-embed></div>");                 
                     $("#video-embed").append('<p class="noflash">Adobe Flash is required.  <a href="http://www.adobe.com/go/getflashplayer"><br /><img src="/images/site/get_flash_player.gif" height="31" width="88" /></a></p>');
                 }
              } else {
                 $(this).parent().html("<div id=video-embed></div>");
                 fo.write("video-embed");
              }
              return false;
       });
    },

    render480Videos: function(autoplay) {
        //alert("bla"); 	
        var num = 0;
        $("object[class='480video']").each( function(i,v) {
              var vid = $(v);
              var src = $("param[name='source']",vid).attr('value');
              var img = $("param[name='image']",vid).attr('value');
              var iosimg = $("param[name='iosimage']",vid).attr('value');
              var fallback = $("param[name='fallback']",vid).attr('value');
              vid.replaceWith('<div id="video-embed-'+num+'" class="video"></div>');
              fo = new SWFObject("/flash/player.swf", "flash"+num, 480, 268+30, "8", "#000000");
              if (img) {fo.addVariable("image",img);}
              fo.addVariable("source",src);
              if (autoplay) {fo.addVariable("autoplay",true);}
              fo.addVariable("allowFullScreen", "true");
              fo.addVariable("analytics", "true");
              fo.addParam("allowFullScreen", "true");
              fo.addParam("wmode", "opaque");
              if (!fo.installedVer.versionIsValid(fo.getAttribute('version'))) {
				if (autoplay) {
					if (jQuery.fancybox) {
					$("#fancybox-wrap").hide()
					window.setTimeout(function(){
					jQuery.fancybox.close()
					},100);
				}
				document.location.href = fallback;
			} else {
				$("#video-embed-"+num).append('<p><a href="'+fallback+'"><img src="'+iosimg+'" alt="Play Video"></a></p>');
			}
			} else {
				fo.write("video-embed-"+num);
			}
				num += 1;
		});
	},
    
   setuser: function(id,name,degree,year) { 
      
      var cstr = id + ':' + name + ':' + degree + ':' + year + ':1.0';
      var cookie_date = new Date ();
      cookie_date.setTime( cookie_date.getTime() + (1000*60*60*24*30) ); 
     
      Core.cookie("HBSINFO",cstr,{path:'/',expires:cookie_date,noencode:true,domain:'.hbs.edu'});
      
      Alumni.name = name;
      Alumni.year = year;
      Alumni.degree = degree;
      if (year) {
         Alumni.affiliation = degree + " '"+year;
      } else {
         Alumni.affiliation = degree;
      }
      var email = id;
      email = email.replace("bschool.hbs.edu","hbs.edu");
      email = email.replace(".alumni.hbs.edu",".hbs.edu");
      Alumni.email = email;
      Alumni.loggedin = true;
   },
   
   set_input: function(text,id) {  
          input = document.getElementById(id);
          console.info(text,id,input);
          if (!input) return false;
          if (id == "login-username" && input.value == text) {
             $(input).css("color","#9d9d9d");
          }
          if (id == "directory-lastname" && input.value == text) {
             $(input).css("color","#9d9d9d");
          }
          $(input).focus(function() {
             console.info("focus",this);
             if (this.value == text) {this.value = "";$(this).css("color","black")}
          });
          $(input).blur(function() {
             if (this.value == "") {this.value = text;$(this).css("color","#9d9d9d")}
          });
   },

   home_resources_hover: function() { 
    $("#home-resources-tab").hover( function () {$("#home-resources").show();}, 
                                        function () {}
                                       );
    
    $("#home-resources").hover( function () {}, 
                                    function () {$(this).hide();}
                                   );
   },
    
    
   ifloggedin: function() {
      // need to run this twice for IE bug
      var $body = $(document.body);
      if ($body.hasClass('logged-in') || $body.hasClass('logged-out')) return;
      
      if (Alumni.loggedin) {
         $body.addClass('logged-in');
      } else {
         $body.addClass('logged-out');
         $("#subnav .login-required a").click(function(){return false;}).addClass("disabled");
      }
   },
   
   ifs: function() {
      if (Alumni.loggedin) {
         var y = Alumni.year || '';
         var d = Alumni.degree || '';
         d = d.toLowerCase();
         d = d.replace(/[^a-z]/,'');
         $(".if-"+d).show();  // if-mba
         $(".if-"+d+"20"+y).show();  //if-mba20xx
         $(".if-"+d+"19"+y).show();  //if-mba19xx
      }
   },
   
    
   home_tabs: function() {
       $("#home-whatsnew-tab").click(function() {
            $("#col2").attr("class","whatsnew")
            return false;
       });
       $("#home-events-tab").click(function() {
            $("#col2").attr("class","events")
            return false;
       });
   },
   
   expandable_uls: function() {
       $("#content .wrap .expandable").not("table").each(function() {
           var lis = $(this).children()
           if (lis.length == 0) {return}
           $(lis[0]).addClass("first");
           $(lis[lis.size()-1]).addClass("last");
           lis.each(function() {
              var li = $(this)
              li.addClass("closed");
              var tog = $("a:first",this)
              tog.addClass("toggler");
              tog.click(function() {
                  li.toggleClass("closed");
                  li.toggleClass("open");
                  return false;
              });
           });
       });
   },
   
   expandable_tables: function() {
       $("#content .wrap table.expandable").each(function() {


           var table = $(this);
           $("td li",table).hide().css("display","none")
           var lis = $("th li",this);
           if (lis.length == 0) {return}
           $(lis[0]).addClass("first");
           $(lis[lis.size()-1]).addClass("last");
           
           lis.each(function(i) {
              var text = $(this).html();
              $(this).html('<a href="#" class="toggler">'+text+'</a>');
              $("a.toggler",this).click(function() {
                 $("th a.on",table).removeClass("on");
                 $(this).addClass("on");
                 $("td li",table).hide()
                 $("td li",table).slice(i,i+1).show()
                 return false;
              });
           });

       })
   },
   
 // Green Tooltip That Appears in Sidebar
   tooltips: function() {
        function findPos(obj)  {
            var curleft = curtop = 0;
            if (obj.offsetParent) {
                curleft = obj.offsetLeft
                curtop = obj.offsetTop
                while (obj = obj.offsetParent) {
                    curleft += obj.offsetLeft
                    curtop += obj.offsetTop
                }
            }
            return [curleft,curtop];
        }
        

        var toolsHelp = document.getElementById('form-help');
        var toolsCallout = document.getElementById('form-help-callout');

        if ( toolsHelp ) {         
            toolsHelp.onmouseover = function() {              
                toolsCallout.style.left = findPos(this)[0] - 250 + "px";               
                toolsCallout.style.top =  findPos(this)[1] + 27 + "px";
                toolsCallout.style.display = "block";
            }
            toolsHelp.onmouseout = function() {
                toolsCallout.style.display = "none";
            }
        }
   },
   

   loginform: function() {
      $("#loginform").submit(function(){ 
          var username = $("#login-username").val();
          username = jQuery.trim(username);
          
          var password = $("#login-password").val();
          password = jQuery.trim(password);
  
          var redir = document.location.href;
          
          // a redirect parameter is being passed to the /login/ page
          if (/\?http/.test(document.location.search)) {
             redir = document.location.search;
             redir = redir.replace(/^\?/,'');
          }
          if (redir.indexOf('/login/') == -1) {
             $("input[name='url']",this).val(redir);
          }

          if (/@hbs.edu/.test(username)) {
             $("#login-username").val(username);
          } else if (/.hbs.edu/.test(username)) {
             $("#login-username").val(username);
          } else if (/^[a-z]+$/.test(username)) {
             $("#login-username").val(username);
          } else {
             $("#login-username").val(username + ".hbs.edu");
          }

          
          
          
          return true;
      });
   },
   
   outage: function() {
      if(Outage.is_down()) {
          var msg = "<p style=\"padding-top:.5em;font-weight:bold;\">Login Unavailable</p>"+Outage.message() +"<br>";
          $("form[action~='secure.hbs.edu/login']").replaceWith(msg);
      }
   },
   
   csstweak: function() {
      var p = $("div.content-title").next().each(function() {
         if (this.tagName == 'P') $(this).css("margin-top","1em");
      })
      
   },
   
   // Class year info is here
   draw_login: function() {
      if (RegExp("/apps/login/").test(document.location.href)) return;
      var html = '';
      var info = Core.cookie("HBSINFO");
      if (!info) {return};
      var p = info.split(":");

      var s = p[1] + ", " + p[2];
      var c = '';
      if (p[3]) {
        //  s = '<img  class="class-year"  src="http://www.alumni.hbs.edu/images/site/years/'+p[3]+'.gif" alt="'+p[3]+'">' + s
		  s = s + p[3];
          c = " userwyear"
      }
      
      if (window.appname == 'navigator') {
      
         html +=      '<div class="user-info">';
         html +=         '<p>Logged in as:</p>';
         html +=         '<p class="user'+c+'"><strong>'+s+'</strong></p>';
         html +=         '   <a href="http://www.alumni.hbs.edu/cgi-bin/logoff.cgi">Logout</a>';
         html +=      '</div>';
         html +=    '</div>'
      
      } else {
      
         html +=         '<p><em>You are logged in:</em></p>';
         html +=         '<p class="user'+c+'"><strong>'+s+'</strong></p>';
      
      }

      Alumni.loggedin = true;
      if (s && !window.loadcomplete) document.write(html);
   },
   
   bulletin: function() {
        var loc = document.location.href;
        if (document.location.href.indexOf('/bulletin/') == -1) {return}
        var rx = new RegExp("/bulletin/([0-9]+)/([a-z]+)/");
        var m = rx.exec(loc)
        if (m) {
           var year = m[1];
           var month = m[2];
           $("#subnav img.cover").wrap('<a href="/bulletin/'+year+'/'+month+'/"></a>');
        }
        
        $("#content .archive img").each(function() {
            if (/update/.test(document.location.href)) return;
            if (document.getElementById('noresize')) return;
            var img = $(this);
            if (img.hasClass('caption')) return;
            var h = img.height();
            var w = img.width();
            if (h && w) {
               img.attr('height',h*.75);
               img.attr('width',w*.75);
            }
            
        });
        
        $("#content #related").each(function() {
           var html = $(this).html()
           $(this).remove()
           $("#subnav").append(html);
        });
        
        Alumni.clean_comments();
   },
   
   // Carousel Code
   autorotate: 1,
   carousel: function() {
        if (!document.getElementById("carousel")) return;
        $("#play").hide();
        
        var low = 0;
        var high = $("#carousel > div").size() - 1;
        //var current = Math.floor(Math.random() * ( 1 + high - low ) + low );
        var current = 0;
        
        function showdiv(num) {
           console.info('showing',num);
           $("#carousel>div").each(function(i) {
              i == num ? $(this).show() : $(this).hide()
           });
           
           $("#carousel ul#nav-carousel li").each(function(i) {
  	    i == num ? $(this).addClass('on') : $(this).removeClass('on')
           });
        }
      
        $("#carousel ul#nav-carousel li").each(function(i) {
          $(this).click(function(){current = i;showdiv(i);Bulletin.autorotate = 0;return false;});
        });
        
        
        $("#prevnext-prev").click(function() {
           Alumni.autorotate = 0;
           current = current - 1;
           if (current < 0) { current = high }
           showdiv(current);
           return false;
        });
        
        $("#prevnext-next").click(function() {
           Alumni.autorotate = 0;
           current = (current + 1) % (high + 1);
           showdiv(current);
           return false;
        });

        $("#play").click(function() {
		Alumni.autorotate = 1;		
		rotate();
           	$(this).hide();
           	$("#pause").show();
		showdiv(current);
        });
        
        $("#pause").click(function() {
           Alumni.autorotate = 0;
           showdiv(current);
           $(this).hide();
           $("#play").show();
           return false;
        });
      
        function rotate(){ 
           window.setTimeout(function(){
              if (!Alumni.autorotate) return;
              current = (current + 1) % (high + 1);
              showdiv(current);
              rotate();
           },8000);
        }
      
        rotate();
        showdiv(current);
      
   },   
   
   ebaker: function() {
        var loc = document.location.href;
        if (document.location.href.indexOf('/ebaker/') == -1) {return}
        
        $("a.how-to").click(function() {
          if ($(this).hasClass("open")) {
              $(this).removeClass("open")
              $(this).css("font-weight","normal");
              var container = this.parentNode.parentNode;
              $("div.how-to",$(container)).slideUp();
          } else {
              $(this).addClass("open")
              $(this).css("font-weight","bold");
              var container = this.parentNode.parentNode;
              $("div.how-to",$(container)).slideDown();
          }
          return false;
        });
   
   },
   
   autofill_forms: function() {

        if (Alumni.loggedin && document.getElementById('commentform')) {
           $("#commentform input[name='N']").val(Alumni.name);
           $("#commentform input[name='Affiliation']").val(Alumni.affiliation);
        }
        
        if (Alumni.loggedin && document.getElementById('feedbackform')) {
           $("#feedbackform input[name='sender']").val(Alumni.name + ', ' + Alumni.affiliation);
           $("#feedbackform input[name='email']").val(Alumni.email);
        }

        if (Alumni.loggedin && document.getElementById('onesourcetrial')) {
           $("#onesourcetrial input[name='email']").val(Alumni.email);
        }
        
        if (document.getElementById('sendtofriendform')) {
           var title = unescape(window.location.search.substring(7));
           if (title) {
              $("#sendtofriendform input[name='title']").val(title);
           }
           $("#sendtofriendform input[@name='cameFrom']").val(document.referrer);
           if (Alumni.loggedin) {
               $("#sendtofriendform input[name='friend']").val(Alumni.name);
               $("#sendtofriendform input[name='f']").val(Alumni.email);
           }
        }
   },
   
   homepage: function() {
        // correct long names on the homepage (not sure if we need this and it has a safari bug)
        return
        if (document.body.className.indexOf("home") > -1) {
           if ($("div.login").height() > 80) {
              $("#content-top").addClass("size-3");
           }
        };
   },
   
   gallery: function() {
      $("a.go-gallery").click(function(){
         Gallery.run($(this).attr('href'));
         return false;
      });
   },
   
   facultysearch: function() {
      $("a.go-facultysearch").click(function(){
         var url = "/ssi/facultysearch.html";
         $.ajax({
              type:"GET",
              url:url,
              success: function(data) {
                   var data = $("<div/>").append(data);
                   var html = data.find("#facultysearch-insert").html();
                   Lightbox.show(html);
              },
              error: function(msg) {
                   document.location = $("a.go-facultysearch").attr('href');
              }
         });
         return false;
      });
   },

   clubsearch: function() {
      $("a.go-clubsearch").click(function(){
         var url = "/ssi/clubsearch.html";
         $.ajax({
              type:"GET",
              url:url,
              success: function(data) {
                   var data = $("<div/>").append(data);
                   var html = data.find("#clubsearch-insert").html();
                   Lightbox.show(html);
              },
              error: function(msg) {
                   document.location = $("a.go-clubsearch").attr('href');
              }
         });
         return false;
      });
   },
   
   reunionsearch: function() {
      $("a.go-reunionsearch").click(function(){
         var url = "/ssi/reunionsearch.html";
         $.ajax({
              type:"GET",
              url:url,
              success: function(data) {
                   var data = $("<div/>").append(data);
                   var html = data.find("#reunionsearch-insert").html();
                   Lightbox.show(html);
              },
              error: function(msg) {
                   document.location = $("a.go-reunionsearch").attr('href');
              }
         });
         return false;
      });
   },   
   
   tabs: function() {
     $("div.tab-container").each(function() {

        var container = this;
        if($("a.on",container).size() == 0) {
           $("a.tab:first",container).addClass("on");
        }
        toggle_tab(0);
        
        function toggle_tab(num) {
           $("div.tab-content",container).each(function(x) {
              if(x==num) {
                $(this).show();
              } else {
                $(this).hide();
              }
           });
        }
        
        $("a.tab",container).each(function(num) {
           $(this).click(function(){
               if ($(this).hasClass('nojs')) {return true;}
               $("a.on",container).removeClass("on");
               $(this).addClass("on");
               toggle_tab(num);
               return false;
           });
        });
        
     });
   },
   
   setscroll: function() {
   
      // we have to do this because the screen 
      // redraws onload and breaks
      // anchor links
      // and some pages have anchors inside collapsed elements
      // http://webstage.alumni.hbs.edu/faq/#ebaker
      // http://webstage.alumni.hbs.edu/reunions/faculty_presentations.html#finance

      function scrollto(target) {
         // remove any current targets and scroll to the new one
         $(".expandable li.open a.toggler").trigger("click");
         $(".hash-focus").removeClass("hash-focus");

         target = $(target);
         if (!target.size()) return;
         target.addClass("hash-focus");


         
         // if the focus in on a toggler, open it up
         $(".expandable li.hash-focus a.toggler").trigger("click").parent().css({backgroundColor:"#EEF8BD"}).animate({backgroundColor:"white"},1700);
         
         // if the focus is inside a toggler, open up the parent
         $(".expandable li .hash-focus").css({backgroundColor:"#EEF8BD"}).animate({backgroundColor:"white"},1700).parent().find("a.toggler").trigger("click")

         var targetOffset = target.offset().top;
         $('html,body').animate({scrollTop: targetOffset - 50}, 1);

      }

      function pollhash() {
          setTimeout(pollhash,300);

          var hash = document.location.hash;
          if (!hash) return;
          if (Alumni.lasthash && hash == Alumni.lasthash) {return}  // same hash as before

          var piece = hash.replace("#",'');
          var target = document.getElementById(piece) || $("#content a[name='"+piece+"']:first");

          scrollto(target)
          Alumni.lasthash = hash;
      }
      
      pollhash();


   },
   
   rewrite_emails: function(form) {
        if ((form.e && form.e.value == 'jcahill') || (form.e && form.e.value == 'classified_ad')) {
                form.e.value = form.e.value + '@hbs.edu';
        }
   },
   
   techrequest_send: function(form) {
        form.s.value =  form.s.value + " - " + form.category.value; //generate subject line
        if (form.category.value === 'Website') {
                form.e.value = 'alumniweb@hbs.edu';
        }
   },   
   
   printthispage: function() {
      $("#printthispage").click(function(){
         window.print();
         return false;
      });
   },
   
   sendtofriend: function() {
      if (!document.getElementById('sendtofriend')) return;
      if (/\/bulletin\//.test(document.location.href)) {
         var href = $("#sendtofriend").attr('href');
         var title = $("#content h3:first").text();
         $("#sendtofriend").attr('href',href+"?title="+escape(title))
      }
   },
   
   links: function() {
   
      $("#givebutton a").click(function(){
          analytics.view(this.href)
      });

   
      $("a").each(function(x,link){
      
         if (link.className.indexOf("new_window") > -1 || 
             link.className.indexOf("go-database") > -1 ) {
           $(link).click(function(){
              // prevent doubleclicking
              if ($(link).hasClass("clicking")) return false;
              $(link).addClass("clicking");
              Alumni.new_window(link);
              window.setTimeout(function(){$(link).removeClass("clicking")},500);
              return false;
           });
         }
         
         if (link.className.indexOf("popup") > -1) {
           $(link).click(function(){
              Alumni.popup(link);
              return false;
           });
         }
         
      });
      
   },
   
   /*
    *  finds and enables video objects
    */ 

   rendervideos: function() {
      var num = 0;
      $("object[class='video']").each( function(i,v) {
          var vid = $(v);
          var src = $("param[name='source']",vid).attr('value');
          var img = $("param[name='image']",vid).attr('value');
          var fmt = $("param[name='format']",vid).attr('value');
          var size = $("param[name='size']",vid).attr('value');
          vid.replaceWith('<div id="video-embed-'+num+'"></div>');
           
          var fo;
          fo = new SWFObject("/flash/inline_vid_336x189.swf", "flash"+num, 336, 189+29, "8", "#000000");
          fo.addVariable("screenshot",img);
          fo.addVariable("vidSource",src);
          if (!fo.installedVer.versionIsValid(fo.getAttribute('version'))) {
              //fo.installedVer.major
             $("#video-embed-"+num).append('<p class="noflash">Adobe Flash is required.  <a href="http://www.adobe.com/go/getflashplayer"><br /><img src="/images/site/get_flash_player.gif" height="31" width="88" /></a></p>');
          } else {
             fo.write("video-embed-"+num);
          }
          num += 1;
      });
   },
   
   thisurl: function() {
        var thisurl = document.location.href;
        if (thisurl.indexOf('#') > -1) {
           thisurl = thisurl.split(/#/)[0];
        }
        if (thisurl.indexOf('list_editables') > -1 ) {
           thisurl = document.referrer;
        }
        return thisurl;
    },

    normalize: function(url) {
       url = url.replace(/index.html/,'')
       return url;
    },

    sameurl: function(url,link) {
       if (!link || !link.href){return 0}
       if (Alumni.normalize(url) == Alumni.normalize(link.href)) {return 1};
       return 0;
    },
    
    new_window: function(link) {
      var url = link.href || link;
      var nw = window.open(url, "newwin", 'width=800,height=550,directories=yes,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
      if (nw) {nw.focus();}
    },
    
    popup: function(link) {
      var url = link.href || link;
      //var nw = window.open(url, "newwin", 'width=400,height=250,directories=yes,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
     // if (nw) {nw.focus();}
    },
    
    last:''
   
   
}

var Outage = {
    is_down: function() {
        return false;
        var now = new Date();
        var start = new Date();
        start.setTime(Date.parse("Jul 3,2008 12:00:00 GMT-0400"));
        var end = new Date();
        end.setTime(Date.parse("Jul 4,2008 18:00:00 GMT-0400"));
        if (now > start && now < end) {
           return true;
        } else {
           return false;
        }
    },
    
    message: function() {
        return "<p>Due to IT maintenance, login will be unavailable from <b>Thursday, July 3rd at 12:00pm EDT</b> through <b>Friday July 4 at 6:00pm EDT</b></p>";
    }
}


var AlumniApps = {
     ondomready: function() {
        if (AlumniApps[window.appname]) AlumniApps[window.appname]();
        AlumniApps.cleanup();
     },
     
     dynamo: function() {
        if (/apps\/login/.test(document.location)) {
           $("#appcontent p").each(function(){
              if (/NOTE:/.test($(this).text())) {$(this).hide().parent().after('<p><b>NOTE: </b> If you have forgotten or need to change your password, please use our <a href="http://www.alumni.hbs.edu/lefa/">online tools</a> (available 24hrs/day) or contact the Alumni Records Office at 617-495-6438 (M-F, 9AM-5PM ET), <a href="mailto:alumni_records@hbs.edu"> alumni_records@hbs.edu</a>. If you are an HBS faculty or staff member or a current MBA student, please <a href="https://secure.hbs.edu/login/'+document.location.search+'">click here</a> to log in.</p>');}
           });
        } 
        if(Outage.is_down()) {
           var msg = Outage.message();
           $("#content h1").replaceWith("<h1>Login Unavailable</h1>");
           $("#content form[action~='secure.hbs.edu/login']").replaceWith(msg);
        }
     },
     
     classnotes: function() {
        $("#content table[@width='60%']").addClass("issuenav").removeAttr('bgcolor').removeAttr('width').removeAttr('align').removeAttr("cellpadding");
        $("img[src~='clear_form']").parent().remove();
        $("img[src~='forms/submit.gif']").replaceWith('<button id="submitbtn">Submit</button>');
        $("span.form-header").each(function(){$(this).replaceWith('<h3 class="form-header">'+$(this).text()+'</h3>');})
     },

     navigator: function() {
        $(".12-text").addClass("middle");
        $("table[bgcolor='#cccccc']").addClass("narrow").removeAttr('bgcolor');
        $("td[bgcolor='#990000']").addClass("hr").removeAttr('bgcolor');
        $("td[bgcolor='#f3efe6']").addClass("update").removeAttr('bgcolor').parent();
        $("td[valign='center']").css("text-align","center");
        $(".12-text-dkred-bold").parent().find("br").remove();
        $("a[href~='Search()']").attr('id','searchbtn').html("Search")
        $("tr[bgcolor='#cccccc']").remove();
        $("img[src~='remove']").addClass("remove");
        //$("img[src~='findsimilar']").parent().html("<button>Find Similar</button>");
     },

     cleanup: function() {
        analytics.settings({profile:'alumni'});

        $("#tools-help").show()
        $("#tools-help p").html("Find a friend, find a job, or find out more about the latest HBS research. Access a wealth of tools and resources exclusively for HBS alumni with your LEFA.");
        Alumni.tooltips();

        $("#hbs100link").css("visibility","hidden");
        
        $('#volunteers-nav').html('Boards &amp; Volunteers');
        $('#clubs-nav').parent('li').css('margin-left','1.75em');
        $('#bulletin-nav').html('Bulletin');

        var d = new Date();
        var year = d.getFullYear();
        $("#copyright").html("Copyright &copy " + year + " President & Fellows of Harvard College");

        $("ul.my-alumni li.first").html('<a href="http://www.alumni.hbs.edu/lefa/">LEFA Info</a>')
        
        if (!$("#search_form input[name='sub']").size()) { $("#search_form").append('<input type="hidden" name="sub" value="alumni" />') }
        
        $("#footer ul.nav li.last").html('<a href="http://www.alumni.hbs.edu/feedback/">Give Us Feedback</a>').prev().remove();
        
        $("a[href~='hbr_home.jhtml']").attr('href','http://www.alumni.hbs.edu/hbrsa/hbrsa.html');

        // add google analytics tag
        $.ajax({
            type: 'GET',
            url: 'http://www.google-analytics.com/ga.js',
            cache: true,
            success: function() {
                 if (window._gat) {
                    var pageTracker = _gat._getTracker("UA-389200-2"); 
		    pageTracker._initData(); 
                    pageTracker._trackPageview(); 
                 }
            },
            dataType: 'script',
            data: null
        });

     }
}


var Gallery = {
    run: function(url) {
        $.get(url,function(data) {
           var data = $("<div/>").append(data);
           var title = data.find("#gallery-title").html();
           var images = data.find("#gallery-images");
           Gallery.totalimages = 0;
           Gallery.currentnum = -1;
           Gallery.render(title,images);
        });
        
    },
    totalimages: 0,
    currentnum: -1,
    images: [],
    render: function(title,images) {
        var body = $("body");
        body.append('<div id="lightbox-wrap" style="display:none"></div>');
        html = '<div class="gallery-lightbox" id="lightbox" style="display:none"><a class="close" href="#">close</a>';
        html += '<div class="gallery">'
        html += '<h4>'+title+'</h4><ul id="lightbox-thumnails">';
        
        var lis = images.find("li");
        Gallery.totalimages = lis.size();
        Gallery.images = images;
        var fullimages = '';
        lis.each(function(i){
           var li = $(this);
           var src = $("img:first",li).attr("src");
           html += '<li><img src="'+src+'" alt="" height="30" width="42" /></li>';
           fullimages += '<div><img src="'+src+'" alt="" />';
           var caption = $("p:first",li).html();
           if (caption) {
              fullimages += '<br/><span class="caption">'+caption+'</span>';
           }
           fullimages += '</div>';
        });
        html += '</ul></div>'
        html += '<div class="detail">';
        html += '  <div class="detail-nav" id="lightbox-detail-next"></div>'
        html += '  <div class="detail-image" id="lightbox-detail-image">'+fullimages+'</div>'
        html += '</div>';
        html += '</div>';
        body.append(html);
        //$("#lightbox-wrap").fadeIn();
        //$("div.gallery-lightbox").fadeIn()
        
        $("#lightbox-wrap").show();
        $("div.gallery-lightbox").show()

        var scroll = Lightbox.getPageScroll()
        $("#lightbox").css("top",scroll[1]+300);
        


        Gallery.setimage(0);
        
        $("#lightbox-thumnails img").each(function(i) {
           $(this).click(function() {
             Gallery.setimage(i);
             return false;
           });
        });
        
        $("div.gallery-lightbox a.close").click(function() {
            Lightbox.close();
            return false;
        });
        
       
        
        
    },
    
    setimage: function(num) {
        if (Gallery.currentnum == num) return;
        Gallery.currentnum = num;
        $("#lightbox-thumnails li.on").removeClass("on");
        var img = $("#lightbox-thumnails img")[num];
        img = $(img);
        img.parent().addClass("on");

        $("#lightbox-detail-image").find(">div:visible").fadeOut()
        $("#lightbox-detail-image").find(">div:eq("+num+")").fadeIn()
        var total = Gallery.totalimages;
        var next = '';
        if (num != '0') {
           next += '<a class="prev" href="#">prev</a>';
        }
        if (num < total - 1) {
           next += '<a class="next" href="#">next</a>';
        }
        $("#lightbox-detail-next").html(next);
        
        $("#lightbox-detail-next a.next").click(function() {
           Gallery.setimage(Gallery.currentnum + 1);
           return false;
        });
        $("#lightbox-detail-next a.prev").click(function() {
           Gallery.setimage(Gallery.currentnum - 1);
           return false;
        });
        
    }
    
}


var Lightbox = {
    show: function(insert) {
        var body = $("body");
        body.append('<div id="lightbox-wrap" style="display:none"></div>');
        html = '<div class="gallery-lightbox" id="lightbox" style="display:none"><a class="close" href="#">close</a>';
        html += insert
        body.append(html);
        //$("#lightbox-wrap").fadeIn('fast');
        //$("div.gallery-lightbox").fadeIn('fast')
        $("#lightbox-wrap").show();
        $("div.gallery-lightbox").show();

        $("#flashcontent").css("visibility","hidden")
        var scroll = Lightbox.getPageScroll()
        $("#lightbox").css("top",scroll[1]+300);
        
        $("div.gallery-lightbox a.close").click(function() {
	            Lightbox.close();
	            return false;
        });
    },
    
    
    close: function() {
       //$("#lightbox-wrap").fadeOut("normal",function(){$(this).remove()});
       //$("div.gallery-lightbox").fadeOut("normal",function(){$(this).remove()});
       $("#lightbox-wrap").remove();
       $("div.gallery-lightbox").remove();
       $("#flashcontent").css("visibility","visible")
    },
    
    getPageScroll: function() {
            var xScroll, yScroll;
            if (self.pageYOffset) {
                yScroll = self.pageYOffset;
                xScroll = self.pageXOffset;
            } else if (document.documentElement && document.documentElement.scrollTop) {     // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
                xScroll = document.documentElement.scrollLeft;
            } else if (document.body) {// all other Explorers
                yScroll = document.body.scrollTop;
                xScroll = document.body.scrollLeft; 
            }
            arrayPageScroll = new Array(xScroll,yScroll) 
            return arrayPageScroll;
     }
     
}



window.Alumni = Alumni;

if (window.Bulletin) {
  // do nothing
} else if (window.appname) {
  $(document).ready(function(){AlumniApps.ondomready()});
} else {
  $(document).ready(function(){Alumni.ondomready();});
  $(window).load(function(){Alumni.onload()});
  Alumni.hidebody();
}



})(jQuery);

