/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};

/* DumbCrossfade - http://storage.sebringcreative.com.s3.amazonaws.com/jquery/dumbCrossFade.htm */
/* 2010 Hubsoft.com && SebringCreative.com (written by Jason Sebring, mail@jasonsebring.com) - Dual licensed under the MIT and GPL licenses. */
(function($){$.fn.dumbCrossFade=function(settings){var publicAccessorLabel='dumbCrossFade.publicAccessor';var configLabel='dumbCrossFade.config';if(typeof(this.data(publicAccessorLabel))!=='undefined'&&this.data(publicAccessorLabel)!==null){var pa=this.data(publicAccessorLabel);var cg=this.data(configLabel);var args=Array.prototype.slice.apply(arguments);if(args.length>0){if(typeof(args[0])==='object'){if(settings)$.extend(cg,settings);var args=Array.prototype.slice.apply(arguments);if(args.length>1){args=args.slice(1,args.length);}else{pa.start();return this;}}if(arguments.length===1){pa[arguments[0]]();}else if(arguments.length>1){var args=Array.prototype.slice.apply(arguments);args=args.slice(1,args.length);pa[arguments[0]].apply(this,args);}}return this;}var config={'slideType':'slidehorizontal','index':0,'showTime':5000,'transitionTime':1000,'doHoverPause':true,'maxZIndex':100,'slideChange':null,'direction':'forward','fadeInOut':false},timeOut=null,itemArray=[],blockAnimation=false,lastIndexRequest=-1,$self=this
$window=$(window),$body=$('body');if(settings)$.extend(config,settings);function cancelSlideShow(){if(timeOut!==null){window.clearTimeout(timeOut);timeOut=null;}}function doSlideShowNow(){if(blockAnimation){if(arguments.length>0){lastIndexRequest=arguments[0];}return;}var currentIndex=config.index;var nextIndex=(arguments.length>0)?arguments[0]:(config.index>=itemArray.length-1)?0:config.index+1;if(config.direction==='backward'){if(currentIndex===0){nextIndex=itemArray.length-1;}else{nextIndex=currentIndex-1;}}if(currentIndex==nextIndex){return;}var $f=itemArray[currentIndex].show(),$n=itemArray[nextIndex];blockAnimation=true;doneF=function(){$f.hide();if(config.fadeInOut){$f.css({'opacity':'1.0'});$n.css({'opacity':'1.0'});}blockAnimation=false;if(lastIndexRequest!=-1){doSlideShowNow(lastIndexRequest);lastIndexRequest=-1;}};$f.css('z-index',(config.maxZIndex-1)+'');$n.css('z-index',config.maxZIndex+'');switch(config.slideType){case'slidehorizontal':var pos=$f.position(),width=$f.width(),adjustX='-='+width;if(config.direction==='forward'){$n.css({'left':(parseInt(pos.left)+width)+'px'});}else{$n.css({'left':(parseInt(pos.left)-width)+'px'});adjustX='+='+width;}if(config.fadeInOut){$n.css({'opacity':'0','display':'block'});$f.animate({'left':adjustX,'opacity':'0'},config.transitionTime,'swing');$n.animate({'left':adjustX,'opacity':'1.0'},config.transitionTime,'swing',doneF);}else{$n.show();$f.animate({'left':adjustX},config.transitionTime,'swing');$n.animate({'left':adjustX},config.transitionTime,'swing',doneF);}break;case'slidevertical':var pos=$f.position(),height=$f.height(),adjustY='-='+height;if(config.direction==='forward'){$n.css({'top':(parseInt(pos.top)+height)+'px','display':'block'});}else{$n.css({'top':(parseInt(pos.top)-height)+'px','display':'block'});adjustY='+='+height;}if(config.fadeInOut){$n.css({'opacity':'0','display':'block'});$f.animate({'top':adjustY,'opacity':'0'},config.transitionTime,'swing');$n.animate({'top':adjustY,'opacity':'1.0'},config.transitionTime,'swing',doneF);}else{$n.show();$f.animate({'top':adjustY},config.transitionTime);$n.animate({'top':adjustY},config.transitionTime,doneF);}break;case'fade':$n.fadeIn(config.transitionTime,doneF);break;}if(config.slideChange!==null){config.slideChange(nextIndex);}config.index=nextIndex;}function doSlideShow(){cancelSlideShow();timeOut=window.setTimeout(function(){doSlideShowNow();doSlideShow();},config.showTime);}$self.each(function(){(itemArray.length===config.index)?$(this).show():$(this).hide();if(itemArray.length===0){if(config.doHoverPause){$(this).parent().hover(function(){cancelSlideShow();},function(){cancelSlideShow();doSlideShow();});}}itemArray[itemArray.length]=$(this);});var publicAccessor={'jump':function(index){cancelSlideShow();doSlideShowNow(index);return publicAccessor;},'start':function(){$self.children().hide();itemArray[config.index].show();config.direction='forward';doSlideShow();},'stop':function(){cancelSlideShow();},'next':function(){config.direction='forward';doSlideShowNow();},'previous':function(){config.direction='backward';doSlideShowNow();}};this.data(publicAccessorLabel,publicAccessor);this.data(configLabel,config);doSlideShow();return this;};})(jQuery);

