var selectedDay = -1;
var monthData = null;

function showCalendarLoading() {
  $("#calMonthTable").html("<div id=\"calBusyWait\"><img src=\"http://www.yousustain.com/img/busy_wait2.gif\"><br/>Loading</div>");
}

function buildCalendar(month) {
  $("#calMonth").html(month.month_name + " " + month.year);

  var table = document.getElementById("calMonthTable");
  var curDayIndex = -1;
  var sHtml = "<table cellpadding=\"0\" cellspacing=\"0\">";
  sHtml += "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>";
  for (var i = 0; i < 42; ++i) { 
    var dow = (i % 7);

    // See if we have a current day
    if (curDayIndex == -1) {
      if (dow == month.days[0].dayOfWeek) {
        curDayIndex = 0;
      }
    }

    if (dow == 0) {
      sHtml += "<tr";
      if (Math.floor(i / 7) == 5) {
        sHtml += " id=\"calBottomRow\"";
      }
      sHtml += ">";
    }

    if (curDayIndex >= 0 && curDayIndex < month.days.length) {
      var d = month.days[curDayIndex];

      sHtml += "<td id=\"calDay" + curDayIndex + "\" class=\"calDayActive";
      if (dow == 6) {
        sHtml += " calRightCol";
      }
      if (d.distance > 0) {
        sHtml += " calDayValue";
      }
      sHtml += "\"";
      sHtml += " onclick=\"dayClick(" + curDayIndex + ")\"";
      sHtml += "><div class=\"calDayDate\">" + d.day + "</div><div id=\"calDay" + curDayIndex + "Distance\" class=\"calDayDistance\">" + (d.distance > 0 ? d.distance : "")  + "</div></td>";
      curDayIndex++; 
    } else {
      sHtml += "<td class=\"calDayInactive";
      if (dow == 6) {
        sHtml += " calRightCol";
      }
      sHtml += "\">&nbsp;</td>";
    }

    if (dow == 6) {
      sHtml += "</tr>";
    }
  }
  sHtml += "</table>";
  table.innerHTML = sHtml;
}

function dayClick(iDayIndex) {
  $("#calDaySaveStatus").html("");
  if (selectedDay > -1) {
    // Revert previously selected cell
    $("#calDay" + selectedDay).removeClass("calDaySelected");
  }

  if (iDayIndex != selectedDay) {
    var day = monthData.days[iDayIndex];
    $("#calDay" + iDayIndex).addClass("calDaySelected");
    selectedDay = iDayIndex;
    
    $("#calDayInputDateSpan").html(day.day);
    $("#calDayInputDate").css("background-image", "url(" + websiteRoot + "/img/calendar/" + monthData.month_name.substring(0, 3).toLowerCase() + ".gif)");
    $("#calDayInputDate").css("background-position", "top left");
    $("#calDayInputDate").css("background-repeat", "no-repeat");

    $("#calDayInputDistance").val(day.distance);
 
    // find which trips option to select
    var trips = document.getElementById("calDayRoundTrips");
    if (day.trips > 0) {
        for (var i = 0; i < trips.options.length; i++) {
            var opt = trips.options[i];
            if (opt.value == day.trips) {
                opt.selected = true;
            }
        }
    } else {
        trips.options[1].selected = true;
    }

    $("#calDayInput").slideDown();
  } else {
    selectedDay = -1;
    $("#calDayInput").slideUp();
  }
}

function dayMouseover() {
}

function dayMouseout() {
}

function showDayDistance(iDayIndex) {
  var day = monthData.days[iDayIndex];
  day.distance = $("#calDayInputDistance").val();
  if (day.distance > 0) {
    $("#calDay" + iDayIndex + "Distance").html(day.distance);
  } else {
    $("#calDay" + iDayIndex + "Distance").html("");
  }

  if (day.distance > 0 && !$("#calDay" + iDayIndex).hasClass("calDayValue")) {
    $("#calDay" + iDayIndex).addClass("calDayValue");
  } else if (day.distance == 0 && $("#calDay" + iDayIndex).hasClass("calDayValue")) {
    $("#calDay" + iDayIndex).removeClass("calDayValue");
  }
}

function previousMonth() {
  if (ajaxPending || monthData == null) {
    return;
  }
  var prevYear = monthData.year;
  var prevMonth = monthData.month_number - 1;
  if (prevMonth < 1) {
    prevMonth = 12;
    prevYear--;
  }
  
  selectedDay = -1;
  $("#calDayInput").hide();

  getMonthData(prevYear, prevMonth);  
}

function nextMonth() {
  if (ajaxPending || monthData == null) {
    return;
  }
  var nextYear = monthData.year;
  var nextMonth = monthData.month_number + 1;
  if (nextMonth > 12) {
    nextMonth = 1;
    nextYear++;
  }

  selectedDay = -1;
  $("#calDayInput").hide();
  
  getMonthData(nextYear, nextMonth);  
}

