window.onload = function () {
  if (typeof initGraphs == 'function'){
    initGraphs();
  }

  if (document.getElementById('datePreset')) {
    document.getElementById('datePreset').onchange = function () {
      var preset = document.getElementById('datePreset').value;
      var dateFrom = new Date();
      var now = serverTime.getTime();
      var dateTo = serverTime;
      var aDay = 24*3600*1000;
      var now2 = dateTo.getTime();
      switch(preset)
      {
        case '7d':
          dateFrom.setTime(now-7*aDay);
          document.getElementById('dateFrom').value =
            dateFrom.getFullYear()+'-'
            +zeroPad(dateFrom.getMonth()+1, 2)+'-'
            +zeroPad(dateFrom.getDate(),2);
          document.getElementById('dateTo').value =
            dateTo.getFullYear()+'-'
            +zeroPad(dateTo.getMonth()+1, 2)+'-'
            +zeroPad(dateTo.getDate(),2);
          break;
        case '30d':
          dateFrom.setTime(now-30*aDay);
          document.getElementById('dateFrom').value =
            dateFrom.getFullYear()+'-'
            +zeroPad(dateFrom.getMonth()+1, 2)+'-'
            +zeroPad(dateFrom.getDate(),2);
          document.getElementById('dateTo').value =
            dateTo.getFullYear()+'-'
            +zeroPad(dateTo.getMonth()+1, 2)+'-'
            +zeroPad(dateTo.getDate(),2);
          break;
        case 'lm':
          dateFrom.setTime(now-dateTo.getDate()*aDay);
          document.getElementById('dateFrom').value =
            dateFrom.getFullYear()+'-'
            +zeroPad(dateFrom.getMonth()+1, 2)
            +'-01';
          document.getElementById('dateTo').value =
            dateFrom.getFullYear()+'-'
            +zeroPad(dateFrom.getMonth()+1, 2)+'-'
            +zeroPad(daysInMonth(dateFrom.getFullYear(), dateFrom.getMonth()),2);
          break;
        case 'cm':
          document.getElementById('dateFrom').value =
            dateFrom.getFullYear()+'-'
            +zeroPad(dateFrom.getMonth()+1, 2)
            +'-01';
          document.getElementById('dateTo').value =
            dateTo.getFullYear()+'-'
            +zeroPad(dateTo.getMonth()+1, 2)+'-'
            +zeroPad(dateTo.getDate(),2);
          break;
        case 'cy':
          document.getElementById('dateFrom').value = dateFrom.getFullYear()+'-01-01';
          document.getElementById('dateTo').value =
            dateTo.getFullYear()+'-'
            +zeroPad(dateTo.getMonth()+1, 2)+'-'
            +zeroPad(dateTo.getDate(),2);
          break;
      }
    }
    
    document.getElementById('dateTo').onchange = function () {
      updatePreset(document.getElementById('datePreset'));
    }
    
    document.getElementById('dateFrom').onchange = function () {
      updatePreset(document.getElementById('datePreset'));
    }
    
    // Set the date present selection based on the values in the date fields.
    updatePreset(document.getElementById('datePreset'));
  }

  if (typeof customInit == 'function'){
    customInit();
  }
};

$(document).ready(function(){
  /* Tooltip */
  xOffset = 15;
  yOffset = -10;
  $('.tooltip').parent().hover(function(){
    $(this).children('.tooltip').stop(true, true);
    $(this).children('.tooltip').fadeIn("slow");
  }, function(){
    $(this).children('.tooltip').stop(true, true);
    $(this).children('.tooltip').fadeOut("fast");
  });

  $('.tooltip').parent().mousemove(function(e){
    $(this).children('.tooltip').offset({top: e.pageY+yOffset, left: e.pageX+xOffset});
  });
  $('.tooltip').parent().mouseleave(function(e){
    $(this).children('.tooltip').stop(true, true);
    $(this).children('.tooltip').fadeOut("fast");
  });
    
  /* Tabbed area */
  $('.tabbedArea').each(function(){
    $(this).children('.tabFragment').hide();
    $(this).find('.tabs :first').addClass('active');
    $($(this).find('.tabs :first a').attr('href')).show();
  });

  $('.tabs a').click(function(){
    $(this).parents('.tabbedArea').children('.tabFragment').hide();
    $(this).parent().addClass('active');
    $(this).parent().siblings().removeClass('active');
    $($(this).attr('href')).show();
    $('table.report').scrollable();
    return false;
  });

  /* Expand area */
  $('.expandArea .expandLegend').click(function(){
    $(this).siblings('.expandSection').toggle('fast');
  });
//  $('.expandSelf .subject').click(function(){
//      alert("clicked");
//      
//  });

  $('.expandSelf').click(function(){
    var isVisible = $(this).find('.expandSection').is(':visible');
    $(this).parents('.accordion').find('.expandSelf .expandSection').hide('fast');
    $(this).parents('.accordion').find('.expandSelf').removeClass('open');
    if (isVisible) {
      $(this).find('.expandSection').hide('fast');
      $(this).removeClass('open');
    } else {
      $(this).find('.expandSection').show('fast');
      $(this).addClass('open');
   }
  });
  $('.triggerExpand').click(function(){        
    $(this).parent().find('div.expandSection').toggle('slow');
  });
  
  $('.inlineMenuTrigger').click(function(event) {
    if ($(this).find('.inlineMenu').is(':visible'))
      $('.inlineMenu').hide();
    else {
      $('.inlineMenu').hide();
      $(this).find('.inlineMenu').first().toggle('fast');
    }
    
    $('body').one('click',function() {
      $('.inlineMenu').hide();
    });

    event.stopPropagation();
  });

  /* Suppress onClick events on parent blocks when clicking a link */
  $('a').click(function() {
    $(this).parents().unbind('click');
  });

  if (window.location.hash) {
    $('*[id="'+window.location.hash.replace('#', '')+'"]').children('.expandSection').toggle('slow');
  }

  /* Make disabled links unclickable */
  $('.disabled a').click(function() {
    return false;
  });

  /* Adds sorting to tables */
  $('table.report').tablesorter({
    textExtraction: function(node) {
      return $(node).metadata().rawVal || node.innerHTML;
    },
    widgets: ['zebra']
  });
  
  $('table.report').scrollable();
  
  /* Display percent data nicely */
  $('td.percentage').each(function () {
    if ($(this).metadata().rawVal) {
      $(this).wrapInner('<div class="percentVisual"><div class="bar" style="width:'+$(this).metadata().rawVal+'%"><span></span></div></div>');
      $(this).addClass('dontCrush');
    }
  });

  /* Open external links in a new window */
  $('a[rel="external"]').click(function(){window.open(this.href);return false;});
  
  /* De-emphasises decimals in ratios*/
  $('td.ratio').each(function () {
    $(this).html($(this).html().replace(/\.(\d+)/, '<small>.$1</small>'));
  });
  
  $('.showBaseVal').change(function () {
          if ($(this).attr('checked')) {
              $('td.currency').each(function () {
              if(($(this).metadata().baseVal) && ($(this).metadata().rawVal) != 0){
                  $(this).append( '<span class="baseVal"><br />' + $(this).metadata().baseVal.toString() + '</span>');
              }
              });
          }
          else {
              $('span.baseVal').remove();
          }
      });
});

