months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
monthsShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

var chart;
var dchart0;
var dchart1;
var dchart2;

$(document).ready(function() {
// setup dates
  bcDate = ene.length-1;
  startDate = Date.UTC(2010, 0, 8); // the first day we have data for
  endDateMillis = (bcDate * 24 * 3600 * 1000) + startDate;
  endDate =  new Date(endDateMillis) // the last day we have data for
  edDay = endDate.getUTCDate();
  edMonth = endDate.getUTCMonth();
  edYear = endDate.getUTCFullYear();
  
  dpEndDate = new Date(edYear, edMonth, edDay)
  // generate the date ranges - dates for millis, dateRanges for the select
  dates =  [[1262908800000, 1264896000000]]; // Jan 8 - Jan 31 2010
  dateRanges = ['<option value="0">Jan 8 - Jan 31, 2010</option>'];
  i=1;
  do {
    cMonth = i%12;
    cYear = 2010 + Math.floor(i/12);
    dates0 = Date.UTC(cYear, cMonth, 1);
    if(dates0 > endDateMillis) break;
    eDay = daysInMonth(cMonth, cYear);
    dates1 = Date.UTC(cYear, cMonth, eDay);
    dates[i] = [dates0, dates1];
    dateRanges[i] = '<option value="'+i+'">'+ monthsShort[cMonth] + ' 1 - ' + monthsShort[cMonth] + ' ' + eDay + ', ' + cYear + '</option>';
  } while (i++);
  i--;
  // if the last date we have data for is not the last day of its month,
  // set the last range to one month period ending with the last date
  edLastDay = daysInMonth(edMonth, edYear);
  if(edDay < edLastDay) {
    edPrevMonth = edMonth - 1;
    edPrevYear = edYear;
    if((edMonth - 1) < 0) {
      edPrevMonth = 11;
      edPrevYear -= 1;
    }
    edPrevDateMillis =  Date.UTC(edPrevYear, edPrevMonth, edDay);
    dates[i] = [edPrevDateMillis, endDateMillis];
    dateRanges[i] = '<option value="'+ i +'">Last 30 days</option>';
  }
  dateRanges = dateRanges.join('');
  // set options and style the date range selectbox
  $('.line-date').html(dateRanges);
  $('.styled').customStyle();
  if($.browser.safari) {
    $('.styled').css({marginTop: 10});
  }

// feedback form
  fProcessed = false;
  $('.submit-b').click(function(){
    $('.error').removeClass('error');
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var emailVal = $('.femail').val();
    if(emailVal == '') {
      $('.femail').addClass('error');
      hasError = true;
    } else if(!emailReg.test(emailVal)) {
      $('.femail').addClass('error');
      hasError = true;
    }
    var nameVal = $('.fname').val();
    if(nameVal == '') {
      $('.fname').addClass('error');
      hasError = true;
    }
    var messageVal = $('.msg-text').val();
    if(messageVal == '') {
      $('.msg-text').addClass('error');
      hasError = true;
    }

    if(hasError == false) {
      $(this).hide().after('<img src="images/structural/ajax-loader.gif" alt="Loading" id="loading" />');

      $.post("/sendmail.php",
        { name: nameVal, email: emailVal, message: messageVal },
          function(data){
            $(".feed-f fieldset").slideUp("normal", function() {
              $(".feed-f fieldset").before('<p class="tym">Your message was sent.<br /> Thank you.</p>');
              fProcessed = true;
            });
          }
         );
    }

    return false;
  })

  $('.femail, .fname, .msg-text').focus(function(){
    $(this).removeClass('error');
  })

// monitor popups
  $('.cloud_content h2 a, .cloud_content .mmore').fancybox({
    type: 'iframe',
    width: 800,
    height: 530,
    padding: 20,
    autoScale: false,
    scrolling: 'no',
    overlayColor: '#86BDCC'
  });

// external links
  $('a[rel=external]').attr('target', '_blank');

// preload images
  jQuery.preLoadImages('/images/structural/as_bgr.gif');

// learn more expand
  $('.learn_more').click(function(){
    if ($(this).text() == 'Hide') {
      $('.more-hidden').animate({height: 0});
      $(this).text('Learn More');
    } else {
      $('.more-hidden').animate({height: 300});
      $(this).text('Hide');
    }
  })

// about us expand
  contactVisible = aboutVisible = false;
  $('.tn-about').click(function(){
    if(aboutVisible) {
      aboutVisible = false;
      $('.about-slide').slideUp();
      $(this).removeClass('on');
    } else {
      $('.cs-close').click();
      aboutVisible = true;
      $(this).addClass('on');
      $('.about-slide').slideDown();
    }
  })
  $('.as-close').click(function(){
      aboutVisible = false;
      $('.about-slide').slideUp();
      $('.tn-about').removeClass('on');
  })

  $('.tn-contact').click(function(){
    if(contactVisible) {
      contactVisible = false;
      $('.contact-slide').slideUp();
      $(this).removeClass('on');
    } else {
      $('.as-close').click();
      contactVisible = true;
      $(this).addClass('on');
      if(fProcessed) {
            $(".feed-f fieldset, .submit-b").show();
            $(".tym, #loading").remove();
            fProcessed = false;
      }
      $('.contact-slide').slideDown();
    }
  })
  $('.cs-close').click(function(){
      contactVisible = false;
      $('.contact-slide').slideUp();
      $('.tn-contact').removeClass('on');
  })

// switch chart display
  $('.by_day').click(function(){
    if($(this).hasClass('active')) { return false }
    if ($('.learn_more').text() == 'Hide') {
      $('.learn_more').click();
    }
    $('.over_time').removeClass('active');
    $(this).addClass('active');
    $('#line-chart').css({left: -9000});
    $('.bar-chart').css({left: 100});
    $('.select_date_f').css({height: 0, display: 'none'});
    $('.iid_ctrls').show();
    dateText = getbcDay(bcDate);
    $('.big_date').html(dateText[0]);
    $('.year').html(dateText[1]);
    return false;
  })
  lineF = true;
  $('.over_time').click(function(){
    if($(this).hasClass('active')) { return false }
    if ($('.learn_more').text() == 'Hide') {
      $('.learn_more').click();
    }
    $('.by_day').removeClass('active');
    $(this).addClass('active');
    $('#line-chart').css({left: 100});
    $('.bar-chart').css({left: -9000});
    $('.select_date_f').css({height: 40,display: 'block'});
    $('.iid_ctrls').hide();
    dateText = $('.line-date').find(':selected').text().split(', ');
    $('.big_date').html(dateText[0]);
    if (dateText[1] == undefined) {
		dateText[1] = '';
	}
    $('.year').html(dateText[1]);

    // icons
    if(lineF) {
      // set the  select to the last option
      sLast = $('.line-date option:last').val();
      $('.line-date').val(sLast).change();
      // the legend
      lineF = false;
      $('#line-chart').append('<span class="ico ico0"></span><span class="ico ico1"></span><span class="ico ico2"></span><span class="ico ico3"></span><span class="ico ico4"></span>')
      // hide/show series on icon click
      $('#line-chart .ico').click(function(){
        var ser = chart.series[$('#line-chart .ico').index($(this))];
        if(ser.visible) {
          ser.hide();
        } else {
          ser.show();
        }
      })
    }
    return false;
  })

// bar chart
  minH = 40;
  maxH = 180;
  ratio = ratio = (maxH-minH)/50;

  $('.iid_prev').click(function(){
    if(bcDate > 0) {
      bcDate--;
      setBars(bcDate);
    }
  })
  $('.iid_next').click(function(){
    if(bcDate < ene.length-1) {
      bcDate++;
      setBars(bcDate);
    }
  })
  // datepicker
  $('.bc-date').datepicker({
    minDate: new Date(2010, 0, 8),
    maxDate: new Date(dpEndDate),
    dateFormat: '@',
    showButtonPanel: true,
    closeText: 'X',
    onSelect: function(dateText, inst) {
      bcDate = Math.floor( (dateText*1 - 1262905200000)/(24*3600*1000) + 0.15 );
      setBars(bcDate);
    },
    onChangeMonthYear: function() {
      $.rule('.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active').remove()
    },
    beforeShow: function() {
      $.rule('.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active{ background:url("images/ui-bg_glass_50_3baae3_1x400.png") repeat-x scroll 50% 50% #3BAAE3;border:1px solid #2694E8;color:#FFFFFF;}').appendTo($.rule.sheets()[0])
    }

  });
  $('.iid_cal').click(function(){
    $('.bc-date').datepicker( "show" )
  })
  setBars(bcDate);

// line chart
  // select range
  $('.line-date').change(function () {
    dateText = $(this).find(':selected').text().split(', ');
    if (dateText[1] == undefined) {
		dateText[1] = '';
	}
    $('.big_date').html(dateText[0]);
    $('.year').html(dateText[1])
    start = dates[$(this).val()][0];
    end = dates[$(this).val()][1];
    chart.xAxis[0].setExtremes(start, end);
    day = new Date(start).getDay()+1;
    chart.xAxis[0].options.startOfWeek = day;
    chart.redraw();
    chart.render();
  })

  // the chart
  chart = new Highcharts.Chart({
    chart: {
      renderTo: 'line-chart',
      defaultSeriesType: 'line',
      backgroundColor: null,
      marginBottom: 70,
      marginRight: 60
    },
    title: {
      text: ''
    },
    legend: {
      enabled: false,
      align: 'center',
      verticalAlign: 'bottom',
      x: 20,
      y: -20,
      borderWidth: 1,
      borderColor: '#fafafa',
      symbolWidth: 0,
      symbolPadding: 12,
      itemStyle: {
        color: '#402e00',
        fontWeight: 'bold',
        textTransform: 'uppercase',
        fontSize: '11px'
      }
    },
    credits: {
      enabled: false
    },
    xAxis: {
      lineWidth: 0,
      tickWidth: 1,
      tickLength: 3,
      minorTickLength: 3,
      tickColor: '#000',
      tickInterval: 7*24*3600*1000,
      minorTickInterval: 24*3600*1000,
//      startOfWeek: new Date(dates[dates.length-2]).getDay()+1,
      minorGridLineWidth: 0,
      showFirstLabel: true,
      showLastLabel: true,
      startOnTick: false,
      min: dates[dates.length-1][0],
      max: dates[dates.length-1][1],
      type: 'datetime',
      dateTimeLabelFormats: {
        day: '%b %e',
        week: '%b %e'
      }
    },
    yAxis: {
      min: 0,
      max: 50,
      tickInterval: 20,
      endOnTick: false,
      minorGridLineWidth: 0,
      gridLineWidth: 0,
      title: {
        text: ''
      },
      labels: {
        formatter: function() {
          return this.value +'%';
        }
      },
      showFirstLabel: false
    },
    tooltip: {
      formatter: function() {
          return this.series.name +'<br/>'+
          Highcharts.dateFormat('%b %e', this.x) +': <strong>'+ Math.round(this.y*100)/100 +'%</strong>';
      }
    },
    plotOptions: {
      line: {
        lineWidth: 3,
        shadow: false,
        states: {
          hover: {
            lineWidth: 4
          }
        },
        marker: {
          enabled: false,
          states: {
            hover: {
              enabled: true,
              symbol: 'circle',
              radius: 5,
              lineWidth: 0
            }
          }
        },
        point: {
          events: {
            click: function() {
              bcDate = (this.x - 1263513600000)/(24*3600*1000)+7;
              setBars(bcDate);
              $('.by_day').click();
            }
          }
        }
      }
    },
    series: [{
      name: 'ENVIRONMENT',
      data: ene,
      color: '#B3C46C',
      pointStart: Date.UTC(2010, 0, 8),
      pointInterval: 24 * 3600 * 1000
    }, {
      name: 'EDUCATION',
      data: edu,
      color: '#C483AA',
      pointStart: Date.UTC(2010, 0, 8),
      pointInterval: 24 * 3600 * 1000
    }, {
      name: 'HEALTHCARE',
      data: hlt,
      color: '#D36755',
      pointStart: Date.UTC(2010, 0, 8),
      pointInterval: 24 * 3600 * 1000
    }, {
      name: 'JOBS & THE<br/>ECONOMY',
      data: ecn,
      color: '#DFBE5E',
      pointStart: Date.UTC(2010, 0, 8),
      pointInterval: 24 * 3600 * 1000
    }, {
      name: 'DEFENSE &<br/>MILITARY',
      data: dfn,
      color: '#B8AA98',
      pointStart: Date.UTC(2010, 0, 8),
      pointInterval: 24 * 3600 * 1000
    }]
  });

// pie chart 0
  dchart0 = new Highcharts.Chart({
    chart: {
      renderTo: 'dchart0',
      margin: [0, 0, 0, 0],
      plotBackgroundColor: 'none',
      plotBorderWidth: 0,
      plotShadow: false
    },
    credits: {
      enabled: false
    },
    title: {
      text: ''
    },
    plotArea: {
      shadow: null,
      borderWidth: null,
      backgroundColor: null
    },
    tooltip: {
      enabled: false
    },
    legend: {
      enabled: false
    },
    plotOptions: {
      pie: {
        states: {
          hover: {
            brightness: 0
          }
        }
      }
    },
    series: [{
      type: 'pie',
      name: '',
      innerSize: '60%',
      data: pie0data
    }]
  });

// pie chart 1
  dchart1 = new Highcharts.Chart({
    chart: {
      renderTo: 'dchart1',
      margin: [0, 0, 0, 0],
      plotBackgroundColor: 'none',
      plotBorderWidth: 0,
      plotShadow: false
    },
    credits: {
      enabled: false
    },
    title: {
      text: ''
    },
    plotArea: {
      shadow: null,
      borderWidth: null,
      backgroundColor: null
    },
    tooltip: {
      enabled: false
    },
    legend: {
      enabled: false
    },
    plotOptions: {
      pie: {
        states: {
          hover: {
            brightness: 0
          }
        }
      }
    },
    series: [{
      type: 'pie',
      name: '',
      innerSize: '60%',
      data: pie1data
    }]
  });

// pie chart 2
  dchart2 = new Highcharts.Chart({
    chart: {
      renderTo: 'dchart2',
      margin: [0, 0, 0, 0],
      plotBackgroundColor: 'none',
      plotBorderWidth: 0,
      plotShadow: false
    },
    credits: {
      enabled: false
    },
    title: {
      text: ''
    },
    plotArea: {
      shadow: null,
      borderWidth: 10,
      backgroundColor: null
    },
    tooltip: {
      enabled: false
    },
    legend: {
      enabled: false
    },
    plotOptions: {
      pie: {
        states: {
          hover: {
            brightness: 0
          }
        }
      }
    },
    series: [{
      type: 'pie',
      name: '',
      innerSize: '60%',
      data: pie2data
    }]
  });

// fancybox popup on load
  vars = getUrlVars();
  if(vars['monitor'] && vars['monitor'] < 3) {
    $('.mon-fb:eq('+vars['monitor']+')').click();
  }

}); // document.ready

