//Extend JS objects
Array.prototype.max = function() {
  var max = this[0];
  var len = this.length;
  for (var i = 1; i < len; i++) if (this[i] > max) max = this[i];
  return max;
};
Array.prototype.min = function() {
  var min = this[0];
  var len = this.length;
  for (var i = 1; i < len; i++) if (this[i] < min) min = this[i];
  return min;
};

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

//setup our metadata div object
$.metadata.setType('attr', 'data');

$.fn.toggleValue = function() {
  return this.focus(function() {
    if( this.value == this.defaultValue ) {
      this.value = "";
    }
  }).blur(function() {
    if( !this.value.length ) {
      this.value = this.defaultValue;
    }
  });
};

// tooltip
$.fn.ToolTip = function(bgcolour, fgcolour) {
  this.mouseover(
    function(e) {
      if ((!this.title) && !this.tooltipset) return;
          // get mouse coordinates
          // based on code from http://www.quirksmode.org/js/events_properties.html
          var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft : 0);
          var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop : 0);
          // mouseX += 5;
          // mouseY += 5;
          bgcolour = bgcolour || "#f8f6d4";
          fgcolour = fgcolour || "#000";
          // if there is no div containing the tooltip
          if (!this.tooltipdiv) {
              // create a div and style it
              var div = document.createElement("div");
              this.tooltipdiv = div;
              $(div).css(
              {
                  backgroundColor: bgcolour,
                  border: "1px solid #ddd",
                  borderBottom: "1px solid #333",
                  borderRight: "1px solid #555",
                  color: fgcolour,
                  padding: "2px",
                  position: "absolute",
                  fontSize: "10px"
              });
              // add the title/alt attribute to it
              this.tooltipdiv.innerHTML = (this.title || this.alt);
              this.tooltipdiv.title = "";
              this.tooltipdiv.alt = "";
              $("body").append(div);
              this.tooltipset = true;
          }
          $(this.tooltipdiv).show().css({left: mouseX + "px", top: mouseY + 3 + "px"});
      }
  ).mouseout(
    function() {
      if (this.tooltipdiv) {
          $(this.tooltipdiv).hide();
      }
    }
  );
  return this;
};

