/**
--------------------------------------------------------------------------------------------+
@file Script: commute.js
@author Robbie Liben, Cedar Mountain Software
@mainpage
    Create Date: 7/18/2011

Description:
    Javascript functionss to be used by the Missoula in Motion Commute module.

@Note Change Log:
   When       Who              What
   9/15/2011  Robbie Liben     Included correction for IE7 bug in how buttons are pressed
*--------------------------------------------------------------------------------------------+
*/
var CommuteTypes;
var UserInfo;
var ResponseArray;	// Array of items the user has clicked

jQuery(document).ready(function() {
	// Items to run as soon as the page is loaded
	getCommuteTypes();
	getUserInfo();
	$("#testNextButton").click(function() {commuteNext();});
	$("#backButton").click(function()     {commuteBack();});
	$("#submitButton").click(function()   {commuteSubmit();});
});

function commuteNext() {
/**	@Author Robbie Liben
	@Date	7/18/2011
	@Brief	*/
	//var Tables = document.CommuteTable;
	//var Radios = document.CommuteTable.To1309586400;
	var j = 0;
	var ReportSummary = new Array(CommuteTypes.length + 1)
	for (i = 0; i <= CommuteTypes.length + 1; i++) {
		ReportSummary[i] = 0;
	}
	ResponseArray = Array();
	$("#CommuteTable :radio").each(function(i) {
		if ($(this).attr("checked")) {  // For each radio button that's checked
										// Increment the value for its commute type
			ReportSummary[Number($(this).attr("value"))] += 1;
			if ($(this).attr("value") != "0") {	// Don't include the non-commute days in the response
				ResponseArray[j] = Array($(this).attr("name"), $(this).attr("value"));
				j += 1;
			}
		}
	});
	// Verify that the user has entered some sort of commute.
	CommuteCount = 0;
	for (i = 1; i <= CommuteTypes.length + 1; i++) {
		CommuteCount += ReportSummary[i];
	}
	if (CommuteCount == 0) {
		// The user has not checked any boxes
		alert("Please report at least one commute.");
	} else {
		var TotalTrips = 0;
		var TotalMiles = 0;
		var TotalCO2   = 0;
		for (i = 1; i <= CommuteTypes.length + 1; i++) {
			if (ReportSummary[i] == 0) {
				// The user reported no commutes of this type, so we hide this row
				$("#TypeRow" + i).hide();
			} else {
				// The user reported at least one commute of this type, so we show this row and display its stats
				$("#TypeRow" + i).show();
				$("#CellTrips" + i).html(ReportSummary[i]);
				$("#CellMiles" + i).html(formatNumber(ReportSummary[i] * UserInfo["Mileage"] / 2, 1) + ' miles');
				$("#CellCO2"   + i).html(formatNumber(ReportSummary[i] * UserInfo["Mileage"] * getCO2Savings(i) / 2, 2) + ' lbs.');
				TotalTrips += ReportSummary[i];
				TotalMiles += ReportSummary[i] * UserInfo["Mileage"];
				TotalCO2   += ReportSummary[i] * UserInfo["Mileage"] * getCO2Savings(i);
			}
		}
		$("#TotalTrips").html(TotalTrips);
		$("#TotalMiles").html(formatNumber(TotalMiles/2, 1) + ' miles');
		$("#TotalCO2"  ).html(formatNumber(TotalCO2/2, 2) + ' lbs.');
		// Now display the Next screen
		$("#CommuteTable").hide();
		$("#confirmBox").show();
	}
}

function commuteBack() {
/**	@Author Robbie Liben
	@Date	7/18/2011
	@Brief	*/
	$("#CommuteTable").show();
	$("#confirmBox").hide();
}

function commuteSubmit() {
/**	@Author Robbie Liben
	@Date	7/18/2011
	@Brief	Submits the user's commute report to the server*/
	$.ajax({
		type: "POST",
		url: "Commute/saveCommute",
		data: {"json_data": JSON.stringify(ResponseArray)},
		success: function(json_data) {
			$("#CommuteTable").hide();
			$("#confirmBox").hide();
			$("#CompleteBox").show();
			var results = jQuery.parseJSON(json_data);
			if (results['MilestoneCount'] > 0) {
				$("#MilestoneMessage").show();
				if (results['MilestoneCount'] == 1) {
					$("#MilestoneCount").html("another Milestone");
				} else {
					$("#MilestoneCount").html(results['MilestoneCount'] + " Milestones");
				}
				$("#MilestoneList").html(results['MilestoneList']);
			} else {
				$("#MilestoneMessage").hide();
			}
		},
		error: function() {
			alert('There was an error submitting your commute.\n\nPlease try again.');
		}
	})

}

function getCommuteTypes() {
	// Gets info from the database about a specific category. Loads it into an array
	$.ajax({
		type: "POST",
		url: "Commute/getCommuteTypes",
		data: {"empty": 0},
		success: function(json_data) {
			CommuteTypes = jQuery.parseJSON(json_data);

			j=3; // Debugging Code. Deleete this line.
 		},
		error: function(xhr, textSTatus, errorThrown) {
			alert('An AJAX error occurred: ErrorThrown: ' + errorThrouwn + ', xhr Status: ' + xhr.status + ', Text Status: ' + textSTatus);
		}
	}) 
	return;
}

function getUserInfo() {
	// Gets info from the database about a specific category. Loads it into an array
	$.ajax({
		type: "POST",
		url: "Commute/getUserInfo",
		data: {"empty": 0},
		success: function(json_data) {
			UserInfo = jQuery.parseJSON(json_data);
			j=3; // Debugging Code. Deleete this line.
 		},
		error: function(xhr, textSTatus, errorThrown) {
			alert('An AJAX error occurred: ErrorThrown: ' + errorThrouwn + ', xhr Status: ' + xhr.status + ', Text Status: ' + textSTatus);
		}
	}) 
	return;
}

function getCO2Savings (CommuteID) {
/**	@Author Robbie Liben
	@Date	7/20/2011
	@Brief	Given a CommuteType ID, returns the pounds of CO2 saved per mile for that type*/
	var CO2perMile = 0;
	for (var i = 0; i < CommuteTypes.length; i += 1) {
		if (CommuteTypes[i]['id'] == CommuteID) {
			CO2perMile = CommuteTypes[i]['co2Savings'];
			break;
		}
	}
	return CO2perMile;
}

function formatNumber(ThisNumber, DecimalPlaces) {
/**	@Author Robbie Liben
	@Date	7/20/2011
	@Brief	Input is a number. Out put is a string representation of the number formatted to DecimalPlaces*/
	var Zeros = '';
	for (var i = 1; i <= DecimalPlaces; i += 1) {
		Zeros += "0";
	}
	var WorkingNumber = Math.round(Math.pow(10, DecimalPlaces) * ThisNumber) / Math.pow(10, DecimalPlaces); // Does the rounding
	var WorkingString = WorkingNumber.toString();
	var strLen = WorkingString.length;
	var decimalPos = WorkingString.search(/\./);
	var digits = Math.abs(decimalPos - strLen) -1;
	if (decimalPos == -1) {  // decimal point not found
		WorkingString = WorkingString + '.' + Zeros;
	} else {
		WorkingString = WorkingString + Zeros.substr(0, DecimalPlaces - digits);
	}
	return WorkingString;
}

function setFrom(TheDate, commuteType) {
	$("input[name=F" + TheDate + "]").each(function(i) {
		// Search through the corresponding "from" radio buttons and 
		// check the one with the same value as the "to" radio button.
		if ($(this).attr("value") == commuteType) {
			$(this).attr("checked", true);
		}
	});
}
