﻿
addEvent(window, "load", InitCalculator);

onGetChartComplete = new Event();

var stateFormulaEnum =
        {
        	Gerr: 0,
        	Wyman: 1,
        	Crouch: 2
        }
var stateFormula = 0;

var ActiveTabKey = "HullType";

var lastDisplacementUnitType = 0;
var lastRequiredSpeedUnitType = 0;
var tabControl;

var hull = null;
var html = "";
var oldLwl = 0;
var tbDisplacement;
var tbDesiredSpeed;

var tbLWL;

function Hull() {
	this.ChartClientID = "";
	this.Chart = "";
	this.ButtockAngle = 2;
	this.MaxSLRatio = 1.34;
}

function ConversionHTML() {
	this.rbsLWL = "<b>Length at water line</b><div style=\"margin: 0 auto; width: 183px; text-align: center\"><input id=\"rbHullSpeedFeet\" type=\"radio\" checked=\"checked\" name=\"rbLWL\" value=\'1\' onclick=\"GetConversion('Distance',0, 1, tbLWL);\" />Decimal Feet <input id=\"rbHullSpeedMeters\" type=\"radio\" name=\"rbLWL\" value='0' onclick=\"GetConversion('Distance',1, 0, tbLWL);\" />Meters </div><br /><br />";
	this.rbsDisplacement = "<b>Displacement</b><div style=\"margin: 0 auto; width: 240px; text-align: center\"><input id=\"rbDLRatioPounds\" type=\"radio\" checked=\"checked\" name=\"rbDisplacement\" value=\'0\' onclick=\"DisplacementGetConversion(0);\" />Pounds<input id=\"rbDLRatioKilograms\" type=\"radio\" name=\"rbDisplacement\" value='1' onclick=\"DisplacementGetConversion(1);\" />Kilograms<input id=\"rbDLRatioShortTon\" type=\"radio\" name=\"rbDisplacement\" value='2' onclick=\"DisplacementGetConversion(2);\" />Short Ton</div><br />";
	this.rbsDesiredSpeed = "<b>Desired Max Speed</b><div style=\"margin: 0 auto; width: 330px; text-align: center\"><input id=\"rbRequiredSpeedKTS\" type=\"radio\" checked=\"checked\" name=\"rbRequiredSpeed\" value='0' onclick=\"DesiredSpeedGetConversion(0);\" />Knots<input id=\"rbRequiredSpeedMPH\" type=\"radio\" name=\"rbRequiredSpeed\" value='1' onclick=\"DesiredSpeedGetConversion(1);\" />Miles Per Hour<input id=\"rbRequiredSpeedKPH\" type=\"radio\" name=\"rbRequiredSpeed\" value='2' onclick=\"DesiredSpeedGetConversion(2);\" />Kilometers Per Hour</div><br />";
	this.empty = "<br/><br/><br/><br/><br/><br/><br/>";
}


function InitCalculator() {
    tabControl = igtab_getTabById(nameTCPR);
	if (!hull)
		hull = new Hull();
	html = new ConversionHTML();
	showTabs('rbHullTypeD', 7);
	InitialSelectionHT();
	//InitialSelectionHS();
	//InitialSelectionDL();
	//InitialSelectionPR();
}

function GetConversion(UnitType, FromUnitValue, ToUnitValue, ValueControl) {
	var value = ValueControl.getValue();
	if (value != 0) {
		$get('imgProgress' + ActiveTabKey).style.visibility = 'visible';
		PageMethods.GetConversion(ValueControl.ID, UnitType, FromUnitValue, ToUnitValue, value, OnGetConversionSucceeded, OnGetConversionFailed, UnitType);
	}
}

function OnGetConversionSucceeded(result, userContext, methodName) {
	$get('imgProgress' + ActiveTabKey).style.visibility = 'hidden';
	var results = JSON.parse(result);
	var tb = igedit_getById(results.ClientID);
	if (tb != null)
		tb.setNumber(parseFloat(results.Value));
}

