/*
 * Initial constants
 *
*/
var ExchangeRate = 0.72;

var AudioData_Server_Ratio_Audio = 0.5;
var AudioData_Server_Ratio_Data = 1 - AudioData_Server_Ratio_Audio;

var AudioDataVid_Hosting_Ratio_Audio = 0.35;
var AudioDataVid_Hosting_Ratio_Data = 0.333;
var AudioDataVid_Hosting_Ratio_Video = 1 - (AudioDataVid_Hosting_Ratio_Audio + AudioDataVid_Hosting_Ratio_Data);

var Average_Hosting_Price = 0;		// calculated when hosting table is setup

var BenefitResult = 0; // the original benefit result which is calculated and used for the chart


function roi_load()
{
	var results_container = document.getElementById("results_container");
	results_container.style.display = "none";
	
	
	/***** TEMPORARY: SET DEFAULT VALUES ********/
	txtNumUsers = document.getElementById("txtNumUsers");
	txtMeetPerWeek = document.getElementById("txtMeetPerWeek");
	txtAttendees= document.getElementById("txtAttendees");
	txtPercentageAtt = document.getElementById("txtPercentageAtt");
	txtAvgCostCurrent = document.getElementById("txtAvgCostCurrent");
	txtAvgCostTravel = document.getElementById("txtAvgCostTravel");
	txtAvgLostTime = document.getElementById("txtAvgLostTime");
	txtAvgCostTime = document.getElementById("txtAvgCostTime");
	txtAvgDuration = document.getElementById("txtAvgDuration");
	txtEstNumConverted = document.getElementById("txtEstNumConverted");
	
	txtNumUsers.value = 250;
	txtMeetPerWeek.value = 100;
	txtAttendees.value = 3;
	txtPercentageAtt.value = 10;
	txtAvgCostCurrent.value = 100;
	txtAvgCostTravel.value = 75;
	txtAvgLostTime.value = 1;
	txtAvgCostTime.value = 90;
	txtAvgDuration.value = 1;
	txtEstNumConverted.value = 25;
	/******** END OF TEMPORARY ASSIGNMENT **********/

}