// modified to remove 'cancelSlideShow() from 'next' and 'previouw' instance methods

var Vimeo = {
  loadThumb: function(context, videoID) {
    var url = "http://vimeo.com/api/v2/video/" + videoID + ".json?callback=Vimeo.showThumb";
    $('img', context).before('<script type="text/javascript" src="'+ url +'"></script>');
  },

  showThumb: function(data) {
    var img = $('div[data-video-id=' + data[0].id + '] img');
    img.attr('src', data[0].thumbnail_medium);
  }
};

/**********************************************************************************************

  CSS on Sails Framework
  Title: Site Name
  Author: XHTMLized (http://www.xhtmlized.com/)
  Date: March 2010

***********************************************************************************************/

var Site = {
  Common: {
    tabsInit: function(e) {
      if (typeof $.fn.tabs != 'undefined') {
        $("#audience").tabs({
          selected: -1,
          collapsible: true,
          fx: [{opacity:'toggle', duration:'fast'}, {opacity:'toggle', duration:'fast'}] 
        });
        $(".by-island").tabs();
        $(".energy-data-box").tabs();
      };
    },
    cufonize: function(e) {
      if (typeof Cufon != 'undefined') {
        Cufon.set('fontFamily', 'kievit').replace('.page-title p, .slide .subtitle, .site-name a span + span');
        Cufon.set('fontFamily', 'lubalin').replace('.page-title h2, .slide h2, .energy-hero-name');
        Cufon.set('fontFamily', 'lubalin').replace('.highlight-box h3');
        Cufon.set('fontFamily', 'lubalin').replace('h2.month, #navigation2 ul li a', { hover: true });
      }
    },
  addNavClasses: function(e){
    $("#yahoo_menu_bar ul:first > li:first").addClass('nav-left');
    $("#yahoo_menu_bar ul:first > li:last").addClass('nav-right');
  }
  }
};