function OnGetConversionFailed(error, userContext, methodName) {
	$get('imgProgress' + ActiveTabKey).style.visibility = 'hidden';
	alert(error._message);
}
function GetChecked(rbs) {
	for (var i = 0; i < rbs.length; i++) {
		if (rbs[i].checked) {
			return rbs[i].value;
		}
	}
}
function GetChart(name, subname, valueControl, valueControl2) {
	$get('imgProgress' + ActiveTabKey).style.visibility = 'visible';
	if (hull == null)
		hull = new Hull;

	if (name == 'HullType') {
		hull.ChartClientID = chartHT;
		hull.Chart = 'HullType';
		hull.ChartSub = subname;
		if (valueControl.name == 'rbHullType') {

			if (valueControl.id == "rbHullTypeSD") {
				var sel = $get('slHullTypeBA').selectedIndex;
				hull.ButtockAngle = $get('slHullTypeBA').options[sel].value;
				$get('slHullTypeBA').style.visibility = 'visible';
				$get('txtHullTypeBA').style.visibility = 'visible';
			}
			else {
				$get('slHullTypeBA').style.visibility = 'hidden';
				$get('txtHullTypeBA').style.visibility = 'hidden';
			}
		}
	}
	else if (name == 'HullSpeed') {
		hull.ChartClientID = chartHS;
		hull.Chart = 'HullSpeed';
		hull.ChartSub = subname;
		var rbs = document.forms[0].rbLWL;
		if (hull.FormulaToUse != 2) {
			hull.LWL = valueControl.getValue();
			hull.LWLUnit = GetChecked(document.forms[0].rbLWL);
		}
		else {
			hull.Displacement = valueControl.getValue();
			hull.DisplacementUnit = GetChecked(document.forms[0].rbDisplacement);
		}
	}
	else if (name == 'DLRatio') {
		hull.ChartClientID = chartDL;
		hull.Chart = 'DLRatio';
		hull.ChartSub = subname;

		hull.Displacement = valueControl.getValue();
		hull.DisplacementUnit = GetChecked(document.forms[0].rbDisplacement);
	}
	else if (name == 'PowerRequired') {
		hull.ChartClientID = chartPR;
		hull.Chart = 'PowerRequired';
		hull.ChartSub = subname;
		if (stateFormula == stateFormulaEnum.Crouch) {
			hull.LWL = valueControl.getValue();
			hull.LWLUnit = GetChecked(document.forms[0].rbLWL);
		}
		else {
			hull.DesiredSpeed = valueControl.getValue();
			hull.DesiredSpeedUnit = GetChecked(document.forms[0].rbRequiredSpeed);
		}
		if (valueControl2) {
			if (stateFormula == stateFormulaEnum.Crouch) {
				hull.DesiredSpeed = valueControl2.getValue();
				hull.DesiredSpeedUnit = GetChecked(document.forms[0].rbRequiredSpeed);
			}
			else {
				hull.Displacement = valueControl2.getValue();
				hull.DisplacementUnit = GetChecked(document.forms[0].rbDisplacement);
			}
		}
	}
	var str = JSON.stringify(hull);
	PageMethods.GetChart(str, OnGetChartSucceeded, OnGetChartFailed, name);
	return false;
}



function OnGetChartSucceeded(result, userContext, methodName) {
	hull = JSON.parse(result);
	$get('imgProgress' + ActiveTabKey).style.visibility = 'hidden';
	if (hull != null) {
		var chart = $get(hull.ChartClientID);
		if (chart != null)
			chart.innerHTML = hull.ChartHTML;
		chart.style.width = '686px';
		if (hull.Chart == "HullSpeed") {
			if (hull.ResultHTML != null && hull.ResultHTML != "") {
				$get('divHSResults').innerHTML = hull.ResultHTML;
				if (hull.HullSpeed)
					tbDesiredSpeed.setNumber(hull.HullSpeed);
				var rbs = document.forms[0].rbRequiredSpeed;
				rbs[0].checked = 'checked';
			}
		}
		if (hull.Chart == "DLRatio") {
			if (hull.HullSpeed)
				tbDesiredSpeed.setNumber(hull.HullSpeed);
		}
		else if (hull.Chart == "PowerRequired") {
			if (hull.ResultHTML != null && hull.ResultHTML != "") {
				$get('divPRResults').innerHTML = hull.ResultHTML;
			}
		}
	}
	onGetChartComplete.execute();
}

