/*


Dynamic Application of Functions to DOM
*/
var _debugMode = false;
document.observe('dom:loaded', init);


function init () {
  
  /*
  
  SlideShow instantiation
  */
  if ((window['SlideShow'] != undefined) && $('feature')) {
    var feature = $('feature');
    if (feature.select('.slide').length > 1)
      var homePageSlideShow = new SlideShow(feature, { interval: 8 } );
  }

  // table js
  $$('table.dataTable').each(function(table){
    // highlight table rows on hover
    table
      .observe('mouseover', function(e){
        var t = $(e.target);
        if (t.up('tr') && t.up('tr') != table.select('tr').first())
          t.up('tr').addClassName('hover');
      })
      .observe('mouseout', function(e){
        var t = $(e.target);
        if (t.up('tr') && t.up('tr') != table.select('tr').first())
          t.up('tr').removeClassName('hover');
      });
    // apply alt class to even tr's
    table.select('tr:nth-child(even)').invoke('addClassName', 'alt');
    
    // appy last css class to the end td's
    table.select('tr').each(function(tr){
      Try.these(function(){
        if (tr.select('td').last()) tr.select('td').last().addClassName('last');
      });
    });
  });
  // end table js
  
  
  
  // manually insert the rss line on the 2nd home news item
  when('newsHome', function(div){
    div.select('div.newsHomeColumn p').last().replace(
      '<p style="padding-top: 1em;"><strong><a href="http://feeds.feedburner.com/CentralCreditUnionOfFlorida">Subscribe to Our News Feed</a> <a href="http://feeds.feedburner.com/CentralCreditUnionOfFlorida" id="HomeNewsFeedIcon"><img src="/images/feed-icon-16x16.png" alt="RSS Feed Icon" /></a></strong><br /><br /></p>'
    );
  });

  // manually add a class name for IE
  if (Prototype.Browser.IE){
    $$($w('h1 h2 h3 h4 h5 h6').map(function(h){
      return '.contentSectionRight > a:first-child + #{h}, .contentSectionRight #{h}:first-child'.interpolate({ h: h });
    }).join(',')).each(function(el){
      el.addClassName('firstChild');
    });
  }
  
  
  // replace spaces in nav foot with nbsp's
  $$('#navFoot a').each(function(a){ a.update(a.innerHTML.gsub(' ', '&nbsp;')); });
  
  // adjusting the last trailing location
  if ($$('.location').length % 2 != 0){
    $$('.location').last().setStyle({ marginLeft: '270px' });
  }
}
// end init

Event.observe(window, 'load', addPrintLogo);

function addPrintLogo () {
  if ($('head'))
    $('head').insert('<img src="/images/ccufl-logo-print.png" alt="CCUFL" id="printLogo" />');
}

/* force the height of the news area on the home page so that the stroke extends to the full length of the page */
Event.observe(window, 'load', function(e){
  if ($(document.body).hasClassName('home') && $('columnRight') && $('newsHomeStroke') && $('feature')){
    if ($('columnRight').getHeight() > $('newsHomeStroke').getHeight() + $('feature').getHeight()){
      $('newsHomeStroke').setStyle({
        height: $('columnRight').getHeight() - $('feature').getHeight() + 'px'
      });
    }
  }
});

/*

Instantiating the Google Maps object
*/
if (window['AjaxGoogleMaps'] != undefined) {
  var gm = new AjaxGoogleMaps('/coordinates', 'columnInterior', {
    height: 300, width: 770, zoom: 9,
    embedMethod: ['insert', 'top'],
    infoWindowTemplate: new Template(
      '<div class="googleMapsPopup"><strong>#{name}</strong>#{address}<a href="#{google_maps_link}" target="_blank">View Google Maps</a></div>'
    )
  });
}