/*
 * Function: frmOrgChanges
 * Description: handles changes made to the "Your Organisation" section of the form, recalculating
 * 				results based on these values.
*/
function frmOrgChanges()
{
	var txtNumUsers = document.getElementById("txtNumUsers");
	var txtMeetPerWeek = document.getElementById("txtMeetPerWeek");
	var txtAttendees= document.getElementById("txtAttendees");
	var txtPercentageAtt = document.getElementById("txtPercentageAtt");
	var txtAvgCostCurrent = document.getElementById("txtAvgCostCurrent");
	var txtAvgCostTravel = document.getElementById("txtAvgCostTravel");
	var txtAvgLostTime = document.getElementById("txtAvgLostTime");
	var txtAvgCostTime = document.getElementById("txtAvgCostTime");
	var txtAvgDuration = document.getElementById("txtAvgDuration");
	var txtEstNumConverted = document.getElementById("txtEstNumConverted");

	var results_container = document.getElementById("results_container");

	var lblNumAttendees = document.getElementById("lblNumAttendees");
	var lblNumTrips = document.getElementById("lblNumTrips");
	var lblReductionExpenses = document.getElementById("lblReductionExpenses");
	var lblHoursGained = document.getElementById("lblHoursGained");
	var lblIncProd = document.getElementById("lblIncProd");
	var lblTotalBenefit = document.getElementById("lblTotalBenefit");

	var hdnNumAttendees = document.getElementById("hdnNumAttendees");
	var hdnNumTrips = document.getElementById("hdnNumTrips");
	var hdnReductionExpenses = document.getElementById("hdnReductionExpenses");
	var hdnHoursGained = document.getElementById("hdnHoursGained");
	var hdnIncProd = document.getElementById("hdnIncProd");
	var hdnTotalBenefit = document.getElementById("hdnTotalBenefit");

	var lblSuggestAudio = document.getElementById("lblSuggestAudio");
	var lblSuggestDataPort = document.getElementById("lblSuggestDataPort");
	var lblSuggestDataUser = document.getElementById("lblSuggestDataUser");

	var regExp = /^[-]?[0-9.]+$/;	// positive/negative floating point numbers

	/// Validation data entry and clear results if invalid
	if(!regExp.test(txtNumUsers.value) || txtNumUsers.value.length == 0
		 || !regExp.test(txtMeetPerWeek.value) || txtMeetPerWeek.value.length == 0
		 || !regExp.test(txtAttendees.value) || txtAttendees.value.length == 0 
		 || !regExp.test(txtPercentageAtt.value) || txtPercentageAtt.value.length == 0
		 || !regExp.test(txtAvgCostCurrent.value) || txtAvgCostCurrent.value.length == 0
		 || !regExp.test(txtAvgCostTravel.value) || txtAvgCostTravel.value.length == 0
		 || !regExp.test(txtAvgLostTime.value) || txtAvgLostTime.value.length == 0
		 || !regExp.test(txtAvgCostTime.value) || txtAvgCostTime.value.length == 0
		 || !regExp.test(txtAvgDuration.value) || txtAvgDuration.value.legnth == 0
		 || !regExp.test(txtEstNumConverted.value))
	{
		ClearResults(lblNumAttendees, lblNumTrips, lblReductionExpenses, lblHoursGained, lblIncProd, lblTotalBenefit,
					 lblSuggestAudio, lblSuggestDataPort, lblSuggestDataUser);
		results_container.style.display = "none";

		return;
	}
	


	var numAttendees = txtMeetPerWeek.value * (txtPercentageAtt.value)/100 * txtAttendees.value;
	var numTripsReduced = numAttendees * (txtEstNumConverted.value/100);
	var reducedExpenses = numTripsReduced * txtAvgCostTravel.value;
	var hoursProductivityGain = numTripsReduced * txtAvgLostTime.value;
	var productivityGain = hoursProductivityGain * txtAvgCostTime.value;
	var totalBenefit = parseInt(txtAvgCostCurrent.value) + reducedExpenses + productivityGain;
	
	// set the labels and hidden field vales for the results. The hidden fields will be used by the PHP email script
	lblNumAttendees.innerHTML = hdnNumAttendees.value = addCommas(Math.round(numAttendees));
	lblNumTrips.innerHTML = hdnNumTrips.value = addCommas(Math.round(numTripsReduced));
	lblReductionExpenses.innerHTML = hdnReductionExpenses.value = "$" + addCommas(Math.round(reducedExpenses));
	lblHoursGained.innerHTML = hdnHoursGained.value = addCommas(Math.round(hoursProductivityGain));
	lblIncProd.innerHTML = hdnIncProd.value = "$" + addCommas(Math.round(productivityGain));
	
	BenefitResult = totalBenefit;
	lblTotalBenefit.innerHTML = hdnTotalBenefit.value = "$" + addCommas(Math.round(BenefitResult));


	/* calculate the suggested quantities for audio, data and video units */
	var suggestedAudio = evenNumber(Math.ceil(numAttendees / 7));
	var suggestedDataPort = evenNumber(Math.ceil(numAttendees / 7));
	var suggestedDataUser = evenNumber(Math.ceil(numAttendees));

	lblSuggestAudio.innerHTML = suggestedAudio;
	lblSuggestDataPort.innerHTML = suggestedDataPort;
	lblSuggestDataUser.innerHTML = suggestedDataUser;

	// run the results calculations
	CalculationsAndChart();

}

/*
 * Function: ClearResults
 * Description: clear the values of all the results fields
*/
function ClearResults(lblNumAttendees, lblNumTrips, lblReductionExpenses, lblHoursGained, lblIncProd,
					  lblTotalBenefit, lblSuggestAudio, lblSuggestDataPort, lblSuggestDataUser)
{
	lblNumAttendees.innerHTML = "";
	lblNumTrips.innerHTML = "";
	lblReductionExpenses.innerHTML = "";
	lblHoursGained.innerHTML = "";
	lblIncProd.innerHTML = "";
	lblTotalBenefit.innerHTML = "";		
	
	lblSuggestAudio.innerHTML = "";		
	lblSuggestDataPort.innerHTML = "";		
	lblSuggestDataUser.innerHTML = "";		
}
 