$(document).ready(function() {
  // add last-child for ie7
  if ($('html.ie7, html.ie8').length) {
    $('#yahoo_menu_bar > .bd > ul > li:last-child').addClass('last-child');
  }

  // handle drop down menu position
  $('#yahoo_menu_bar > .bd > ul:first > li').hover(function() {
    $(this).addClass('hover');
    var menu = $(this).find('> .yuimenu > .bd > ul'),
        // get the width of the ancestor menu
        ancestorMenuWidth = $('#yahoo_menu_bar').width(),
        leeway = 10,
        // move the menu to the same position at its parent *from the left*
        ancestorPosition = $('#yahoo_menu_bar').offset().left,
        parentPosition = menu.parent().parent().parent().offset().left - ancestorPosition,
        // get the width of the menu
        menuWidth = menu.width();

    menu.css({ left: 0 + 'px', width: menuWidth });

    // now move the menu
    menu.css({ left: parentPosition + 'px' });

    // if the width of the sub menu + the position of its parent is greater than (the width of the ancestor menu - leeway),
    // subtract its position from the left by the difference of (the sub-menu width + parent position) - (ancestory menu width - leeway)
    var windowWidth = $(window).width();
    if ((menuWidth + parentPosition + ancestorPosition) > windowWidth) {
      menu.css({ right: leeway + 'px', left: '' });
    }
    menu.css({ display: 'block' });
  }, function() {
    $(this).removeClass('hover');
    var menu = $(this).find('> .yuimenu > .bd > ul');
    menu.css({ left: null, display: 'none' });
  });
});

// handle text resizing
function resizeText() {
    var body = $('body');
    var curSize = 'normal', newSize = '';

    if (body.hasClass('text-x-large'))
        curSize = 'x-large';
    else if (body.hasClass('text-large'))
        curSize = 'large';

  newSize = 'large';
    switch(curSize) {
        case 'normal':
            newSize = 'large';
            break;
        case 'large':
            newSize = 'x-large';
            break;
        case 'x-large':
            newSize = 'normal';
            break;
    }

    // save text size in cookie
  $.cookie('textSize', newSize, { expires: 365, path: '/' });

  // swap classes
    body.removeClass('text-' + curSize);
    body.addClass('text-' + newSize);
}

var CalcConfig = {
  longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  fields: {
    'interestRate':     'calc-interest-rate',
    'loanAmount':       'calc-loan-amount',
    'loanTerm':         'calc-loan-term',
    'monthlyPayment':   'calc-monthly-payment',
    'totalPayment':     'calc-total-payment',
    'payoffDate':       'calc-payoff-date',
    'numberOfPayments': 'calc-number-of-payments',
    'startMonth':       'calc-first-payment-date-month',
    'startYear':        'calc-first-payment-date-year'
  },
  calc: function() {
    MortgageCalculator.calculatePMT(this.fields);
  }
};

var MortgageCalculator = {
  PMT: function(i, n, p) {
    var res = 0;
    if (i == 0 && n == 0) {
      return res;
    }
    if (i == 0) {
      res = -p / n;
    } else {
      res = i * p * Math.pow((1 + i), n) / (1 - Math.pow((1 + i), n));
    }
    return res;
  },
  calculatePMT: function(fields) {
    var i = parseFloat($('#' + CalcConfig.fields.interestRate).val().replace(/[^0-9.]/g,''));
    i = isNaN(i) ? 0 : i / 1200;
    var n = parseFloat($('#' + CalcConfig.fields.loanTerm).val().replace(/[^0-9.]/g,''));
    n = isNaN(n) ? 0 : n  * 12;
    var p = parseFloat($('#' + CalcConfig.fields.loanAmount).val().replace(/[^0-9.]/g,''));
    var pmt = this.PMT(i, n, -p);
    if (isNaN(pmt)) {
      pmt = 0;
    }

    var fieldNumberOfPayments = $('#' + CalcConfig.fields.numberOfPayments).html(isNaN(n) ? 0 : n);
    var fieldMonthly = $('#' + CalcConfig.fields.monthlyPayment).html(pmt);
    var fieldTotal = $('#' + CalcConfig.fields.totalPayment).html(isNaN(pmt * n) ? 0 : pmt * n);

    if (jQuery.formatCurrency) {
      fieldMonthly.formatCurrency();
      fieldTotal.formatCurrency();
    }

    this.updateDate(n, fields);
  },
  updateDate: function(n, fields) {
    var month = parseInt($('#' + CalcConfig.fields.startMonth + ' option:selected').val()) - 1;
    var year = parseInt($('#' + CalcConfig.fields.startYear + ' option:selected').val());

    // future year
    if (n > 12) {
      year += parseInt(n/12);
    }

    // future month
    if ((n % 12) + month > 12) {
      month = ((n % 12) + month) % 12;
    }

    var date = new Date();
    date.setFullYear(year, month, 1);
    $('#' + CalcConfig.fields.payoffDate).html(CalcConfig.longMonths[date.getMonth()] + ' ' + date.getFullYear());
  }
};

