/*
** library.js - Library Javascript Library
** jgriffith
**
*/

Core.log.email = true;

(function($){

var Library = {
  
   ondomready: function() {
        Library.ebaker();
        Library.carousel();
		Library.expandables();
        Library.expandall();
        Core.settings({site:'library'});
        
        subHover();
        rewrite_links();
		Library.links();
       
        if (window.analytics) {analytics.save()}
       
   },

   ebaker: function() {
        if (! /ebaker/.test(document.location.href)) { return }
        
        $("ul.expandable ol").hide()
        $("ul.expandable>li>a").click(function() {
          $(this).next().slideToggle();
          return false;
        })

        $("div.resource div.how-to").hide();
        $("div.resource a.how-to").click(function(){
            $(this).parent().parent().find("div.how-to").slideToggle();
            return false;
        });

   },
   
   expandables: function() {
        $("#content dl.expandable dd").addClass("closed");
        $("#content dl.expandable dd a").click(std_newwindow);
        $("#content dl.expandable dt").click(function() {
          $(this).toggleClass("open");
          $(this).next().toggleClass("closed");
          $("#content dl.expandable dt.stayopen").addClass("open");
          return false;
        });
    },
  
   expandall: function() {    
      $("#expandall").click(function() {
           $("#content dl.expandable dd").toggleClass("closed");
           $("#content dl.expandable dd").toggleClass("open");
           return false;
      });
   },
       
   links: function() {
      $("a.downloadlink").mousedown(function(){ analytics.view(this.href); 
	  });
   },

// Carousel Code
   autorotate: 1,
   carousel: function() {
        if (!document.getElementById("carousel")) return;
        
        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);Library.autorotate = 0;return false;});
        });
        
        
        $("#prevnext-prev").click(function() {
           Library.autorotate = 0;
           current = current - 1;
           if (current < 0) { current = high }
           showdiv(current);
           return false;
        });
        
        $("#prevnext-next").click(function() {
           Library.autorotate = 0;
           current = (current + 1) % (high + 1);
           showdiv(current);
           return false;
        });
      
        function rotate(){ 
           window.setTimeout(function(){
              if (!Library.autorotate) return;
              current = (current + 1) % (high + 1);
              showdiv(current);
              rotate();
           },3000);
        }
      
        rotate();
        showdiv(current);
      
    }
   
}

window.Library = Library;

$(document).ready(function(){Library.ondomready();});

})(jQuery);



/* ***************************************************************************************

   Dropmenu Code

*************************************************************************************** */

var agt=navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_netscape6 = (is_nav && (agt.indexOf('netscape6')!=-1));
var is_mac    = (agt.indexOf("mac")!=-1);
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_opera = (agt.indexOf("opera") != -1);

if (is_mac && is_ie || is_netscape6 || is_opera) {
	//do nothing
} else {

subHover = function () {
	trace("performing subhover");
	if (!document.getElementById("gnav")) {return;}
	var subEls = document.getElementById("gnav").getElementsByTagName("li");
		for (var i=0; i<subEls.length; i++){
			subEls[i].onmouseover=function() {
				//if (this.className.indexOf('subhover') == -1) {
					this.className+=" subhover ";
			//}
				//if (!(this.id == 'find' || this.parentNode.id == 'find' || this.parentNode.parentNode.id == 'find')) {
				//	alert(this.id);
                //  setTimeout("hoveroff('find')",150);
                  // this is to deal with the front page find
		        //}
 			}
    	    subEls[i].onmouseout=function() {
    		    //this.className=this.className.replace(new RegExp("subhover\\b"), "");
    		    setTimeout("hoveroff(\""+this.id+"\")",150);
            }
       }
  }

function hoveroff(id) {
	trace('hoveroff');
    element = document.getElementById(id);
    if (element) {
        element.className=element.className.replace(new RegExp("subhover\\b"), "");
        //alert(element.className);
    }
}
//function hoveroff(id) {
 //   element = document.getElementById(id);
   // if (element) {
    //    element.className=element.className.replace(/subhover/gi, "");
  //  }
//}

// delay on the first mouseover on the page
// need to delay menu close
}




/* ***************************************************************************************

   Popup Code

*************************************************************************************** */