$(window).resize(function() {
  $('table.report').scrollable();
});

function zeroPad(n, digits) {
  n = n.toString();
  while (n.length < digits) {
    n = '0' + n;
  }
  return n;
}

function daysInMonth(year,month) {
  var dd = new Date(year, month+1, 0);
  return dd.getDate();
}

function updatePreset(selectElem) {
  if (selectElem.tagName.toLowerCase() == 'select') {
    var now = serverTime;
    
    var dateTo = new Date();
    var dateParts = document.getElementById('dateTo').value.split('-');
    dateTo.setFullYear(dateParts[0]);
    dateTo.setMonth(dateParts[1]-1);
    dateTo.setDate(dateParts[2]);
    
    var dateFrom = new Date();
    dateParts = document.getElementById('dateFrom').value.split('-');
    dateFrom.setFullYear(dateParts[0]);
    dateFrom.setMonth(dateParts[1]-1);
    dateFrom.setDate(dateParts[2]);
    
    var aDay = 1000*3600*24;
    
    var currentYear = new Date();
    currentYear.setMonth(0);
    currentYear.setDate(1);
    
    var lastMonth = new Date();
    lastMonth.setMonth(now.getMonth()-1);
    lastMonth.setDate(1);
    
    var eoLastMonth = new Date();
    eoLastMonth.setDate(1);
    eoLastMonth.setTime(eoLastMonth.getTime()-aDay);
    
    var presetVal = "";
    
    if (''+now.getFullYear()+now.getMonth()+now.getDate() == ''+dateTo.getFullYear()+dateTo.getMonth()+dateTo.getDate()) {
      switch ((Math.floor(dateFrom.getTime()/aDay))) {
        case Math.floor(currentYear.getTime()/aDay):
          presetVal = 'cy';
          break;
        case Math.floor(now.getTime()/aDay)-(now.getDate()-1):
          presetVal = 'cm';
          break;
        case Math.floor(now.getTime()/aDay)-30:
          presetVal = '30d';
          break;
        case (Math.floor(now.getTime()/aDay)-7):
          presetVal = '7d';
          break;
      }
    } else if (Math.floor(dateFrom.getTime()/aDay) == Math.floor(lastMonth.getTime()/aDay) 
      && Math.floor(dateTo.getTime()/aDay) == Math.floor(eoLastMonth.getTime()/aDay)) {
      presetVal = 'lm';
    }

  
    for (var i=0; i < selectElem.options.length; i++) {
      if (selectElem.options[i].value == presetVal)
        selectElem.options[i].selected = true;
    }
  }
}

function str_repeat(i, m) {
  for (var o = []; m > 0; o[--m] = i);
  return o.join('');
}

function sprintf() {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x, s = '';
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) {
      o.push(m[0]);
    }
    else if (m = /^\x25{2}/.exec(f)) {
      o.push('%');
    }
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) {
        throw('Too few arguments.');
      }
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number')) {
        throw('Expecting number but found ' + typeof(a));
      }
      switch (m[7]) {
        case 'b':
          a = a.toString(2);
          break;
        case 'c':
          a = String.fromCharCode(a);
          break;
        case 'd':
          a = parseInt(a);
          break;
        case 'e':
          a = m[6] ? a.toExponential(m[6]) : a.toExponential();
          break;
        case 'f':
          a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a);
          break;
        case 'o':
          a = a.toString(8);
          break;
        case 's':
          a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a);
          break;
        case 'u':
          a = Math.abs(a);
          break;
        case 'x':
          a = a.toString(16);
          break;
        case 'X':
          a = a.toString(16).toUpperCase();
          break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a >= 0 ? '+'+ a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length - s.length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(s + (m[4] ? a + p : p + a));
    }
    else {
      throw('Huh ?!');
    }
    f = f.substring(m[0].length);
  }
  return o.join('');
}