/*

Powers the Navigation for the site, using the class more for an organized set of functions more than anything else
*/
var Nav = Class.create({
  
  initialize: function(navId, subNavClassName){
    this.navId = navId;
    this.subNavClassName = subNavClassName;
    document.observe('dom:loaded', this.domLoaded.bind(this));
  },
  
  domLoaded: function(){
    this.setupNavPrimary();
    this.setupNavTop();
    this.setupNavSub();
  },
  
  setupNavPrimary: function(){
    this.ul = $(this.navId);
    if (!this.ul) return;
    var ul = this.ul;
    var lis = ul.select('li');
    this.lis = lis;
    this.links = ul.select('a');
    
    // establish 'active' property
    this.establishActiveProperty(lis);
    
    this.getActiveLinkName(this.links);

    ul.observe('mouseover', this.hover.bind(this)).observe('mouseout',  this.hoverOut.bind(this)).observe('click', this.fakeAnchorClick.bind(this));
    
    // add arrows to li's
    lis.each(function(li, i){
      li.insert('<img src="/images/nav-arrow.png" alt="" />');
      li.down('img').setStyle({
        left: (li.getWidth() / 2) - 10 + 'px'
      });
    });
  },

  hover: function(e) {
    var t = $(e.target)
    if (t.match('li')) var highlightT = t;
    else if (t.match('a')) var highlightT = t.up();
    if (highlightT) {
      this.lis.invoke('removeClassName', 'hover');
      highlightT.addClassName('hover');
      this.showAssociatedNavSub(highlightT);
    }
  },

  hoverOut: function(e) {
    var t = $(e.target);
    if (t.match('li') && this.notImg(e)) var hideT = t;
    else if (t.match('a') && this.notImg(e)) var hideT = t.up();
    else if (t.match('img')) var hideT = t.up('li');
    if (hideT) {
      this.tryToRevertToActive(e);
      hideT.removeClassName('hover');
    }
  },

  fakeAnchorClick: function (e) {
    var t = $(e.target);
    if (t.match('li') && t.down('a'))
      window.location = t.down('a').href;
  },

  notImg: function (e) {
    if ($(e.relatedTarget) && Object.isFunction($(e.relatedTarget).match)) {
      // if not img or is an image that is not related
      if (!$(e.relatedTarget).match('img')
        || !$(e.target).siblings().any(function(s){return (s == e.relatedTarget);})
      ) {
        return true;
      } else { return false; }
    } else { return false; }
  },

  establishActiveProperty: function(lis){
    for (var i = lis.length - 1; i >= 0; i--) {
      lis[i]._active = lis[i].hasClassName('active');
    };
  },

  getAssociatedNavSub: function(t){
    var name = t.down('a').innerHTML.strip();
    var navSubItem = $$('.navSubItem').find(function(item, i){
      return (item.down('h3').innerHTML.strip() == name);
    });
    return navSubItem || false;
  },

  showAssociatedNavSub: function(t){
    // cl('showAssociatedNavSub');
    var associatedNavSub = this.getAssociatedNavSub(t);
    if (associatedNavSub) {
      $$('#navPrimary li.active', '#navTop li.active').invoke('removeClassName', 'active');
      $$('.navSubItem').invoke('hide');
      associatedNavSub.show();
      t.addClassName('active');
    }
  },

  tryToRevertToActive: function(e){
    // cl('tryToRevertToActive');
    // if there is an active link
    if (!this.activeLink && !this.activeNavSub) cl('there is NO an active link');
    if (!this.activeLink && !this.activeNavSub) return;
    var t = $(e.target);
    var rt = $(e.relatedTarget);
    var ct = $(e.currentTarget);
    var navSubShell = $('navSubShell');
    // if mousing out of the shell, or anything inside of it
    if (t == navSubShell || t.descendantOf(navSubShell)) {
      // and not mousing over anything inside of the shell
      if (rt) {
        if (!rt.descendantOf(navSubShell) && !rt.descendantOf(this.ul) && rt != navSubShell) {
          cl('if mousing out of the shell, or anything inside of it AND not mousing over anything inside of the shell');
          this.revertToActive();
        }
      }
    }
    // if mouseout on li and related target is not a child of div
    // for when you mouseout from the top of the navprimary
    else if (t.match('li') || t.match('a') || t.match('li img')) {
      if (!rt.descendantOf(navSubShell) && rt != navSubShell && !rt.descendantOf(this.ul)) {
        cl('if mouseout on li and related target is not a child of div');
        this.revertToActive();
      }
    }
  },

  revertToActive: function(){
    // cl('revert to active');
    // if the activeLink isn't already active
    if (this.activeLink && this.activeLink.up('li').hasClassName('active')) return;
    [this.lis, this.navTopLis].flatten().invoke('removeClassName', 'hover').invoke('removeClassName', 'active');
    
    if (this.activeLink) {
      this.activeLink.up('li').addClassName('hover').addClassName('active');
    }
    this.showActiveNavSubItem();
  },

  getActiveLinkName: function(links){
    if (links.any(function(link, i){ return link.up('li')._active; })) {
      this.activeLink = links.find(function(link, i){ return link.up('li')._active; });
      this.activeLinkName = this.activeLink.innerHTML.strip();
    }
    // if page has navsub but not in a link
    else if (this.windowLocationHasNavSub()) {
      // show NavSub
      this.activeLinkName = this.windowLocationHasNavSub().gsub('-', ' ');
      this.activeNavSub = this.activeLinkName;
      // cl(this.activeLinkName);
    }
  },
  
  windowLocationHasNavSub: function(){
    // returns window location or false;
    var loc = new String(window.location).split('/');
    loc = loc.slice(3, loc.length);
    if (loc.length > 0) loc = loc[0];
    loc = loc.split('#')[0]
    if (loc) {
      cl(loc);
      return loc;
    } else {
      return false;
    }
  },

  setupNavSub: function(){
    this.navSubShell = $('navSubShell');
    if (this.navSubShell)
      this.navSubShell.observe('mouseout', this.tryToRevertToActive.bind(this));
    
    this.tweakNavSubPadding();
    this.showActiveNavSubItem();
  },

  showActiveNavSubItem: function(){
    // hide all but the intended navSubItem
    this.navSubItems = $$('.navSubItem').invoke('hide');
    if (this.navSubItems.length > 0) {
      var activeNavSubItem = this.navSubItems.find(function(item, i){
        return (this.activeLinkName.toLowerCase() == item.down('h3').innerHTML.strip().toLowerCase())
      }.bind(this));
      if (activeNavSubItem) activeNavSubItem.show();
    }
  },

  tweakNavSubPadding: function(){
    // add 'minor' css class name to navSub when it contains few links
    this.navSubs = $$('.navSub').each(function(ul){
      var lis = ul.select('li');
      if (lis.length <= 4) {
        ul.addClassName('oneRow');
      }
      if (lis.length > 4 && lis.length <= 8) {
        ul.addClassName('twoRows');
      }
      if (lis.length > 8 && lis.length <= 12) {
        ul.addClassName('threeRows');
      }
      // add custom 'addPadding' css class to li's w/o links
      lis.each(function(li, i){
        if (!li.down('a')) li.addClassName('addPadding');
      });
    });
  },

  setupNavTop: function(){
    this.navTop = $('navTop');
    if (!this.navTop) return;
    this.navTopLis = this.navTop.select('li');
    this.navTopLinks = this.navTop.select('a');
    this.establishActiveProperty(this.navTopLis);
    this.getActiveLinkName(this.navTopLinks);
  }

});