// finds a good spot on the screen to position the new window
function windowpos() {
    trace('window pos');
    var x;
    var y;
    if (window.screenLeft) {  //IE
         x = window.screenLeft + 10 + Math.floor(Math.random()*41);
         y = window.screenTop + 10 + Math.floor(Math.random()*41);
         y = y - 100;
    } else if (window.screenX) {
         x = window.screenX + 10 + Math.floor(Math.random()*41);
         y = window.screenY + 10 + Math.floor(Math.random()*41);
    } else {
         x = 10 + Math.floor(Math.random()*41);
         y = 10 + Math.floor(Math.random()*41);
    }
    var pos = ",left="+x+",top="+y+",";
    //alert(pos);
    trace('finished pos');
    return pos;
}

function focus(win) {
  trace('begin focus');
  try {
     if (win) {win.focus();}
  } catch (e) {

  }
  trace('focus done');
}


function base_href() {
 var b = document.getElementsByTagName('base');
 if (b && b[0] && b[0].href) {
   return b[0].href;
 }
 return '';
}

/// used for new window
function new_window(url) {
  trace('new_window');
  analytics.view(url);
  nw = window.open(url, "_blank", 'width=800,height=650,directories=yes,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes'+windowpos());
  focus(nw);
  return false;
}

/// used for pop ups
function popup(url) {
  trace('popup');
  analytics.view(url);
  nw = window.open(url,'_blank', 'width=750,height=450,resizable=yes,menubar=yes,location=yes,toolbar=yes,scrollbars=yes'+windowpos());
  focus(nw);
  return false;
}

function new_db_window(url) {
  trace('new_db_window');
  analytics.view(url);
  nw = window.open(url, "_blank", 'width=800,height=650,directories=yes,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes'+windowpos());
  focus(nw);
  return false;
}

function new_db_window2(url) {
  trace('new_db_window2');
  // a slightly offset database window used on pages like this
  // http://webstage.library.hbs.edu/intra/go/venturexpert.html
  analytics.view(url);
  nw = window.open(url, "_blank", 'width=800,height=650,directories=yes,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes'+windowpos());
  focus(nw);
  return false;
}

/// used for print pop ups
function printpop(url) {
  trace('new_db_window');
  analytics.view(url);
  nw = window.open(url, '_blank', 'width=650,height=500,resizable=yes,location=yes,toolbar=yes,menubar=yes,scrollbars=yes'+windowpos());
  focus(nw);
  return false;
}


/// used for hc pop ups
function hcpopup(url) {
  trace('hcpopup');
  analytics.view(url);
  nw = window.open(url, '_blank', 'width=470,height=550,resizable=yes,location=yes,toolbar=no,menubar=no,scrollbars=yes'+windowpos());
  focus(nw);
  return false;
}

function database_popup() {
    trace('database_popup');
    return new_db_window(this.href);
}

function pdf_popup() {
    trace('pdf_popup');
    //register_click_a(this);
    return new_db_window(this.href);
}

function print_popup() {
    trace('print_popup');
    //register_click_a(this);
    return printpop(this.href);
}

function hc_popup() {
    trace('hc_popup');
    //register_click_a(this);
    return hcpopup(this.href);
}

function std_popup() {
    trace('std_popup');
    //register_click_a(this);
    return popup(this.href);
}

function std_newwindow() {
    trace('std_newwindow');
    //register_click_a(this);
    return new_window(this.href);
}


function is_offsite_link(a) {
   var thisdomain = document.location.host;
   var linkdomain = a.host.replace(/:\d+/,'');
   if (linkdomain && linkdomain != thisdomain) {
       return 1
   } else {
       return 0;
   }
}

// turns all database links into popup windows
// and PDF links to new windows

