//
// core.js - Sitewide JavaScript 
//
// $Author: jgriffith $
// $Date: 2008/04/03 20:28:53 $
// $Revision: 1.5 $
//

(function($){

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

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

    quicklinks: function() {
        $("#toggleQL").click(function(){ $("#quicklinks").toggleClass("open");return false;});
    },
    
    validated: function() {
        var $forms = $("form.validated");
        if ($forms.size() > 0) {
           $.ajax({
              type: 'GET',
              url: '/js/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").length>0) {
                if($("#siteindex-slider").length==0) {
                   $("#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 += "&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() {};
}