var nav = new Nav('navPrimary', 'navSub');



/*


From functions-lib.js
*/
/* Utility Functions */
function cl(str){
  if(_debugMode) Try.these(
    function(){
      console.log(str);
    },
    function(){
      nitobi.Debug.log(str);
    }
  );
}

function t(f) {
  Try.these(f);
}

/*
from: http://mislav.caboo.se/js/when-available-in-prototype/
When object is available, do function fn.
*/
function when(obj, fn) {
  if (Object.isString(obj)) obj = /^[\w-]+$/.test(obj) ? $(obj) : $(document.body).down(obj)
  if (Object.isArray(obj) && !obj.length) return
  if (obj) fn(obj)
}


Element.addMethods({
  /*


  Makes 32 bit PNG's transparency work in Internet Explorer 6

    * Dependent on "Prototype JavaScript framework (1.6.0)":http://www.prototypejs.org/2007/8/15/prototype-1-6-0-release-candidate
    * Works on *img elements* and on *background images of elements*
    * PNG's can be used as backgrounds. However, *image tiling will not work*
    * *Safe to use* - You don't have to make an exception or write separate code for IE6
    * Background PNG's used in :hover's might need another application of the method


  Example Usages:

   $('yourPNG').pngHack();
   $$('div#fixMe', 'img#andMe', 'img.andUsTo').invoke('pngHack');

  */
  pngHack: function(el){
    var el = $(el);
    if (!Prototype.Browser.IE) return el;
    var gif = '/images/s.gif';
    if ((el.match('img')) && (el.src.include('png'))){
      var alphaImgSrc  = el.src;
      var sizingMethod = 'scale';
      el.src = gif;
    } else if (el.getStyle('backgroundImage').include('png')){
      var bgc = el.getStyle('backgroundColor') || '';
      var alphaImgSrc = el.getStyle('backgroundImage').gsub(/url\(|\)|'|"/, '');
      var sizingMethod = 'crop';
      el.setStyle({ background: [bgc, ' url(', gif, ') no-repeat'].join('') });
    } else {
      return el;
    }
    el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="#{al}",sizingMethod="#{sz}")'.interpolate({ al: alphaImgSrc, sz: sizingMethod });
    return el;
  },
  /*
    
    centers the element vertically and horizontally within it's parent element
      requires positioning of the element, and dimensions
  */
  center: function(el){
    var el = $(el);
    var parent = el.up();
    return el.setStyle({
      left: (parent.getWidth()  - el.getWidth())  / 2 + 'px',
      top:  (parent.getHeight() - el.getHeight()) / 2 + 'px'
    });
  },
  fakeMinHeight: function(el){
    var el = $(el);
    if (!Prototype.Browser.IE) return el;
    if (Number(el.getStyle('height').gsub('px', '')) < Number(el.getStyle('minHeight').gsub('px', ''))) {
      el.setStyle({ height: el.getStyle('minHeight') });
    }
    return el;
  }
});

/*


Equalize the heights of columns
*/
Object.extend(Array.prototype, {
  equalize: function(){
    if (this.any(function(el){
      return Object.isElement(el)
    }))
      this.invoke('setStyle', {
        height: this.map(function(el){
          return el.getHeight()
        }).max() + 'px'
      });
    return this;
  }
});


/*


Adds the ability to random a number
*/
Object.extend(Number.prototype, {
  rand: function(){
    return Math.ceil(this * Math.random());
  }
});