function OnGetChartFailed(error, userContext, methodName) {
	alert(error._message);
	//document.getElementById('UltraChart1').innerText = 'An Error occured please try again.';
	$get('imgProgress' + ActiveTabKey).style.visibility = 'hidden';
	onGetChartComplete.execute();
}
function showTabs(checkId, angle) {
	if (checkId == "rbHullTypeD") {
		$get('divRbsHS1').innerHTML = html.rbsLWL;
		tbLWL = igedit_getById(nametbHS1);
		$get('divHSCalcControls2').innerHTML = html.empty;
		$get('divRbsDL1').innerHTML = html.rbsDisplacement;
		tbDisplacement = igedit_getById(nametbDL1);
		$get('divRbsPR1').innerHTML = html.rbsDesiredSpeed;
		tbDesiredSpeed = igedit_getById(nametbPR1);
		$get('divPRCalcControls2').style.visibility = 'hidden';
		tabControl.Tabs[1].setVisible(true);
		tabControl.Tabs[1].setText("Hull Speed");
		tabControl.Tabs[2].setVisible(true);
		tabControl.Tabs[2].setText("DL Ratio Gerr");
		tabControl.Tabs[3].setText("Power Required Gerr");
		$get('divHSTitle').innerHTML = "<h2>Displacement Hull Speed</h2>";
		$get('divHSFormula').innerHTML = "<b>Formula</b> : Kts = 1.34 * LWL^½</p>";
		$get('divPRFormula').innerHTML = "<p><b>David Gerr's formula : </b>SHP = Disp.lwl / ((2.3 - SL Ratio)*8.11)^3 </p>";
		stateFormula = stateFormulaEnum.Gerr;
	}
	else if (checkId == "rbHullTypeSD") {
		$get('divRbsHS1').innerHTML = html.rbsLWL;
		tbLWL = igedit_getById(nametbHS1);
		$get('divHSCalcControls2').innerHTML = html.empty;
		$get('divRbsPR1').innerHTML = html.rbsDesiredSpeed;
		$get('divPRCalcControls2').style.visibility = 'visible';
		tbDesiredSpeed = igedit_getById(nametbPR1);
		$get('divRbsPR2').innerHTML = html.rbsDisplacement;
		tbDisplacement = igedit_getById(nametbPR2);
		tabControl.Tabs[1].setVisible(true);
		tabControl.Tabs[1].setText("Hull Speed");
		tabControl.Tabs[2].setVisible(false);
		tabControl.Tabs[3].setText("Power Required Wyman");
		$get('divHSTitle').innerHTML = "<h2>Semi-Displacement Hull Speed</h2>";
		$get('divHSFormula').innerHTML = "<b>Formula</b> : Kts = SL Ratio * LWL^½</p>";
		$get('divPRFormula').innerHTML = "<p><b>Wyman's formula :</b>Cw = 0.8+(0.17*SL Ratio) SHP = (Disp.lb/1000)*(kts/(Cw*sqrt(lwl)))^3 </p>";
		stateFormula = stateFormulaEnum.Wyman;
	}
	else if (checkId == "rbHullTypeP") {
		$get('divRbsHS1').innerHTML = html.rbsDisplacement;
		tbDisplacement = igedit_getById(nametbHS1);
		$get('divHSCalcControls2').innerHTML = html.empty;
		$get('divRbsPR1').innerHTML = html.rbsLWL;
		tbLWL = igedit_getById(nametbPR1);
		$get('divPRCalcControls2').style.visibility = 'visible';
		$get('divRbsPR2').innerHTML = html.rbsDesiredSpeed;
		tbDesiredSpeed = igedit_getById(nametbPR2);
		tabControl.Tabs[1].setVisible(true);
		tabControl.Tabs[1].setText("Displacement Crouch");
		tabControl.Tabs[2].setVisible(false);
		tabControl.Tabs[3].setText("Power Required Wyman");
		$get('divHSTitle').innerHTML = "<h2>Power Required based on Displacement</h2>";
		$get('divHSFormula').innerHTML = "<b>Formula</b> : SL Ratio = 0.8/((Disp.lb/SHP/1000)^1/3 - 0.17)</p>";
		$get('divPRFormula').innerHTML = "<p><b>Wyman's formula :</b>Cw = 0.8+(0.17*SL Ratio) SHP = (Disp.lb/1000)*(kts/(Cw*sqrt(lwl)))^3 </p>";
		stateFormula = stateFormulaEnum.Crouch;
	}
}
function controlFocusDefault(index) {
	if (index == 0) {//Hull Type

	}
	else if (index == 1) {//Hull Speed
		if (stateFormula == stateFormulaEnum.Crouch)
			tbDisplacement.focus();
		else
			tbLWL.focus();
	}
	else if (index == 2) {//DL Ratio
		tbDisplacement.focus();
	}
	else if (index == 3) {//Power Required
		if (stateFormula == stateFormulaEnum.Crouch)
			tbLWL.focus();
		else if (stateFormula == stateFormulaEnum.Wyman)
			tbDisplacement.focus();
		else
			tbDesiredSpeed.focus();
	}
	else if (index == 4) {// Wyman or ...???
	}
}