function getMonthData(iYear, iMonth) {
  ajaxPending = true;
  var url = "http://www.yousustain.com/ajax/tread_load_month.php";
  if (iYear != null && iMonth != null) {
    url += "?year=" + iYear + "&month=" + iMonth;
  }
  showCalendarLoading();
  $.getJSON(url, function(json) {
              monthData = json;
              buildCalendar(monthData);
              showTotals();
              ajaxPending = false;
              });
}

function saveDay() {
  ajaxPending = true;
  $("#calDaySaveStatus").html("<img src=\"http://www.yousustain.com/img/busy_wait_small.gif\"/> Saving");

  var dayIndex = selectedDay;
  var distance = $("#calDayInputDistance").val();
  var trips = $("#calDayRoundTrips").val();
  if (distance == 0) {
      trips = 0;
  }

  // Input validation
  if (distance < 0) {
      alert("Please enter a distance of zero or more");
      $("#calDaySaveStatus").html("<img src=\"http://www.yousustain.com/img/icon_error.gif\"/> Distance too low");
      return;
  }
  if (distance > 10000) {
      alert("Please enter a reasonable days distance");
      $("#calDaySaveStatus").html("<img src=\"http://www.yousustain.com/img/icon_error.gif\"/> Distance too large");
      return;
  }

  var sUrl = "http://www.yousustain.com/ajax/tread_save_day.php?year=" + monthData.year + "&month=" + monthData.month_number + "&day=" + (dayIndex+1) + "&distance=" + distance + "&trips=" + trips;

  $.ajax({
      url: sUrl,
      type: 'GET',
      dataType: 'html',
      timeout: 10000,
      error: function(request, errMsg, errObj) {
          $("#calDaySaveStatus").html("<img src=\"http://www.yousustain.com/img/icon_error.gif\"/> Error Saving");
      },
      success: function(html){
          $("#calDaySaveStatus").html("<img src=\"http://www.yousustain.com/img/icon_tick.gif\"/> Success!");

          // Update the totals
          var distanceDelta = distance - monthData.days[dayIndex].distance;
          var tripsDelta = trips - monthData.days[dayIndex].trips;
          monthData.month_distance += distanceDelta;
          monthData.month_trips += tripsDelta;
          monthData.total_distance += distanceDelta;
          monthData.total_trips += tripsDelta;

          monthData.days[dayIndex].distance = distance;
          monthData.days[dayIndex].trips = trips;
          showDayDistance(dayIndex);
          showTotals();

          ajaxPending = false;
          $("#calDay" + selectedDay).removeClass("calDaySelected");
          selectedDay = -1;
          $("#calDayInput").slideUp(1500);
      }
  });
}

function showTotals() {
    // kg CO2 per km == 0.28
    // Calories per km == 21.875
    // Cold-car penalty: 40% more pollution (not CO2) for first 3.2km (same as adding 1.28km per trip)
    var co2PerKM = 0.28;
    var cashSavingsPerKM = 0.1125;
    var cashSavingsPerColdKM = 0.075; // additional
    var caloriesPerKM = 21.875;

    var unitsConversion = 1;
    var massConversion = 1;
    if (distanceUnits == "miles") {
        unitsConversion = 1.6;
        massConversion = 2.2;
    }

    $("#calMonthDistance").text(monthData.month_distance);
    var monthCO2 = monthData.month_distance * unitsConversion * massConversion * co2PerKM;
    $("#calMonthCO2").text(monthCO2.toFixed(0));
    var monthCalories = monthData.month_distance * unitsConversion * caloriesPerKM;
    $("#calMonthCalories").text(monthCalories.toFixed(0));
    // Approximation of cold penalty
    var monthColdDistance = monthData.month_trips * 3.2;
    if (monthColdDistance > monthData.month_distance * unitsConversion) {
        monthColdDistance = monthData.month_distance * unitsConversion;
    }
    var monthCash = (monthData.month_distance * unitsConversion * cashSavingsPerKM) + (monthColdDistance * cashSavingsPerColdKM);
    $("#calMonthCash").text(monthCash.toFixed(2));

    $("#calTotalDistance").text(monthData.total_distance);
    var totalCO2 = monthData.total_distance * unitsConversion * massConversion * co2PerKM;
    $("#calTotalCO2").text(totalCO2.toFixed(0));
    var totalCalories = monthData.total_distance * unitsConversion * caloriesPerKM;
    $("#calTotalCalories").text(totalCalories.toFixed(0));
    // Approximation of cold penalty
    var totalColdDistance = monthData.total_trips * 3.2;
    if (totalColdDistance > monthData.total_distance * unitsConversion) {
        totalColdDistance = monthData.total_distance * unitsConversion;
    }
    var totalCash = (monthData.total_distance * unitsConversion * cashSavingsPerKM) + (totalColdDistance * cashSavingsPerColdKM);
    $("#calTotalCash").text(totalCash.toFixed(2));
}