function rewrite_links() {
    trace("performing rewrite_links");
    
    var links = document.getElementsByTagName('a');
    for (var x = 0;x < links.length; x++) {
        a = links[x];
        if (!a.href) {continue;}
        var dbpopup = false;
        if (a.href.indexOf('hul.eresource') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('/bkr_cgi/database/') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('http://voyager.library.hbs.edu/') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('holliscatalog.harvard.edu') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('tdnet.com') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('hul.eresource') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('lewis.hul.harvard.edu') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('e-research.lib.harvard.edu') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('ezp1.harvard.edu') > -1 ) { dbpopup = true; } //also true for tdnet above
        if (a.href.indexOf('/bkr_cgi/voy') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('/bkr_cgi/hollis') > -1 ) { dbpopup = true; }
        if (a.href.indexOf('/catalog/') > -1 ) { dbpopup = true; }
        if (dbpopup) { 
           a.className += " offsite";  //add stats
           a.onclick = database_popup; 
        }

        var pdf = false;
        if (a.href.search(/\.pdf$/) > -1) {pdf = true;}
        if (pdf) {
            if (a.className.indexOf('pdf') == -1) { a.className += ' pdf'; }   //add stats
            a.className += ' offsite';
            a.onclick = pdf_popup;
        }

        if      (a.className.indexOf('print') > -1 && a.className.indexOf('popup')) { a.onclick = print_popup; }
        else if (a.className.indexOf('hc') > -1 && a.className.indexOf('popup')) { a.onclick = hc_popup; }
        else if (a.className.indexOf('popup') > -1) { a.onclick = std_popup; }
        else if (a.className.indexOf('newwin') > -1) { a.onclick = std_newwindow; }
        
        if (is_offsite_link(a) && !a.onclick) {
            a.onclick = function() {
                analytics.view(this.href);
                return true;
            }
        }
    }
}



/* ***************************************************************************************

   Scripts.js

*************************************************************************************** */




var hours = "";

// used on book and article forms (code from w3schools)
function showdate(){
    trace('showdate');
    var d=new Date();
    var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
    document.write(weekday[d.getDay()] + " ");
    document.write(d.getDate() + ". ");
    document.write(monthname[d.getMonth()] + " ");
    document.write(d.getFullYear());
}

// code for dropdown
function dropdown(element) {
      trace('dropdown');
      whichOne = element.selectedIndex;
      document.location = element.options[whichOne].value;
}

// a noop for the trace function when logging is turned off
function trace(str) {};

// function at top of all internal pages
function go(where){   trace('go'); document.location = where;}

// stage a form
function stage_form(form){
    trace('stage form');

    if (document.location.href.indexOf('webdev') > -1 ||
        document.location.href.indexOf('webstage') > -1) {
        if (form.e && form.f) {
            if (!form.e.length) {
               form.e.value = form.f.value;  // always send the admin email to whatever was typed in
            } else {
               for (x=0;x<form.e.length;x++) {
                  form.e[x].value = ''
               }
               form.e[0].value = form.f.value;
            }
        }
        if (!form.f && form.email) {
            form.e.value = form.email.value;  // if you aren't using the 'f' variable, you might be using the 'email' one instead
        }

        if (form.aTemplate) {
            form.aTemplate.value = form.aTemplate.value.replace(/www\.library\.hbs\.edu/,"webstage.library.hbs.edu");
        }
        if (form.u) {
            form.u.value = form.u.value.replace(/www\.library\.hbs\.edu/,"webstage.library.hbs.edu");
        }
    }
} 


// code for toggling div visibility
function swap(targetId){
    trace('swap');
    if (document.getElementById)
    {
    target = document.getElementById(targetId);
        //alert(target.style.display);
        if (target.style.display == "none" || !target.style.display)
            {
            //alert('show');
            target.style.display = "block";
            }
        else
            {
            //alert('hide');
            target.style.display = "none";
            }
    }
}


/* ***************************************************************************************

   HOME ROTATE CODE

*************************************************************************************** */


// definition and function to write random profiles to the home page
var homephoto_alt = new Array(20);
// Enter the total number of profiles for the home page here.
// Make sure there are at least this many images and alt tags in the array.
var totalhomeprofiles = 5;
// Images and alt tags for the right side image of the profile
homephoto_alt[1]="Photo 1: Historical Collections, Baker Library | Bloomberg Center";
homephoto_alt[2]="Photo 2: Stamps Reading Room, Baker Library | Bloomberg Center";
homephoto_alt[3]="Photo 3: Stamps Reading Room, Baker Library | Bloomberg Center";
homephoto_alt[4]="Photo 4: Inside the Exchange, Baker Library | Bloomberg Center";
homephoto_alt[5]="Photo 5: Baker Staircase, Baker Library | Bloomberg Center";
pn = Math.round(Math.random() * (totalhomeprofiles - 1)) +1;
// Function to write the rotating code on the front page.