// if we're viewing a page with staff profiles, rebuild the page to make the profiles collapsable
$('.staff-profile').each(function(idx, el) {
  // duplicate the header and prepend it to the existing container
  var header = $(el).find('h4').clone();
  var headerImage = $(el).find('h4 img').detach();
  $(el).find('h4').empty().append(headerImage);
  var content = $(el).html();
  $(el).empty().prepend("<div class=\"header clearfix\"></div>");
  $(el).find('.header').append(header).find('img').attr('style', '');

  // make a new container for the content and stick the existing content in it
  $(el).find('.header').after("<div class=\"content clearfix\"></div>");
  $(el).find('.content').html(content);

  // whenever the header is clicked on, it toggles the content block
  var openClass = 'staff-profile-open';
  $(el).find('.header').toggle(function() {
    $(this).parent().addClass(openClass);
    $(this).parent().find('.content').slideDown();
  }, function() {
    $(this).parent().removeClass(openClass);
    $(this).parent().find('.content').slideUp();
  });
});

// handle anything we deem to be collapsable
$('.collapsable').each(function(idx, el) {
  // duplicate the header and prepend it to the existing container
  var header = $(el).find('h4').clone();
  // var headerImage = $(el).find('h4 img').detach();
  $(el).find('h4').empty();//.append(headerImage);
  var content = $(el).html();
  $(el).empty().prepend("<div class=\"header clearfix\"></div>");
  $(el).find('.header').append(header).find('img').attr('style', '');

  // make a new container for the content and stick the existing content in it
  $(el).find('.header').after("<div class=\"content clearfix\"></div>");
  $(el).find('.content').html(content);

  // whenever the header is clicked on, it toggles the content block
  var openClass = 'collapsable-open';
  $(el).find('.header').toggle(function() {
    $(this).parent().addClass(openClass);
    $(this).parent().find('.content').slideDown();
  }, function() {
    $(this).parent().removeClass(openClass);
    $(this).parent().find('.content').slideUp();
  });
});

// add Google Analytics to any PDF document we come across
$('a[href$=".pdf"]').click(function() {
  _gaq.push(['_trackPageview', $(this).attr('href')]);
});

