//
// core.js - Sitewide JavaScript 
//
// $Author: jgriffith $
// $Date: 2008/05/12 17:11:55 $
// $Revision: 1.6 $
//

(function($){

// don't run this if it has been imported twice
if (window.Core) return; 

var Core = {
    init: function() {
       Core.quicklinks();
       Core.admin();
       Core.SiteIndex.init();
       Core.Rollover.init();
       Core.validated();
    },

    options: {
       site: 'unspecifiedsite',
       plugins: ''
    },

    settings: function(opt) {
      for (var v in opt) {
        Core.options[v] = opt[v];
      }
    },
    
    quicklinks: function() {
        Core.quicklinks_status = 'closed';
        Core.quicklinks_interval = null;
        function check_status() {
             if (Core.quicklinks_status == 'closed') {
                $("#quicklinks").removeClass("open");
             }
             if (Core.quicklinks_interval) window.clearInterval(Core.quicklinks_interval);
        }
        function ql_open() {
             Core.quicklinks_status = 'open';
             $("#quicklinks").addClass("open");
             if (Core.quicklinks_interval) window.clearInterval(Core.quicklinks_interval);
             return false;
        }
        function ql_close() {
             Core.quicklinks_status = 'closed';
             //window.setTimeout(check_status,1000);
             Core.quicklinks_interval=self.setInterval(check_status,1000);
             return false;
        }
        
        function ql_toggle() {
             $("#quicklinks").toggleClass("open");
        }
        
        $("#toggleQL").click(ql_toggle);
        $("#quicklinkslist").hover(ql_open,ql_close);
        $("#toggleQL").hover(function() {
                               Core.quicklinks_status = 'open';
                             },
                             ql_close);
    },

    admin: function() {
       //load any webstage admin tools
        if (document.getElementById('edit_button')) {
           $.ajax({
              type: 'GET',
              url: '/admin/shared/js/wps.js',
              cache: true,
              success: function() {
                  Admin.init();
              },
              dataType: 'script',
              data: null
              });
        }
    },
    
    validated: function() {
        if (!Core.options.plugins) { return }
        var $forms = $("form.validated");
        if ($forms.size() > 0) {
           $.ajax({
              type: 'GET',
              url: Core.options.plugins+'/jquery.validate.js',
              cache: true,
              success: function() {
                 $(document).trigger('validator.loaded');
                 $forms.each(function(i,form) {
                    $(form).validate();
                 });
              },
              dataType: 'script',
              data: null
              });
        }
    }
    
}

$(document).ready(function(){Core.init()});


Core.SiteIndex = {
    init: function() {
        $("#toggleSI").click(function(){ 
            if ($("#toggleSI.openSI").size()>0) {
                if($("#siteindex-slider").size()<1) {
                   $("#siteindex-location").append('<div id="siteindex-slider" style="height:'+Core.SiteIndex.height+'px"></div>');
                   $("#siteindex-slider").hide();
                   $("#siteindex-slider").append('<iframe src="/siteindex/siteindex.html?'+Core.SiteIndex.focus+'" id="siteindex-iframe" name="siteindex-iframe" scrolling="no" frameborder="0" style="border-width:0pt;height:'+Core.SiteIndex.height+'px;width:960px;margin: 0 auto;"></iframe><div class="clear"></div>');
                   $("#siteindex-iframe").load(function(){
                      var iframe = window.frames['siteindex-iframe']
                      try {
                         var ifdoc = iframe.document || iframe.contentDocument || iframe.contentWindow && iframe.contentWindow.document || null; 
                         if (!ifdoc.getElementById("siteindex_content")) {
                            // if we can't find the siteindex file
                            document.location = "http://www.hbs.edu/about/siteindex.html";
                         }
                         $("#closeSI",ifdoc).click(function(){
                             Core.SiteIndex.close();
                             return false;
                         });
                      } catch (e) {
                         
                      }
                   });
                } 
                Core.SiteIndex.open();
            } else {
                Core.SiteIndex.close();
            }
            return false;
        });
    },

    open: function() {
        $("#siteindex-slider").slideDown(1000)
        $(".siteindex-fade").fadeTo(1000,.3);
        $("#toggleSI").removeClass("openSI").addClass("closeSI")
    },

    close: function() {
        $("#siteindex-slider").slideUp(1000);
        $(".siteindex-fade").fadeTo(1000,1);
        $("#toggleSI").removeClass("closeSI").addClass("openSI")
    },
    setfocus: function(config) {
       for (var i=0;i<config.length;i++) {
          var rx = config[i][0];
          var focus = config[i][1];
          if (RegExp(rx).test(document.location.href)) {Core.SiteIndex.focus = focus; return}
       }
       return;
    },
    setheight: function(h) {Core.SiteIndex.height = h},
    height: 345,
    focus: ''
}



/*
 *  Finds all img.rollover and enables mouseover rollovers
 */

Core.Rollover = {
    init: function() {
       $("img.rollover").each(function (i) {
                 var img = $(this);
                 var newsrc = img.attr('src');
                 newsrc = newsrc.replace(/\.(gif|png|jpg)$/,'-over.$1');
                 Core.Rollover.imgs[i] = new Image(1,1);
                 Core.Rollover.imgs[i].src = newsrc;
                 img.mouseover(function(){
                      try {
                         if (window.Core && window.Core.Rollover && window.Core.Rollover.loaded) {
                            if (this.className.indexOf('rollover') > -1 && this.src.indexOf('-over') == -1 ) {
                               this.src = this.src.replace(/\.(gif|jpg|png)/,'-over.$1');
                            }     
                         }
                      } catch(e) {}
                 })
                 img.mouseout(function(){
                      try {
                         if (window.Core && window.Core.Rollover && window.Core.Rollover.loaded) {
                            if (this.src.indexOf('-over') != -1 ) {
                               this.src = this.src.replace('-over','');
                            }     
                         }   
                      } catch(e) {}
                 })
       });
       Core.Rollover.loaded = 1;
    },
    imgs: new Array(),
    loaded: 0
}

Core.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '; path=/';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        var uriencoded = options.noencode ? value : encodeURIComponent(value);
        
        // spaces commas and semicolons are not valid cookie values
        uriencoded = uriencoded.replace(' ','%20');
        uriencoded = uriencoded.replace(';','%3B');
        uriencoded = uriencoded.replace(',','%2C');
        document.cookie = [name, '=',uriencoded , expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

Core.log = {
    email: false,
    messageSent: false,
    error: function(msg,url,ln) {
       if (msg.message) {  //if msg is an exception object
          url = msg.fileName;
          ln = msg.lineNumber;
          msg = msg.message;
       }

       Core.log.trace('died...');

       var strValues = "msg=" + escape(msg);
       strValues += "&type=" + 'error';       
       strValues += "&line=" + ln;
       strValues += "&site=" + Core.options.site;
       strValues += "&queryString=" + escape(location.search);
       strValues += "&url=" + escape(document.location);
       strValues += "&httpref=" + escape(document.referrer);
       strValues += "&ua=" + escape(navigator.userAgent);
       strValues += "&trace=" + escape(Core.log.tracestr);

       if (!Core.log.email) return false;    
       if (Core.log.messageSent) return false;

       var img = new Image();
       img.src = "http://www.hbs.edu/cgi-bin/jslog?"+strValues;
       Core.log.messageSent = true;
       
       return false;  // don't completely trap the error
   },

   tracestr: "",
   trace: function (str) {
       Core.log.tracestr += str + "\n";
   }

};


jQuery.cookie = Core.cookie;
// an uncached js load
jQuery.loadJS = function(url,fn) {
   $.ajax({
        type: 'GET',
        url: url,
        cache: true,
        success: fn,
        dataType: 'script',
        data: null
   });
}

window.Core = Core;
window.onerror = Core.log.error;

})(jQuery);


/* ----------------------------------------------------
 *
 * for browsers that don't support logging
 *
 * ----------------------------------------------------
 */
 
if(!("console" in window) || !("firebug" in console)) {
   var names = ["log", "debug", "info", "warn", "error", "assert","dir", "dirxml", "group"
                , "groupEnd", "time", "timeEnd", "count", "trace","profile", "profileEnd"];
   window.console = {};
   for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}

/* ----------------------------------------------------
 *
 * Add support for jQuery Color Animations
 *
 * ----------------------------------------------------
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);


/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Version: 1.0, 31.05.2007
 * Changelog:
 * 	31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 */

(function(jQuery) {

jQuery.noConflict();

jQuery.fn.pngFix = function() {

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		jQuery(this).find("img[@src$=.png]").each(function() {

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'image\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);
		});

	}

};

})(jQuery);





if (window.location.search.match(/[\?&]__profile__\b/)) {

           $.ajax({
              type: 'GET',
              url: 'http://www.hbs.edu/js/plugins/jquery.profile.js',
              cache: true,
              success: function() {
                 jQuery.profile();setTimeout(function(){jQuery.profile.done()},2000);
              },
              dataType: 'script',
              data: null
              });

    //document.write('<script type="text/javascript" src=""></script>');
    //document.write('<script type="text/javascript"></script>');
}