function nextClick() {
	var index = (tabControl.getSelectedIndex() + 1);
	while (!tabControl.Tabs[index].getVisible()) {
		if (tabControl.Tabs.length < index)
			return false;
		else
			index++;
	}
	tabControl.setSelectedIndex(index);
	TabChange(tabControl.getSelectedTab(), index);
	return false;
}

function backClick() {
	var index = (tabControl.getSelectedIndex() - 1);
	while (!tabControl.Tabs[index].getVisible()) {
		if (index < 0)
			return false;
		else
			index--;
	}
	tabControl.setSelectedIndex(index);
	TabChange(tabControl.getSelectedTab(), index);
	return false;
}
function TabChange(tab, index) {
	ActiveTabKey = tab.Key;
	controlFocusDefault(index);
	LoadTabChart();
}
function onTabChange(tabcontrol, tab, e) {
	TabChange(tab, tabControl.getSelectedIndex());
}

var loadedHS = 'false';
var loadedDL = 'false';
var loadedPR = 'false';

function LoadTabChart() {
//	if (ActiveTabKey == 'HullType') {
//		InitialSelectionHT();
//	}
	if (ActiveTabKey == 'HullSpeed'&&loadedHS=='false') {
	    InitialSelectionHS();
	    loadedHS = 'true';
	}
	else if (ActiveTabKey == 'DLRatio' && loadedDL == 'false') {
	    InitialSelectionDL();
	    loadedDL = 'true';
	}
	else if (ActiveTabKey == 'PowerRequired' && loadedPR == 'false') {
	    InitialSelectionPR();
	    loadedPR = 'true';
	}
}

function TrapKD(btnID, event) {
	btn = findObj(btnID);
	if (document.all) {
		if (event.keyCode == 13) {
			event.returnValue = false;
			event.cancel = true;
			btn.click();
		}
	}
	else if (document.getElementById) {
		if (event.which == 13) {
			event.returnValue = false;
			event.cancel = true;
			btn.focus();
			btn.click();
		}
	}
	else if (document.layers) {
		if (event.which == 13) {
			event.returnValue = false;
			event.cancel = true;
			btn.focus();
			btn.click();
		}
	}
}