$(document).ready(function() {
  // load default text size
  if ($.cookie('textSize')) {
    var previous = null;
    values = ['normal', 'large', 'x-large'];
    for(val in values) {
      if ($('body').hasClass(val)) {
        $('body').removeClass(val);
      }
    }
    $('body').addClass('text-' + $.cookie('textSize'));
  }

  // add text resize capabilities
  $('#text-resizer a').click(function(evt) {
    evt.preventDefault();
    resizeText();
  });

  // find the newsletter sign up link. if there are any, grab the form and make it available
  $('.website-contact-form').click(function(evt) {
    var source = this;
    evt.preventDefault();
    // don't load an aready loaded form
    if ($('#newsletter-form-container').length < 1) {
      $(document.body).append('<div id="newsletter-form-container" style="display: none;"></div>');
    } else if ($('#newsletter-form-container').html() !== null) {
      $.fancybox({
        content: $('#newsletter-form-container').html(),
        width: 300,
        height: 220,
        autoDimensions: false
      });
      // showWebsiteContactForm(source);
      return;
    }
    $.ajax({
      url: '/100',
      context: document.body,
      success: function(data) {
        var domFormPath = '#newsletter-form-container .website-contact-form';
        $('#newsletter-form-container').html(data);
        $.fancybox({
          content: data,
          width: 300,
          height: 220,
          autoDimensions: false
        });
      }
    });
  });

  // fix section navs
  var currentSectionParents = $("#section_nav a.currentPage").parents(),
      sectionNavDivIndex = currentSectionParents.index($("#section_nav")),
      rest = currentSectionParents.slice(0, sectionNavDivIndex);

  rest.addClass("currentPath");

  //rest.find('.currentPath:eq(0) > a')
  $('li.currentPath:eq(0) > a').addClass('currentSection');

  $('#section_nav > ul > li:eq(0) > a').wrap('<span class="headSection" />');

  Site.Common.tabsInit();
  Site.Common.cufonize();
  Site.Common.addNavClasses();

  // create the slideshow nav
  $("#slideshow").append("<div id=\"slideshow-nav\">");
  var numSlides = $("#slideshow .slide").length;
  for (var i = 0; i < numSlides; i++) {
    $("#slideshow-nav").append('<a id="slide-' + i + '" href="#">' + (i + 1) + "</a>");
  }
  var slideshowThumbs = $("#slideshow-nav a");
  for (var i = 0; i < numSlides; i++) {
    $(slideshowThumbs[i]).click(function(evt) {
      evt.preventDefault();
      $('#slideshow .slide').dumbCrossFade('jump', parseInt(evt.target.innerHTML) - 1);
    });
  }
  $(slideshowThumbs[0]).addClass('cur');

  // start the slideshow
  $('#slideshow .slide').dumbCrossFade({
    slideType: 'fade',
    showTime: 6500,
    doHoverPause: false,
    slideChange: function(curIndex) {
      slideshowThumbs.removeClass('cur');
      $(slideshowThumbs[curIndex]).addClass('cur');
    }
  });

  // handle any embded videos we find!
  /**
   * HTML Template
   * -------------
   * <div class="video-embed" data-height="{ height }" data-type="{ youtube|vimeo }" data-video-id="{ videoID }" data-width="{ width }">
   *   <a href="{ URL of video page }" target="_blank"><img src="{ link to placeholder image }" /></a>
   *   <p class="title"><a href="{ link to video page }" target="_blank">{ title }</a></p>
   *   <p class="caption">{ caption }</p>
   * </div>
   */
  $('.video-embed').each(function() {
    var width = $(this).data('width'),
        height = $(this).data('height'),
        videoID = $(this).data('video-id'),
        type = $(this).data('type'),
        title = $('.title', this).text(),
        caption = $('.caption', this).text();

    // videoEmbedThumbs(type, this, videoID);

    $("h3, a", this).click(function(e) {
      e.preventDefault();

      $.fancybox({
        content: '<div class="video-lightbox">' + videoEmbedByType(type, width, height, videoID, title, caption) + '</div>',
        width: width,
        height: height + 100,
        autoDimensions: false,
        padding: 0
      });
    });
  });

  function videoEmbedThumbs(type, context, videoID) {
    switch (type) {
      case 'vimeo':
        Vimeo.loadThumb(context, videoID);
        break;
    }
  }

  function videoEmbedByType(type, width, height, videoID, title, caption, href) {
    var code = '';

    switch(type) {
      case 'hawaiistream':
        code = '<object width="' + width + '" height="' + height + '"><param name="allowScriptAccess" value="always"></param><param name="allowFullScreen" value="true"></param><param name="movie" value="http://www.hawaiistream.com/public/flash/Viewer.swf"></param><param name="FlashVars" value="scheme=embedVod&videoId=' + videoID + '&pwidth=' + width + '&pheight=' + height + '&autoplay=no"></param><embed FlashVars="scheme=embedVod&videoId=' + videoID + '&pwidth=' + width + '&pheight=' + height + '&autoplay=no" src="http://www.hawaiistream.com/public/flash/Viewer.swf" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '" allowScriptAccess="always" allowFullScreen="true" ></embed></object>';
        if (href == null || href == 'undefined') {
          href = 'http://www.hawaiistream.com/video/' + videoID;
        }
        break;
      case 'vimeo':
        code = '<iframe src="http://player.vimeo.com/video/' + videoID + '?title=0&amp;byline=0&amp;portrait=0" width="' + width + '" height="' + height + '" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe>';
        if (href == null || href == 'undefined') {
          href = 'http://vimeo.com/' + videoID;
        }
        break;
      case 'youtube':
        code = '<iframe allowfullscreen="true" class="youtube-player" frameborder="0" height="' + height + '" src="http://www.youtube.com/embed/' + videoID + '" title="YouTube video player" type="text/html" width="' + width + '"></iframe>';
        if (href == null || href == 'undefined') {
          href = 'http://youtube.com/?v=' + videoID;
        }
        break;
      case 'discovery':
        code = '<iframe allowtransparency="true" frameborder="0" height="' + height + '" id="dit-video-embed" scrolling="no" src="http://static.discoverymedia.com/videos/components/snag-it-player.html?network=sci&amp;clipRefId=' + videoID + '&amp;auto=no" width="' + width + '"></iframe>';
        if (href == null || href == 'undefined') {
          href = '#';
        }
        break;
      case 'swfobject':
        // Still figuring this part out - support a callback function that fancybox calls?
        /*
        code + '<div id="swfobject-video"></div>';
        var so = new SWFObject('http://hawaiienergy.com/media/swf/jwplayer/player.swf','mpl',width,height,'9');
        so.addParam('allowfullscreen','true');
        so.addParam('allowscriptaccess','always');
        so.addParam('wmode','opaque');
        so.addVariable('file','http://hwcdn.net/g5n3v6w7/fms/rh1.f4v.smil');
        so.addVariable('provider','highwinds');
        so.write('swobject-video');
        */
        break;
    }

    if (code != '') {
      code += '<div class="embed-info"><p class="title"><a href="' + href + '" target="_blank">' + title + '</a></p><p class="caption">' + caption + '</div>';
    }

    return code;
  }

  // set initial payoff date
  if ($('#calculator').length > 0) {
    $('#calc-loan-amount').keyup(CalcConfig.calc);
    $('#calc-loan-term').keyup(CalcConfig.calc);
    $('#calc-interest-rate').keyup(CalcConfig.calc);
    $('#calc-first-payment-date-month').change(CalcConfig.calc);
    $('#calc-first-payment-date-year').change(CalcConfig.calc);
    MortgageCalculator.updateDate(parseFloat($('#' + CalcConfig.fields.loanTerm).val()) * 12, CalcConfig.fields);
  }

  // from http://www.google.com/support/analytics/bin/answer.py?answer=55527
  function recordOutboundLink(link, category, action) {
    _gat._getTrackerByName()._trackEvent(category, action);
    setTimeout('document.location = "' + link + '"', 100);
  }

  // record outbound links
  $('.bulletin a, .outbound a').click(function(e) {
    e.preventDefault();
    recordOutboundLink($(this).attr('href'), 'Outbound Links', e.target.href);
  });

  // build the menu for the graphs on the homepage
  /*
  if ($('#news-block-graphs .graphs')) {
      var graphs = $('#news-block-graphs .graphs');
      // just get the images and clear any extra marksup
      var images = graphs.find('a');
      graphs.empty().append(images);
      var content_block = graphs.parent();
      // build the select options
      var options = '';
      for (var i=0; i<images.length; i++) {
          options += '<option value="'+i+'">'+$(images[i]).find('img').attr('alt')+'</option>';
      }
      var select = "<select id=\"graphs\">" + options + "</select>";
      select = $(select).change(function(evt) {
         graphs.empty().append(images[$(evt.target).attr('value')]);
      });
      content_block.append(select);
  }
  */
});