/*
 * Function: CalculationsAndChart
 * Description: handles changes made to the selected quanities for audio, video and and data, triggering the recalculation
 * 				of the resulting chart, and then plotting the chart
*/
function CalculationsAndChart()
{
	
	VOIP_Gateway_Channels = Create_VOIP_Gateway_Channels();
	VOIP_Gateway_Boards = Create_VOIP_Gateway_Boards();
	VOIP_Gateway_VX1200s = Create_VOIP_Gateway_VX1200s();

	Audio_OR_Data_Ports = Create_Audio_OR_Data_Ports();
	
	// Note: the following array should be used for populating the selection dropdown list for Contract Term
	Contract_Terms = Create_Contract_Terms();	

	Hosting_Costs = Create_Hosting_Costs();
	Hosting_Support_Total_Month = Calculate_Hosting_Support_Total_Month(Hosting_Costs);
	
	
	Video_Ports_Scopia = Create_Video_Ports_Scopia();
	Video_Ports_Neogate = Create_Video_Ports_Neogate();
	
	Dell_Server_x2s = Create_Dell_Server_x2();
	
	VOIP_Medians = Create_VOIP_Medians(VOIP_Gateway_Channels, VOIP_Gateway_Boards, VOIP_Gateway_VX1200s);
	
	OXE_vs_VX_TCO = Create_OXE_vs_VX_TCO(VOIP_Gateway_Channels, VOIP_Gateway_VX1200s);
	
	Channels_120_Over_6years = Create_Channels_120_Over_6years(VOIP_Gateway_Channels, VOIP_Gateway_VX1200s);
	
	// The following table in the ROI spreadsheet isn't used so leaving it out for now
	// Old_Monthly_Values = Create_Old_Monthly_Values();
	
	Audio_Data_IM_RTUs = Create_Audio_Data_IM_RTUs();
	Video_RTUs = Create_Video_RTUs();

	// Note: only the Median is used in the following table at the time of writing this code, but will still store the rest
	// of the information in case it is wanted in the future
	Teamwork_Unit_Costs = Create_Teamwork_Unit_Costs(Dell_Server_x2s, VOIP_Gateway_VX1200s, Audio_OR_Data_Ports,
													 Video_Ports_Scopia, Video_Ports_Neogate, Audio_Data_IM_RTUs, Video_RTUs);

	Average_Costs_Port_User = Create_Average_Costs_Port_User(Teamwork_Unit_Costs);
	
	Hosting_Costs_Per_Unit = Create_Hosting_Costs_Per_Unit(Hosting_Support_Total_Month);

	var ContractTerm = parseInt(document.getElementById('selContractTerm').options[document.getElementById('selContractTerm').selectedIndex].value);

	End_User_Variables = Create_End_User_Variables();

	End_User_Sell_Price = Create_End_User_Sell_Price(End_User_Variables, ContractTerm);
	
	var lblTotalBenefit = document.getElementById("lblTotalBenefit");
	// trip out any monetary figures or commas
	
	Cost_Vs_Revenue = Create_Cost_Vs_Revenue(VOIP_Gateway_VX1200s, Audio_OR_Data_Ports, Video_Ports_Scopia, Video_Ports_Neogate,
								Audio_Data_IM_RTUs, Video_RTUs, BenefitResult, ContractTerm, Hosting_Support_Total_Month);
	
	Net_Benefits_Series = Create_Net_Benefits_Series(Cost_Vs_Revenue);
	
	
	var xdata = GetColumnIntoArray(Net_Benefits_Series, 0);
	var ydata = GetColumnIntoArray(Net_Benefits_Series, 1);
	var hdnBenefitsArrayXdata = document.getElementById("hdnBenefitsArrayXdata");
	var hdnBenefitsArrayYdata = document.getElementById("hdnBenefitsArrayYdata");
	hdnBenefitsArrayXdata.value = js_array_serialize(xdata);
	hdnBenefitsArrayYdata.value = js_array_serialize(ydata);

	// plot the results
	jQuery("#results_container").show();
	jQuery("#chart_placeholder").show();

	jQuery.plot($("#chart_placeholder"), [ Net_Benefits_Series ], {
										  xaxis: {
											  ticks: [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72],
											  min: 0
											  },
										  lines: {
											Color: { colors: ["#0070C0"] }
										  }
										  });
}

/* 
 * Function: js_array_serialize
 * Description: Converts a javascript array to a string in PHP serialized format.
 * This is useful for passing arrays to PHP. On the PHP side you can 
 * unserialize this string from a cookie or request variable. For example,
 * assuming you used javascript to set a cookie called "php_array"
 * to the value of a javascript array then you can restore the cookie 
 * from PHP like this:
 *    <?php
 *    session_start();
 *    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
 *    print_r ($my_array);
 *    ?>
 * This automatically converts both keys and values to strings.
 * The return string is not URL escaped, so you must call the
 * Javascript "escape()" function before you pass this string to PHP.
*/
function js_array_serialize (inArray)

{
    var array_php = "";
    var total = 0;
    for (var key in inArray)
    {
        ++ total;
        array_php = array_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(inArray[key]).length + ":\"" + String(inArray[key]) + "\";";
    }
    array_php = "a:" + total + ":{" + array_php + "}";
    return array_php;
}