function findObj(n, d) {
	var p, i, x;
	if (!d)
		d = document;
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p + 1)].document;
		n = n.substring(0, p);
	}
	if (!(x = d[n]) && d.all)
		x = d.all[n];
	for (i = 0; !x && i < d.forms.length; i++)
		x = d.forms[i][n];
	for (i = 0; !x && d.layers && i < d.layers.length; i++)
		x = findObj(n, d.layers[i].document);
	if (!x && d.getElementById)
		x = d.getElementById(n);
	return x;
}

function Event() {
	this.eventHandlers = new Array();
}

Event.prototype.addHandler = function(eventHandler) {
	this.eventHandlers.push(eventHandler);
}

Event.prototype.execute = function(args) {
	while (this.eventHandlers.length > 0) {
		this.eventHandlers.shift()(args);
	}
}
function DisplacementGetConversion(toUnit) {
	GetConversion('Weight', lastDisplacementUnitType, toUnit, tbDisplacement);
	lastDisplacementUnitType = toUnit;
}
function DesiredSpeedGetConversion(toUnit) {
	GetConversion('Speed', lastRequiredSpeedUnitType, toUnit, tbDesiredSpeed);
	lastRequiredSpeedUnitType = toUnit;
}
//******************Hull Type

function InitialSelectionHT() {
	GetChart('HullType', 'Displacement', $get('rbHullTypeD'));
}

function HTClear() {
	HSClear();
	DLClear();
	PRClear();
}

function onButtockSizeChange(control) {
	hull.ButtockAngle = control.options[control.selectedIndex].value;
	var rbs = document.forms[0].rbHullType
	var id = 0;
	for (var i = 0; i < rbs.length; i++) {
		if (rbs[i].checked) {
			id = rbs[i].id;
			break;
		}
	}
	InitialSelectionHS();
	InitialSelectionPR();
}

function HTGetChart(type, control) {
	loadedHS = 'false';
	loadedDL = 'false';
	loadedPR = 'false';
	if (control.id == "rbHullTypeD") {
		hull.MaxSlRatio = 1.34;
		hull.HullType = 0;
		stateFormula = stateFormulaEnum.Gerr;
	}
	else if (control.id == "rbHullTypeSD") {
		hull.HullType = 1;
		stateFormula = stateFormulaEnum.Wyman;
	}
	else if (control.id == "rbHullTypeP") {
		hull.HullType = 2;
		stateFormula = stateFormulaEnum.Crouch;
	}
	GetChart('HullType', type, control);
	HTClear();
	showTabs(control.id, hull.ButtockAngle);
}
function ShowHelp(button,id) {
	if (stateFormula == stateFormulaEnum.Gerr) {
		if (id == "helpHullTypeChart")
			showDialog('/InfoChartDisplacementHull.aspx');
		else if (id == "helpHullSpeedCalc")
			showDialog('/InfoHullSpeedLWL.aspx');
		else if (id == "helpHullSpeedResultChart")
			showDialog('/InfoHullSpeedResults.aspx');
		else if (id == "helpPowerRequired")
			showDialog('/InfoPowerRequiredDisplacement.aspx');
	}
	else if (stateFormula == stateFormulaEnum.Wyman) {
		if (id == "helpHullTypeChart")
			showDialog('/InfoBoatHullRun.aspx');
		else if (id == "helpHullSpeedCalc")
			showDialog('/InfoHullSpeedLWL.aspx');
		else if (id == "helpHullSpeedResultChart")
			showDialog('/InfoHullSpeedResults.aspx');
		else if (id == "helpPowerRequired")
			showDialog('/InfoPowerRequiredSemiDisplacement.aspx');
	}
	else if (stateFormula == stateFormulaEnum.Crouch) {
		if (id == "helpHullTypeChart" || id == "helpHullSpeedCalc" || id == "helpHullSpeedResultChart")
			showDialog('/InfoChartCrouchHull.aspx');
		else if (id == "helpPowerRequired")
			showDialog('/InfoPowerRequiredPlaning.aspx');
	}
	return false;
}
//******************Hull Speed
//        addEvent(window, "load", InitialSelectionHS);