// animate the bars and set the big date text
function setBars(d) {
  $('.iid_prev').removeClass('inactive');
  $('.iid_next').removeClass('inactive');
  if(bcDate == ene.length-1) {
    $('.iid_next').addClass('inactive');
  } else if (bcDate == 0) {
    $('.iid_prev').addClass('inactive');
  };
  
  
  dat = new Date((d * 24 * 3600 * 1000) + startDate);
  $('.big_date').html(months[dat.getUTCMonth()] + ' ' + dat.getUTCDate());
  dat.setDate(dat.getUTCDate());
  dat.setMonth(dat.getUTCMonth());
  dat.setFullYear(dat.getUTCFullYear());
  $('.year').html(dat.getFullYear());
  $('.bc-date').datepicker('setDate', dat);
  if(d < ene.length) {
    var hgt = new Array();
    var txt = new Array();
    hgt[0] = ene[d]*ratio+minH;
    hgt[1] = edu[d]*ratio+minH;
    hgt[2] = ecn[d]*ratio+minH;
    hgt[3] = hlt[d]*ratio+minH;
    hgt[4] = dfn[d]*ratio+minH;

    txt[0] = (Math.round(ene[d]) +'<span>%</span>');
    txt[1] = (Math.round(edu[d]) +'<span>%</span>');
    txt[2] = (Math.round(ecn[d]) +'<span>%</span>');
    txt[3] = (Math.round(hlt[d]) +'<span>%</span>');
    txt[4] = (Math.round(dfn[d]) +'<span>%</span>');

    $('.bar0').stop().animate({height: hgt[0]}, {queue: false});
    $('.bar1').stop().animate({height: hgt[1]}, {queue: false});
    $('.bar2').stop().animate({height: hgt[2]}, {queue: false});
    $('.bar3').stop().animate({height: hgt[3]}, {queue: false});
    $('.bar4').stop().animate({height: hgt[4]}, {queue: false});

    $('.perc0').html(txt[0]).stop().animate({bottom: hgt[0]+32}, {queue: false});
    $('.perc1').html(txt[1]).stop().animate({bottom: hgt[1]+32}, {queue: false});
    $('.perc2').html(txt[2]).stop().animate({bottom: hgt[2]+32}, {queue: false});
    $('.perc3').html(txt[3]).stop().animate({bottom: hgt[3]+32}, {queue: false});
    $('.perc4').html(txt[4]).stop().animate({bottom: hgt[4]+32}, {queue: false});
  } else {
    // don't have data, show flat bars
    $('.bar0, .bar1, .bar2, .bar3, .bar4').stop().animate({height: minH}, {queue: false});
    $('.perc0, .perc1, .perc2, .perc3, .perc4').html('');
  }
}

// format the date string for bar chart
function getbcDay(d) {
  var dat = new Date((d * 24 * 3600 * 1000) + startDate);
  var dMonthDay = months[dat.getUTCMonth()] + ' ' + dat.getUTCDate();
  var dYear = dat.getUTCFullYear();
  var dates = [ dMonthDay, dYear ];
  return dates;
}

//preload images
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
  }
}
})(jQuery)

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
}

// return days in a month
function daysInMonth(iMonth, iYear) {
  return 32 - new Date(iYear, iMonth, 32).getDate();
}