// Behaviours
$(document).ready(function() {

  // flash
  if ($('div.flash').length > 0) {
    var statuses = ['error', 'notice'];
    for (var i = 0; i < statuses.length; i++) {
      var status = statuses[i];
      $('div.'+status).append('<img class="flash-close-box" src="/images/icons/'+status+'_close.gif" alt=""/>');
    }
    $('img.flash-close-box').click(function() {
      $('div.flash').remove();
      return false;
    });
    //absolute postitioning: need to subtract margins, padding, border, etc.
    $('div.flash').width($(window).width()-($('div.flash').outerWidth(true)-$('div.flash').width()));
    $('div.flash').slideDown('slow');
    $('div.flash').animate({ opacity: 1.0 }, 10000).slideUp('slow', function() { $(this).remove(); });
  }

  //navigation parent menu item -- add hover effects and on click event
  $("ul.subnav").parent().find('a.has_subnav').after("<span></span>").click(function() {
    $(this).next().click();
  }).hover(function() {
    $(this).next().css("background-color", "#029ab2");
    $(this).css("background-color", "#029ab2");
  }, function() {
    $(this).next().removeAttr("style");
    $(this).removeAttr("style");
  });

  //navigation sub menu items -- add hover effects and on click event to follow each link
  $("ul.main li span").click(function() {
    $(this).parent().find("ul.subnav").toggle();
    $(this).parent().hover(function() { }, function(){
    $(this).parent().find("ul.subnav").hide();
    });
  }).hover(function() {
    $(this).siblings().css("background-color", "#029ab2");
    $(this).addClass("subhover");
  }, function() {
    $(this).siblings(':visible').css("background-color", "#3c75cf");
    $(this).removeClass("subhover");
  });

  $("input.toggle-value").toggleValue();

  // users_sessions: toggle login type
  $('#toggle_login_type_link').click(function() {
    $('#password-login').toggle();
    $('#openid-login').toggle();
    if ($('#password-login').css("display") == 'none') {
      $('#toggle_login_type_link').html("(Sign in with username/password)");
    } else {
      $('#toggle_login_type_link').html("(Sign in with an OpenID)");
    }
    return false;
  });

  $('input[type=checkbox]#csv').click(function() {
     var action = $(this).parent().parent().attr('action').replace('.csv', '');
     if ($(this).is(':checked')) { action+= '.csv'; }
     $(this).parent().parent().attr('action', action);
  });

  $('span.strftime, span.time_ago_in_words').click(function() {
    if ($('span.strftime').is(':visible')) {
      $('span.strftime').hide();
      $('span.time_ago_in_words').show();
    } else {
      $('span.strftime').show();
      $('span.time_ago_in_words').hide();
    }
    return false;
  });

  // buildings: toggle managed_by
  $('img.managed_by').click(function() {
    $('tr#managed_by_row-'+this.id.split('-')[1]).toggle();
    return false;
  });

  // meter readings: toggle comment
  $('img.comment-icon').click(function() {
    if ($('tr#row-'+this.id).find('p').text() == '') {
      window.location = $('td#edit-'+this.id+' > a').attr('href');
    } else {
      $('tr#row-'+this.id).toggle();
    }
    return false;
  });

  // buildings
  $('a.edit-category').click(function() {
    $('span#category-edit').toggle();
    $('span#category-show').toggle();
    return false;
  });

  // building categories select (building_types)
  $("select#categories").change(function() {
    $.ajax({
      type: "GET", url: '/building_types.js?building_type_category_id='+ $(this).val(),
      success: function(data) {
        var types = eval( "(" + data + ")");
        var options = '';
        for (var i = 0; i < types.length; i++) {
          options += '<option value="' + types[i].building_type.id + '">' + types[i].building_type.name + '</option>';
        }
        $("select#types").html(options);
        $("select#types").removeAttr("disabled");
      }
    });
  });

  // meter type select (units)
  $("select#meter_meter_type").change(function() {
    if ($(this).val() == 'ElectricityMeter') {
      $('div.off-peak').parent().show();
    } else {
      $('div.off-peak').parent().hide();
    }
    $.ajax({
      type: "GET", url: '/units.js?meter_type='+ $(this).val(),
      success: function(data) {
        var selected_unit = $("select#units :selected").val();
        var units = eval( "(" + data + ")");
        var options = '';
        for (var i = 0; i < units.length; i++) {
          options += '<option value="' + units[i].unit.id + '">' + units[i].unit.name + '</option>';
        }
        $("select#units").html(options);
        $("select#units").val(selected_unit);
      }
    });
  });

  //load meter types on page load for meter form
  if ($("select#meter_meter_type").length > 0) {
    $.ajax({
      type: "GET", url: '/units.js?meter_type='+ $("select#meter_meter_type").val(),
      success: function(data) {
        var selected_unit = $("select#units :selected").val();
        var units = eval( "(" + data + ")");
        var options = '';
        for (var i = 0; i < units.length; i++) {
          options += '<option value="' + units[i].unit.id + '">' + units[i].unit.name + '</option>';
        }
        $("select#units").html(options);
        $("select#units").val(selected_unit);
      }
    });
  }

  $("tr").hover(function() {
      $(this).addClass("hilite");
  }, function() {
      $(this).removeClass("hilite");
  });

  $("input#hide_generated").click(function() {
    if ($(this).attr('checked')) {
      $('tr.generated').hide();
    } else {
      $('tr.generated').show();
    }
  });

  // radio buttons
  $("td input[type='radio'].toggle").bind('click', function() {
    var notChecked = $("input[name='"+this.name+"']:not(:checked)");
    for (var i = 0; i < notChecked.length; i++) {
      $("tr."+$(notChecked[i]).val()).hide();
    }
    var checked = $("input[name='"+this.name+"']:checked");
    for (var i = 0; i < checked.length; i++) {
      $("tr."+$(checked[i]).val()).show();
    }
    return true;
  });

  //community aggregates period selection radio buttons
  $("th input[type='radio'].toggle_period").bind('click', function() {
    //convert to metric check box
    var convert_checked = false;
    if ($("th input[type='checkbox'].toggle_metric_conversion")[0] !== undefined) {
      convert_checked = $("th input[type='checkbox'].toggle_metric_conversion")[0].checked;
    }
    var notChecked = $("input[name='"+this.name+"']:not(:checked)");
    for (var i = 0; i < notChecked.length; i++) {
      $("span."+notChecked[i].value).hide();
      $("span."+notChecked[i].value+"_kgs").hide();
    }
    var checked = $("input[name='"+this.name+"']:checked");
    for (var i = 0; i < checked.length; i++) {
      if (convert_checked) {
        $("span."+$(checked[i]).val()).show();
        $("span."+$(checked[i]).val()+".c_metric").hide();
        $("span."+$(checked[i]).val()+"_kgs").show();
      } else {
        $("span."+$(checked[i]).val()+"_kgs").hide();
        $("span."+$(checked[i]).val()).show();
      }
    }
    return true;
  });
  //community aggregates convert from 1000's lbs to metric tonnes
  $("th input[type='checkbox'].toggle_metric_conversion").change(function() {
    //alert(this.checked + ' is my value set?');
    var period_to_show = $("input[name='period']:checked");
    if (this.checked) {
      $("th.metric").show();
      $("th.non_metric").hide();
      $("span.c_metric."+period_to_show[0].value).hide();
      $("span.c_metric."+period_to_show[0].value+'_kgs').show();
    } else {
      $("th.metric").hide();
      $("th.non_metric").show();
      $("span.c_metric."+period_to_show[0].value+'_kgs').hide();
      $("span.c_metric."+period_to_show[0].value).show();
    }
  });

  // building tabs
  $('#building-tabs > ul').tabs().bind('show.ui-tabs', function(e, ui) {
    // setup a regex expression to test if the analysis tab is shown
    var analysis_regex = /^analysis.*/;
    if (analysis_regex.test(ui.panel.id)) {
      populateCusumTable();
      $("#cusum-table").show();
      //get the data (if not gotten) and draw the performance line if not drawn
      if ($('#performance-line-heating').length != 0) { getAnalysisChartData("performance_line", "heating"); }
      else if ($('#performance-line-cooling').length != 0) { getAnalysisChartData("performance_line", "cooling"); }
      //only do this for the de version
      if (ui.panel.id == "analysis-de") { shrinkAnalysisDiv(); }
    } else {
      $("#cusum-table").hide();
    }
    if (ui.panel.id == 'report') { resizeReportDivs(); }
    return false;
  });

  // snapshot tabs
  $('#snapshot-tabs > ul').tabs().bind('show.ui-tabs', function(e, ui) {
    return false;
  });

  // community tabs
  $('#community-tabs > ul').tabs().bind('show.ui-tabs', function(e, ui) {
    return false;
  });

  // degree day tabs
  $('#degree-day-tabs > ul').tabs().bind('show.ui-tabs', function(e, ui) {
    //use the panel id naming convention to recreate the parts
    panel_id_parts = ui.panel.id.split("-");
    analysis_type = panel_id_parts[0]+"_"+panel_id_parts[1];
    degree_day_type = panel_id_parts[2];
    //make sure the data retrieved and the chart is drawn
    getAnalysisChartData(analysis_type, degree_day_type);
    return false;
  });

  // Tracking chart tabs
  $('#chart-tabs > ul').tabs().bind('show.ui-tabs', function(e, ui) {
    if (ui.panel.id == 'energy') {
      getTimeSeriesChartData();
      switchZoomWeekSelect(false);
    } else {
      getChartData(ui.panel.id);
      //disable the zoom for the recent activity as it is only 7 days no whole timeseries period
      (ui.panel.id == 'weekly_electricity') ? switchZoomWeekSelect(true) : switchZoomWeekSelect(false);
    }
    return false;
  });

  // buidling report tabs
  $('#report-tabs > ul').tabs().bind('show.ui-tabs', function(e, ui) {
    //resize the report divs
    resizeReportDivs();
    return false;
  });

  //business reprt tabs
  $('div#business-report-tabs > ul').tabs().bind('show.ui-tabs', function(e, ui) {
    return false;
  });

  //newsletter form text field
  $('#uihrdy-uihrdy.email-add').focus(function() {
    $(this).val('');
  });

  //modify the newsletter subscribe form function
  $('#newsletter-subscribe.check').change(function() {
    if ($(this).is(':checked')) {
      $('#uihrdy-uihrdy-submit').val('Subscribe');
      var mod_url = $('#uihrdy-uihrdy-submit').closest('form').attr('action').replace("/u/", "/s/");
      $('#uihrdy-uihrdy-submit').closest('form').attr('action', mod_url);
    } else {
      $('#uihrdy-uihrdy-submit').val('Unsubscribe');
      var mod_url = $('#uihrdy-uihrdy-submit').closest('form').attr('action').replace("/s/", "/u/");
      $('#uihrdy-uihrdy-submit').closest('form').attr('action', mod_url);
    }
  });

  //email confirmation field
  $('#email-confirmation').blur(function() {
    if ($('#user_email').val() != "") {
      if ($('#user_email').val() != $('#email-confirmation').val()) {
        //alert the user that we have a problem.
        $('#email-confirmation-alert').show();
        $('#email-confirmation').css("background-color", "#F2AFAF");
        $('#email-confirmation').focus();
        $('#user_submit').attr('disabled', true);
      } else {
        //enable the submit button once we pass
        $('#email-confirmation').css("background-color", "#FFFFFF");
        $('#email-confirmation-alert').hide();
        $('#user_submit').attr('disabled', false);
      }
    }
  });

  //check the email confirmation when i check the terms & conditions
  $('#user_password_confirmation').focus(function() {
    if ($('#user_email').val() != "") {
      $('#email-confirmation').blur();
    }
  });

  //add a popup notifying the user that we are processing the uploaded file.
  $('#csv_submit').click(function() {
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#loader-popup").height();
    var popupWidth = $("#loader-popup").width();
    $("#loader-popup").css({ "position": "absolute", "top": windowHeight/2-popupHeight/2, "left": windowWidth/2-popupWidth/2 });
    $('img.small-loader').show();
    $('#loader-popup').fadeIn("slow");
  });

  //only allow the csv upload if the user selects a file
  $('#csv_file').change(function() {
    if ($(this).val() != "") {
      var ext = $(this).val().substring($(this).val().lastIndexOf('.') + 1).toLowerCase();
      if(ext != 'csv') {
        $(this).val("");
        $('#csv_submit').attr('disabled', true);
        $('#csvfile_ext_error').show();
      } else {
        $('#csv_submit').attr('disabled', false);
        $('#csvfile_ext_error').hide();
      }
    } else {
      $('#csv_submit').attr('disabled', true);
    }
  });

  //attach numeric function to meter_reading field
  $('input#meter_reading_reading').numeric();

  //setup the dialog for no readings for the weekly period selected
  $("#no-readings-dialog-modal").dialog({
    autoOpen: false,
    resizable: false,
    modal: true,
    closeOnEscape: true
  });

  //setup the dialog for meter readings check
  $("#dialog-confirm").dialog({
      open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
      autoOpen: false,
      resizable: false,
      //height:140,
      modal: true,
      closeOnEscape: false,
      buttons: {
        "Agree": function() {
          $( this ).dialog( "close" );
          //skip our submit handler
          $('form[class$=meter_reading]')[0].submit();
        },
        Cancel: function() {
          $( this ).dialog( "close" );
          //focus on the reading field
          $('input#meter_reading_reading').focus();
          $('div#valid-meter-reading > span').attr('title', 'invalid');
        }
      }
    });

  //meter readings roll over dialog
  $("#dialog-multi-readings-confirm").dialog({
      open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
      autoOpen: false,
      resizable: false,
      //height:140,
      modal: true,
      closeOnEscape: false,
      buttons: {
        "Agree": function() {
          $( this ).dialog( "close" );
          //skip our submit handler
          $('form#multi_meter_readings')[0].submit();
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
  });

  //override submit event handler for the multi-meter-readings page to check roll overs / form validation before submit
  if ($('form#multi_meter_readings').length > 0) {
    $('form#multi_meter_readings').submit(function() {
      //check if the ajax result has passed
      var invalid_fields = false;
      //check all the readings on the page
      jQuery.each($('form#multi_meter_readings > div.panel'), function(index, value) {
        //check the next reading panel if this one is valid
        // if ($('span[id^=valid-meter-reading-]', this).attr("title") === 'valid') { return true; } else { valid_form = false; }
        var meter_id = $('[id$=_meter_id]', this).val();
        var reading_val = $('input#[id$=_reading]', this).val();
        //check if a reading has been set
        if (reading_val === "") {
          if ($('span#'+this.id+'_readingid', this).length === 0) { $('<span id='+this.id+'_readingid style="color:red">*&nbsp</span>').insertBefore($('input#[id$=_reading]', this)); }
          invalid_fields = true;
        }
        if (meter_id == "") {
          if ($('span#'+this.id+'_meterid', this).length === 0) { $('<span id='+this.id+'_meterid style="color:red">*&nbsp</span>').insertBefore($('select[id$=_meter_id]', this)); }
          invalid_fields = true;
        }
      });
      //stop any processing the form if any of the fields are invalid
      if (invalid_fields) {
        if ($('span#required-fields', this).length === 0) { $('<span id="required-fields" style="color:red">* Indicates required fields&nbsp</span>').insertBefore($('form#multi_meter_readings > p.submit > input#meter_readings_submit')); }
        return false;
      }
      //make sure the user doesn't press the button again
      var back_href = $('form#multi_meter_readings > p.submit > span > a').attr('href');
      $('form#multi_meter_readings > p.submit > input#meter_readings_submit').attr('disabled', 'disabled');
      $('form#multi_meter_readings > p.submit > span > a').removeAttr("href");
      //loop over each panel
      jQuery.each($('form#multi_meter_readings > div.panel'), function(index, value) {
        var meter_id = $('[id$=_meter_id]', this).val();
        var reading_val = $('input#[id$=_reading]', this).val();
        //set the field to testing for each panel -- used in AJAX callback
        $('span[id^=valid-meter-reading-]', this).attr("title", "testing");
        //AJAX call to get the latest reading for this meter
        checkPreviousValuesMultiReadings(this.id, meter_id, reading_val, back_href);
      });
      //override the default submit handler
      return false;
    });
  }

  //override submit handler to check for roll over for the meter reading form.
  if ($('form[class$=meter_reading]').length > 0) {
    $('form[class$=meter_reading]').submit(function() {
      //check if the ajax result has passed
      if ($('div#valid-meter-reading > span').attr("title") == 'invalid') {
        var reading_id = get_meter_reading_form_id();
        var meter_id = $('[id$=meter_reading_meter_id]').val();
        //check if a reading has been set
        if ($('input#[id$=meter_reading_reading]').val() === "") {
          $('input#[id$=meter_reading_reading]').focus();
          return false;
        } else if (meter_id == "") {
          //check that the user setup a meter
          $('select[id$=meter_reading_meter_id]').focus();
          return false;
        } else if($('input#[id$=meter_reading_reading]').val() !== "") {
          var back_href = $('p.submit > span > a').attr('href');
          //make sure the user doesn't press the button again
          $('input[type=submit][id$=meter_reading_submit]').attr('disabled', 'disabled');
          $('p.submit > span > a').removeAttr("href");
          //AJAX call to get the latest reading for this meter
          checkLastReading(meter_id, reading_id, back_href);
          return false;
        }
      }
    });
  }

  //setup the click handler event for the help help_table_image icon
  if ($("img#help_table_image").length > 0) {
    //bind a click handler to the help image
    $("img#help_table_image").click(function() {
      $("#dialog-annualised-table-help").dialog("open");
    });
  }

  //setup the click handler event for the help icon
  if ($("img#help_image").length > 0) {
    //bind a click handler to the help image
    $("img#help_image").click(function() {
      $("#dialog-help").dialog("open");
    });
  }

  //bind the click close events to the help list links
  if ($("#dialog-help").length > 0) {
    //bind a click handler to the help image
    $("#dialog-help > ul > li > a").click(function() {
      $("#dialog-help").dialog("close");
    });
  }

  //help dialog
  $("#dialog-help").dialog({
      open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
      autoOpen: false,
      resizable: false,
      //height:140,
      modal: true,
      closeOnEscape: true,
      buttons: {
        "Close": function() {
          $( this ).dialog( "close" );
        }
      }
  });

  //help table dialog
  $("#dialog-annualised-table-help").dialog({
      open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
      autoOpen: false,
      resizable: false,
      //height:140,
      modal: true,
      closeOnEscape: true,
      buttons: {
        "Close": function() {
          $( this ).dialog( "close" );
        }
      }
  });


  //tootltip for interpolated readings.
  // $('span.interpolated').ToolTip();

  //setup my JS notice & weather station warning for the AJAX calls
  $("#js_flash").hide(); // hide the JS Flash container div
  //hide my waring about weather station providing invalid days
  $("#invalid_weather_data").hide();

  //US override for default building table display and CSS
  if (locale == 'en-US') { $("td input[type='radio'][value='money-spend'].toggle").click(); }

  //multi-reading comment div show hide
  if ($("div[id^=comment_toggles]").length > 0) {
    //loop over each one
    jQuery.each($("div[id^=comment_toggles]"), function(index, value) {
      //bind click handlers to the icons
      $("img#arrow_up", this).click(function() {
        $("div#reading_comment_"+(index+1)).hide();
      });
      $("img#arrow_down", this).click(function() {
        $("div#reading_comment_"+(index+1)).show();
      });
    });
  }

  //report year type select events
  if ($("input[name=year-type]", $("div#report")).length > 0) {
    $("input[name=year-type]", $("div#report")).click(function() {
      if (this.value === "1") {
        //check boundary of cal years against the fin years (cal SuperSet fin)
        var cal_year = $("select#cal_report_year", $("div#report")).val();
        //set the value to be the last fin year
        ($("select#fin_report_year > option[value='" + cal_year +"']", $("div#report")).text() === "") ? $("select#fin_report_year > option", $("div#report")).last().attr('selected', 'selected') : $("select#fin_report_year", $("div#report")).val($("select#cal_report_year", $("div#report")).val());
        $("select#cal_report_year", $("div#report")).hide();
        $("select#fin_report_year", $("div#report")).show();
      } else {
        $("select#cal_report_year", $("div#report")).val($("select#fin_report_year", $("div#report")).val());
        $("select#fin_report_year", $("div#report")).hide();
        $("select#cal_report_year", $("div#report")).show();
      }
    });
  }

  //business report - turn off cal / fin years if all years selected
  if ($("select[id$=_report_year]", $("div#report")).length > 0) {
    $("select[id$=_report_year]", $("div#report")).change(function() {
      //disable the cal / fin radio buttons if All Years ("") selected
      if (this.value === "") { $("input[name=year-type]", $("div#report")).attr('disabled', 'disabled'); }
      else { $("input[name=year-type]", $("div#report")).removeAttr('disabled'); }
    });
  }

  //process report button event
  if ($("div#report").length > 0) {
    $("button#get_report_data", $("div#report")).click(function() {
      //get the year of interest and the financial year
      var req_financial_year = $("input[name=year-type]:radio:checked", $("div#report")).val();
      var req_year = (req_financial_year === "1") ? $("select#fin_report_year", $("div#report")).val() : $("select#cal_report_year", $("div#report")).val();
      //check if they differ from the last processed values
      var current_year = $("input#year_of_interest", $("div#report")).val();
      var current_financial_year = $("input#financial_year", $("div#report")).val();
      //only process the building report if we have changed year types
      if (req_financial_year !== current_financial_year && $('div.building').length > 0) { getChartData("building_report_summary", true, undefined, req_financial_year); }
      //update the yearly building and business report data
      if (req_year !== current_year || req_financial_year !== current_financial_year) {
        //building report data
        populateReportData(req_year, req_financial_year);
        //business report chart data
        if ($('div.business').length > 0) {
          getChartData("business_report_summary", true, undefined, req_financial_year, req_year);
          getChartData("business_report_details", true, undefined, req_financial_year, req_year);
        }
        //remember the requested values for next time
        $("input#year_of_interest", $("div#report")).val(req_year);
        $("input#financial_year", $("div#report")).val(req_financial_year);
      }
    });
  }

  //business level report
  if ($('div.business').length > 0) {
    //business summary report
    if ($("div#business-summary-table").length > 0) { populateReportData(); }
    //business level summary report
    if ($("div#business-summary-chart").length > 0) {
      var financial_year = $("input[name=year-type]:radio:checked", $("div#report")).val();
      var year_of_interest = (financial_year === "1") ? $("select#fin_report_year", $("div#report")).val() : $("select#cal_report_year", $("div#report")).val();
      getChartData('business_report_summary', false, undefined, financial_year, year_of_interest);
    }
    //all business buildings details report
    if ($("div#business-details-chart").length > 0) {
      var financial_year = $("input[name=year-type]:radio:checked", $("div#report")).val();
      var year_of_interest = (financial_year === "1") ? $("select#fin_report_year", $("div#report")).val() : $("select#cal_report_year", $("div#report")).val();
      getChartData('business_report_details', false, undefined, financial_year, year_of_interest);
    }
  }
  //process the charts if we are on the buildings page.
  if ($('div.building').length > 0) {
    // setup the default charts
    if ($('#money').length != 0) {
      getChartData('money');
    }
    if ($('#energy').length != 0) {
      getTimeSeriesChartData();
    }
    //preload the other chart data
    if ($('#weekly_electricity').length != 0) {
      getChartData('weekly_electricity');
    }
    if ($('#co2').length != 0) {
      getChartData('co2');
    }
    if ($('#snapshot_html').length != 0) {
      //get the summary chart data
      populateSnapshotHTML();
    }
    //building level report
    if ($("div#report").length > 0) {
      populateReportData();
      var financial_year = $("input[name=year-type]:radio:checked", $("div#report")).val();
      getChartData('building_report_summary', false, undefined, financial_year);
    }
//TODO: turn the enabled type of degree day into an ajax call back and setup.
    //get the analysis charts data
    if ($('#performance-line-heating').length != 0) {
      getAnalysisChartData("performance_line", "heating");
      getAnalysisChartData("control_line", "heating");
    }
    if ($('#performance-line-cooling').length != 0) {
      getAnalysisChartData("performance_line", "cooling");
      getAnalysisChartData("control_line", "cooling");
    }
    //and get the cusum table ready
    populateCusumTable();
  }
});

// ---------- USER DEFINED FUNCTIONS ----------

// open links with attribute rel="external" in new window
$(function(){$('a[href][rel*=external]').each(function(i){this.target = "_blank";});});

function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
          str += '<li>(' + type + ') ' + property +
                 ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';

          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

      // Close indent
      str += '</ul>';

    return str;
}

function find_last_multi_reading_panel_num() {
  var reading_num = $('form#multi_meter_readings > div.panel').last().attr('id');
  var num_regex = /^reading_panel_(\d+)/;
  var result = num_regex.exec(reading_num);
  //return a high number to avoid conflicting id's on server
  return (result === null) ? "10001" : parseInt(result[1])+1;
}

//dynamic add and remove content sections
function remove_multi_reading_field(link) {
  if ($('form#multi_meter_readings > div.panel').length > 1) {
    //remove the last panel
    $('form#multi_meter_readings > div.panel').last().remove();
  }
  var num_panels = $('form#multi_meter_readings > div.panel').length;
  if (num_panels == 1) { $(link).hide(); }
  if (num_panels < 10) { $(link).prev().show(); }
}

function add_multi_reading_field(link, regex, content) {
  var replace_num = find_last_multi_reading_panel_num();
  if (replace_num <= 10) {
    var new_id = new Date().getTime();
    var regexp = new RegExp("FINDME", "g");
    $(link).parent().before(content.replace(regexp, replace_num));
    //rebind any click events in the parent div
    var new_panel = $('form#multi_meter_readings > div.panel').last();
    $("img#arrow_up", new_panel).click(function() {
      $("div#reading_comment_"+replace_num).hide();
    });
    $("img#arrow_down", new_panel).click(function() {
      $("div#reading_comment_"+replace_num).show();
    });
  }
  //hide / show the add revmove links
  if (replace_num == 10) { $(link).hide(); }
  if (replace_num > 0) { $(link).next().show(); }
}

function capitalizeMe(str) {
  val = str;
  newVal = '';
  val = val.split(' ');
  for(var c=0; c < val.length; c++) {
    newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + ' ';
  }
  return newVal;
}

function addReportMissingYearsNote(note) {
  $("p#report-missing-year-note").html(note);
}

populateCusumTable = function() {
  //only process if we are on a page that will use this and we havent set it before
  if (charts.cusum.ajax_called === undefined && $('div.building').length > 0 && $('#cusum-table').children().size() == 0) {
    charts.cusum.ajax_called = true;
    metadata = $('div.building').metadata();
    $.ajax({
        type: "GET",
        url: '/buildings/populate_cusum_table/' + metadata.building_id + '?' + 'business_id=' + metadata.business_id + '&format=js',
        dataType: 'html',
        success: function(result){
            charts.cusum.ajax_called = false;
            if (result == "") {
              $('#cusum-table').html("<div></div>");
            } else {
              $("#cusum-table").html(result);
              //cusum table controls
              if ($('form.toggle-cusum-type').length != 0) {
                $("th input[name='cusum-options']").bind('click', function() {
                if (this.value == 'heating') {
                  $('table.cusum-heating').show();
                  $('table.cusum-cooling').hide();
                  $('#cooling-dd-label').hide();
                  $('#heating-dd-label').show();
                } else {
                  $('table.cusum-cooling').show();
                  $('table.cusum-heating').hide();
                  $('#heating-dd-label').hide();
                  $('#cooling-dd-label').show();
                }
              });
            }
          }
        },
        error: function(XMLHttpReq, textStatus, errorThrown) {
         charts.cusum.ajax_called = false;
       }
    });
  }
};

populateSnapshotHTML = function() {
  //only process if we are on a page that will use this and we havent set it before
  if ($('div.building').length > 0 && $('#snapshot_html').children().size() == 1) {
    metadata = $('div.building').metadata();
    $('#snapshot-loader').show();
    $.ajax({
        type: "GET",
        url: '/buildings/populate_snapshot_data/' + metadata.building_id + '?' + 'business_id=' + metadata.business_id + '&format=js',
        dataType: 'html',
        success: function(result){
          $('#snapshot-loader').hide();
          if (result != "") {
            $("#snapshot_html > div[id^=this]").html(result);
            //setup the click functions for the snapshot
            $("form input[type='radio'][name^='this-week'].toggle").bind('click', function() {
              var notChecked = $("input[name='"+this.name+"']:not(:checked)");
              for (var i = 0; i < notChecked.length; i++) {
                $("div#"+$(notChecked[i]).val()).hide();
              }
              var checked = $("input[name='"+this.name+"']:checked");
              var this_week_label = $("a[href^='#this-week'] span").text().split(" ");
              for (var i = 0; i < checked.length; i++) {
                $("div#"+$(checked[i]).val()).show();
                $("a[href^='#this-week'] span").text(this_week_label[0]+' '+$(checked[i]).next('label').text());
              }
              return true;
            });
            // do i have to set the result to nothing? NO Summary form?
            // $('#snapshot_html').html("<div></div>");
          }
        },
        error: function(XMLHttpReq, textStatus, errorThrown) {
          $('#snapshot-loader').hide();
          // do i have to set the result to nothing? NO Summary form?
          // $('#snapshot_html').html("<div></div>");
       }
    });
  }
};

populatePerformanceLineStatsHTML = function(type) {
  //only process if we are on a page that will use this and we havent set it before
  if ($('div.building').length > 0 && $('#performance-line-'+type+'-stats').children().size() == 0) {
    metadata = $('div.building').metadata();
    // $('#snapshot-loader').show();
    $.ajax({
        type: "GET",
        url: '/buildings/populate_performance_line_stats/' + metadata.building_id + '?' + 'business_id=' + metadata.business_id + '&type='+type+'&format=js',
        dataType: 'html',
        success: function(result){
          // $('#snapshot-loader').hide();
          if (result != "") {
            $('#performance-line-'+type+'-stats').html(result);
            // do i have to set the result to nothing? NO Summary form?
            // $('#snapshot_html').html("<div></div>");
          }
        },
        error: function(XMLHttpReq, textStatus, errorThrown) {
          // $('#snapshot-loader').hide();
          // do i have to set the result to nothing? NO Summary form?
          // $('#snapshot_html').html("<div></div>");
       }
    });
  }
};

function populateReportData(year_of_interest, financial_year) {
  //only process if we are on the building / business show page
  if ($("div#report").length > 0) {
    var report_type = 'building';
    // var report_div = undefined;
    if ($('div.business').length > 0) { report_type = 'business'; }
    //disble the button until we get a response
    $("button#get_report_data", $("div#report")).attr('disabled', 'disabled');
    $("span#load_report_data", $("div#report")).show();
    //show the loading images only on first load attempt
    if ($("[id$=summary-table-data]").children().size() === 0) {
      $('[id$=summary-report-loader]').show();
      $('[id$=annual-report-loader]').show();
    }
    var url = '';
    var metadata = $('div.'+report_type).metadata();
    if ($('div.business').length > 0) {
      url = '/businesses/populate_report_data/' + metadata.business_id + '?' +'&format=js';
    } else {
      url = '/buildings/populate_report_data/' + metadata.building_id + '?' + 'business_id=' + metadata.business_id + '&format=js';
    }
    if (year_of_interest === undefined && financial_year === undefined) {
      financial_year = $("input[name=year-type]:radio:checked", $("div#report")).val();
      year_of_interest = (financial_year === 1) ? $("select#fin_report_year", $("div#report")).val() : $("select#cal_report_year", $("div#report")).val();
    }
    //get the form values and submit with these
    url = url + "&year_of_interest="+year_of_interest+"&financial_year="+financial_year;
    $.ajax({
      type: "GET",
      url: url,
      dataType: 'html',
      success: function(result){
        if ($("[id$=summary-table-data]").children().size() === 0) {
          $('[id$=summary-report-loader]').hide();
          $('[id$=annual-report-loader]').hide();
        }
        if (result != "") {
          //need to split the data sets into their respective HTML tabs
          if ($('div.building').length > 0) {
            results = result.split("<!-- SPLIT -->");
            $("#summary-table-data").html(results[0]);
            $("#annual-report-data").html(results[1]);
            resizeReportDivs();
          } else {
            $("[id$=summary-table-data]").html(result);
            //wire up the show / hide business buildings details buttons
            $("img.building-detail", $("table.business-report")).click(function() {
              //show / hide the rows with this id.
              $("tr#"+this.id).toggle();
            });
          }
        }
        //enable the report req button and hide the loading label
        $("button#get_report_data", $("div#report")).removeAttr('disabled');
        $("span#load_report_data", $("div#report")).hide();
      },
      error: function(XMLHttpReq, textStatus, errorThrown) {
        if ($("[id$=summary-table-data]").children().size() === 0) {
          $('[id$=summary-report-loader]').hide();
          $('[id$=annual-report-loader]').hide();
        }
        //enable the report req button and hide the loading label
        $("button#get_report_data", $("div#report")).removeAttr('disabled');
        $("span#load_report_data", $("div#report")).hide();
      }
    });
  }
};

//shrink DE analysis layout when no heating source is set
function shrinkAnalysisDiv() {
  // resize the containing div
  $("#analysis-de").height($(".snapshot-de").height() + $(".building-de").height() + 40);
};

//resize the report div based on the inner HTML
function resizeReportDivs() {
  if ($("div#report").length > 0) {
    if ($("div.summary-table").length > 0) {
      var selectors_height = $("div#report > div.year-boundary").height();
      var summary_table_height = $("#summary-table-data").height();
      var annual_report_height = Math.max($("div[class^=building-report]").height(), $("div#annual-report-data").height());
      $("div#summary-table").height((selectors_height + summary_table_height)*1.025);
      $("div#annual-report").height((selectors_height + annual_report_height)*1.025);
      var report_tabs_height = $('#report-tabs').height();
      $("div#report").height((selectors_height + report_tabs_height)*1.025);
    }
  }
};

function checkPreviousValuesMultiReadings(panel_id, meter_id, this_reading, back_url) {
  var url = '/meter_readings/previous_reading.js?meter_id='+ meter_id;
  $.ajax({
    type: "GET", url: url, dataType: 'json',
    success: function(result) {
      //hide the ajax notify div
      $('form#multi_meter_readings > div.panel#'+panel_id+' > div#reading_check').remove();
      var element = $('form#multi_meter_readings > div.panel#'+panel_id+' > [id$=_meter_id]');
      //enable the form buttons again
      $('form#multi_meter_readings > p.submit > input#meter_readings_submit').removeAttr('disabled');
      $('form#multi_meter_readings > p.submit > span > a').attr("href", back_url);
      if (result !== null && this_reading < result.reading) {
        //set the panel invalid field
        $('form#multi_meter_readings > div.panel#'+panel_id+' > span[id^=valid-meter-reading-]').attr("title", 'invalid');
        //indicate which reading panel is correct / incorrect
        $('<div id="reading_check" style="float:right"><img src="/images/icons/red_cross.png" style="position:relative;top:5px;padding-left:1.5em" title="The value of this reading is smaller than the last reading for this meter, please check your reading." alt="value incorrect"/></div>').insertAfter(element);
        $("#dialog-multi-readings-confirm").dialog('open');
      } else {
        //set the panel valid field
        $('form#multi_meter_readings > div.panel#'+panel_id+' > span[id^=valid-meter-reading-]').attr("title", 'valid');
        $('<div id="reading_check" style="float:right"><img src="/images/icons/green_tick.png" style="position:relative;top:5px;padding-left:1.5em" title="This reading value is ok!" alt="value ok"/></div>').insertAfter(element);
        var all_panels_valid = false;
        //only resubmit the form if we have processed the last panel
        jQuery.each($('form#multi_meter_readings > div.panel'), function(index, value) {
          var valid_field = $('span[id^=valid-meter-reading-]', this).attr("title");
          //set the field to testing for each panel -- used in AJAX callback
          if (valid_field == "testing" || valid_field == "invalid") {
            all_panels_valid = false;
            //break testing of each panel
            return false;
          } else if (valid_field == "valid") {
            all_panels_valid = true;
            return true;
          }
        });
        //if all panels have been tested and pass then submit the form by skipping our submit handler
        if (all_panels_valid) { $('form#multi_meter_readings')[0].submit(); }
      }
    },
    error: function() {
      $('form#multi_meter_readings > div.panel#'+panel_id+' > div#reading_check').remove();
      //enable the form buttons again
      $('form#multi_meter_readings > p.submit > input#meter_readings_submit').removeAttr('disabled');
      $('form#multi_meter_readings > p.submit > span > a').attr("href", back_url);
      //something went wrong - so let the server take care of it and unbind the submit handler
      $('form#multi_meter_readings').unbind('submit');
      if ($('form#multi_meter_readings > input#validation_error').val() == "0") {
        $('form#multi_meter_readings > input#validation_error').val("1");
        $('form#multi_meter_readings')[0].submit();
      }
    }
  });
}

function checkLastReading(meter_id, this_reading_id, back_url) {
  if ($('div#reading_check').length === 0) {
    //notify the user that something is going on
    var element = $('[id$=meter_reading_meter_id]');
    $('<div id="reading_check" style="display:inline"><img src="/images/small_loader.gif" style="position:relative;top:5px;padding-left:1.5em;height:22px;opacity:0.4;filter:alpha(opacity=40)" alt="checking reading validity"/><span class="note">Checking the new readings against known readings</span></div>').insertAfter(element);
  }
  url = '/meter_readings/previous_reading.js?meter_id='+ meter_id;
  if (this_reading_id !== "") { url = url.concat('&this_reading_id='+ this_reading_id); }
  $.ajax({
    type: "GET", url: url, dataType: 'json',
    success: function(result) {
      //hide the ajax notify div
      $('div#reading_check').remove();
      var this_reading = $('input#[id$=meter_reading_reading]').val();
      if (result !== null && this_reading < result.reading) {
        //enable the form buttons again
        $('input[type=submit][id$=meter_reading_submit]').removeAttr('disabled');
        $('p.submit > span > a').attr("href", back_url);
        //handle the case of possible roll over
        $("#dialog-confirm").dialog('open');
      } else {
        //allow the user to submit the form
        $('div#valid-meter-reading > span').attr('title', 'valid');
        $('form[class$=meter_reading]').submit();
      }
    },
    error: function() {
      $('div#reading_check').remove();
      //something went wrong - so let the server take care of it.
      $('div#valid-meter-reading > span').attr('title', 'valid');
      $('form[class$=meter_reading]').submit();
    }
  });
}

//helper function to get the edit meter reading form id
function get_meter_reading_form_id() {
  var form_id = "";
  if ($("form[id^=edit]").length > 0) { form_id = $("form[id^=edit]")[0].id; }
  var id_regex = /^edit_.+_(\d+)/;
  var result = id_regex.exec(form_id);
  return (result === null) ? "" : result[1];
}

function switchZoomWeekSelect(zoom_or_week) {
  if (zoom_or_week) {
    $('#zoom_datepickers').hide();
    $('#week_select_datepicker').show();
  } else {
    $('#zoom_datepickers').show();
    $('#week_select_datepicker').hide();
  }
}