function InitialSelectionHS() {
	GetChart('HullSpeed', 'Displacement', tbLWL);
}
function HSClear() {
	loadedDL = 'false';
	loadedPR = 'false';
	if (stateFormula == stateFormulaEnum.Crouch) {
		tbDisplacement.setNumber(0);
		hull.Displacement = 0;
	}
	else {
		tbLWL.setNumber(0);
		hull.LWL = 0;
		hull.HullSpeed = 0;
	}
	if (ActiveTabKey == "HullSpeed") {
		HSCalculate();
		loadedHS = 'true';
	}
	else
		loadedHS = 'false';
	return false;
}
function HSCalculate() {
	loadedDL = 'false';
	loadedPR = 'false';
	if (hull.FormulaToUse != 2)
		GetChart('HullSpeed', 'Displacement', tbLWL);
	else
		GetChart('HullSpeed', 'Displacement', tbDisplacement);
	//onGetChartComplete.addHandler(CascadeCharts);
	return false;
}
function CascadeCharts() {
	if (stateFormula == stateFormulaEnum.Gerr)
		InitialSelectionDL();

	if (oldLwl == 0)
		oldLwl = hull.LWL;
	else if (oldLwl != hull.LWL) {
		oldLwl = hull.LWL;
		hull.GeneratePowerRequiredChart = true;
	}

	InitialSelectionPR();

}
//******************DL Ratio
//        addEvent(window, "load", InitialSelectionDL);


function InitialSelectionDL() {
	GetChart('DLRatio', 'DL', tbDisplacement);
}

function DLClear() {
	loadedPR = 'false';
	tbDisplacement.setNumber(0);
	hull.Displacement = 0;
	hull.PowerRequired = 0;
	if (ActiveTabKey == "DLRatio") {
		InitialSelectionDL();
		loadedDL = 'true';
	}
	else
		loadedDL = 'false';
	return false;
}
function DLCalculate() {
	loadedPR = 'false';
	GetChart('DLRatio', 'DL', tbDisplacement);
	//onGetChartComplete.addHandler(InitialSelectionPR);
	return false;
}

//******************Power Required
//        addEvent(window, "load", InitialSelectionPR);

//        var tbDisplacementPR;

function InitialSelectionPR() {
	GetChart('PowerRequired', 'Main', tbDesiredSpeed);
}
function PRClear() {
	if (stateFormula == stateFormulaEnum.Crouch) {
		tbLWL.setNumber(0);
		hull.LWL = 0;
		hull.HullSpeed = 0;
		hull.HullS
		tbDesiredSpeed.setNumber(0);
		hull.DesiredSpeed = 0;
		hull.HullSpeed = 0;
	}
	else if (stateFormula == stateFormulaEnum.Gerr) {
		tbDesiredSpeed.setNumber(0);
		hull.DesiredSpeed = 0;
		hull.HullSpeed = 0;
	}
	else {
		tbDisplacement.setNumber(0);
		hull.Displacement = 0;
		tbDesiredSpeed.setNumber(0);
		hull.DesiredSpeed = 0;
		hull.HullSpeed = 0;
	}
	if (ActiveTabKey == "PowerRequired") {
		InitialSelectionPR();
		loadedPR = 'true';
	}
	else
		loadedPR = 'false';
	return false;
}
function PRCalculate() {
	hull.GeneratePowerRequiredChart = true;
	if (stateFormula == stateFormulaEnum.Wyman) {
		GetChart(
                    'PowerRequired',
                    'Displacement',
                    tbDesiredSpeed,
                    tbDisplacement);
	}
	else if (stateFormula == stateFormulaEnum.Gerr) {
		GetChart('PowerRequired', 'Displacement', tbDesiredSpeed);
	}
	else if (stateFormula == stateFormulaEnum.Crouch) {
		GetChart('PowerRequired', 'Displacement', tbLWL, tbDesiredSpeed);
	}
	return false;
}