function write_random_homephoto() {
	trace('write_random_homephoto');
	document.write('<div><img src=\"\/images\/front\/rotating\/' + pn + '\/photoL.jpg\"  width=\"139\" height=\"252\" border=\"0\" alt=\"\"><\/div>');
	document.write('<div id=\"findmenu\" class=\"findbg' + pn + '\"><ul><li><a href=\"\/findarticles.html\">Articles<\/a><\/li><li><a href=\"\/findbooks.html\">Books<\/a><\/li><li><a href=\"\/hbs_cases.html\">HBS Cases<\/a><\/li><li><a href=\"\/corporate_reports\/\">Corporate Reports<\/a><\/li><li><a href=\"\/hc\/\">Historical Collections<\/a><\/li><li><a href=\"\/go\/ejournals.html\">Journals / E-Journals<\/a><\/li><li><a href=\"\/guides\/\">Research Guides<\/a><\/li><li><a href=\"\/working_papers.html\">Working Papers<\/a><\/li><li class=\"boc\"><a href=\"\/catalog\/\"><img src=\"\/images\/H-hollis.gif\" alt=\"Hollis Catalog\" class=\"rollover\"><\/a><\/li><\/ul><\/div>');
	document.write('<div><img src=\"\/images\/front\/rotating\/' + pn + '\/photoR.jpg\" width=\"480\" height=\"252\" border=\"0\" alt=\"' +homephoto_alt[pn] + '\"><\/div>');
}

/* ***************************************************************************************

   HC HOME ROTATE CODE

*************************************************************************************** */

// definition and function to write random images to the home page
var hcurl = new Array(20);
var hctext = new Array(20);
var hcalt = new Array(20);
// Enter the total number of images for the home page here.
// Make sure there are at least this many images and alt tags in the array.
var hctotalsideprofiles = 3;

// urls and text for each graphic

hcurl[1]="/hc/popups/homeimage1.html";
hctext[1]="The Harvard Business School Class of 1910";
hcalt[1]="The Harvard Business School Class of 1910";

hcurl[2]="/hc/popups/homeimage2.html";
hctext[2]="French Statistical Broadside";
hcalt[2]="French Statistical Broadside";

hcurl[3]="/hc/popups/homeimage3.html";
hctext[3]="Samuel Stearns account book";
hcalt[3]="Samuel Stearns account book";


var hcpn = 1 
hcpn = Math.round(Math.random() * (hctotalsideprofiles - 1)) +1;
// Function to write the rotating code  on the page.

function hcnext(){
	img = document.getElementById('hcrotating');
	a = document.getElementById('hcwhatisthis');
	pn = pn + 1;
	if (pn > hctotalsideprofiles) {pn = 1;}
	img.src = '/images/hc/front/rotating/' + pn + '/picture.gif';
	a.href = hcurl[pn];
	return false;
}

function hcprev(){
	img = document.getElementById('hcrotating');
	a = document.getElementById('hcwhatisthis');
	pn = pn - 1;
	if (pn < 1) {pn = hctotalsideprofiles;}
	img.src = '/images/hc/front/rotating/' + pn + '/picture.gif';
	a.href = hcurl[pn];
	return false;
}


function hc_write_randompicture() {
   // picture
   document.write('<img id="hcrotating" src="/images/hc/front/rotating/' + hcpn + '/picture.gif" width="275" height="147" border="0" alt="' + hcalt[pn]+ '" />');
   // buttons
   document.write('<div class=\"rotatecontrols\"><a href="#" onclick="return hcprev()"><img src="/images/hc-viewprevious.gif " width="93" height="16" border="0" alt="View Previous"></a><a href="' + hcurl[pn] +'" onclick="return hcpopup(this.href);" id=\"hcwhatisthis\"><img src="/images/hc-whatisit.gif " width="87" height="16" border="0" alt="What is it?" \></a><a href="#" onclick="return hcnext()"><img src="/images/hc-viewnext.gif" width="93" height="16" border="0" alt="View Next " \></a></div>');
}