var kRulesRevised 	= 0;
var kRules50 		= 1;
var kRulesOriginal 	= 2;
var kRules1942 		= 3;
var kRules1940		= 4;

var kRulesVersion = kRules50;

// don't forget, this is the order the pieces are removed in so they need to be in this order
var i=0;
var kBattleShipFakeIndex 	= i++;
var kInfIndex 				= i++;
var kMechInfIndex			= i++;
var kArtIndex 				= i++;
var kTankIndex 				= i++;
var kSubmarineIndex 		= i++;
var kTransportIndex 		= i++;
var kFighterIndex 			= i++;
var kDestroyerIndex 		= i++;
var kTacticalBomberIndex	= i++;
var kCruiserIndex 			= i++;
var kBomberIndex 			= i++;
var kAircraftCarrierIndex 	= i++;
var kBattleshipIndex 		= i++;
var kNumPieces 				= i++;


var kBattleshipFake 	= new battleshipFake();
var kInfantry 			= new infantry();
var kMechanizedInfantry;
var kArtillery 			= new artillery();
var kTank 				= new tank();
var kTransport 			= new transport();
var kSubmarine			= new submarine();
var kFighter 			= new fighter();
var kTacticalBomber;
var kDestroyer 			= new destroyer();
var kCruiser;
var kBomber 			= new bomber();
var kAircraftCarrier 	= new aircraftCarrier();
var kBattleship 		= new battleship();

var kNumSimRuns = 1000;

var ktechHeavyBombers		= "heavyBombers";
var ktechSuperSubmarines	= "superSubmarines";
var ktechAAGuns 			= "aaGuns";
var ktechJetFightersDef 	= "jetFightersDef";
var ktechJetFightersAtt 	= "jetFightersAtt";
var ktechAdvancedArtillery	= "advancedArtillery";
var ktechRadar				= "radar";

/*
// lighter in color
var kAlliesColor = "#C3FDB8";
var kAxisColor = "#FCDFFF";
*/

var kAlliesColor 	= "lightgreen";
var kAxisColor 		= "pink";


function setSimRuns( runs ) {
	kNumSimRuns = runs;
}


function initRevisedValues() {
	
	var i=0;
	kBattleShipFakeIndex 	= i++;
	kInfIndex 				= i++;
	kMechInfIndex			= i++;
	kArtIndex 				= i++;
	kTankIndex 				= i++;
	kSubmarineIndex 		= i++;
	kTransportIndex 		= i++;
	kFighterIndex 			= i++;
	kDestroyerIndex 		= i++;
	kTacticalBomberIndex	= i++;
	kCruiserIndex 			= i++;
	kBomberIndex 			= i++;
	kAircraftCarrierIndex 	= i++;
	kBattleshipIndex 		= i++;
	kNumPieces 				= i++;

	kBattleshipFake 		= new battleshipFake();
	kInfantry 				= new infantry();
	kArtillery 				= new artillery();
	kTank 					= new tank();
	kTransport 				= new transport();
	kSubmarine 				= new submarine();
	kFighter 				= new fighter();
	kDestroyer 				= new destroyer();
	kBomber 				= new bomber();
	kAircraftCarrier 		= new aircraftCarrier();
	kBattleship 			= new battleship();
	
	var rows = getElementsByClass("rulesClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "none";
	}

	var rows = getElementsByClass("revisedClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "";
	}
	
	selectBattleType();
}

function init50Values(improved) {
	
	var i=0;
	kBattleShipFakeIndex 	= i++;
	kInfIndex 				= i++;
	kMechInfIndex			= i++;
	kArtIndex 				= i++;
	kTankIndex 				= i++;
	kSubmarineIndex 		= i++;
	kDestroyerIndex 		= i++;
	kFighterIndex 			= i++;
	kTacticalBomberIndex	= i++;
	kCruiserIndex 			= i++;		// cruiser and bomber have the same IPC, but if we are an attacking group, we drop the cruiser first
	kBomberIndex 			= i++;		// on defense it doesn't matter, because you won't have bombers + cruisers on defense at the same time
	kAircraftCarrierIndex 	= i++;
	kBattleshipIndex 		= i++;
	kTransportIndex 		= i++;		// transports are only allowed to take hits last
	kNumPieces 				= i++;

	kBattleshipFake 		= new battleshipFake50();
	kInfantry 				= new infantry50();
	kArtillery 				= new artillery50();
	kTank 					= new tank50();
	kTransport 				= new transport50(improved);
	kSubmarine 				= new submarine50(improved);
	kFighter				= new fighter50();
	kDestroyer 				= new destroyer50(improved);
	kCruiser 				= new cruiser50(improved);
	kBomber 				= new bomber50();
	kAircraftCarrier 		= new aircraftCarrier50(improved);
	kBattleship 			= new battleship50(improved);
	
	var rows = getElementsByClass("rulesClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "none";
	}

	var rows = getElementsByClass("fiftyClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "";
	}
	
	selectBattleType();
}

function initOriginalValues() {
	
	var i=0;
	kBattleShipFakeIndex 	= i++;
	kInfIndex 				= i++;
	kMechInfIndex			= i++;
	kArtIndex 				= i++;
	kTankIndex 				= i++;
	kSubmarineIndex 		= i++;
	kTransportIndex 		= i++
	kFighterIndex 			= i++;
	kDestroyerIndex 		= i++;
	kTacticalBomberIndex	= i++;
	kCruiserIndex 			= i++;
	kBomberIndex 			= i++;
	kAircraftCarrierIndex 	= i++;
	kBattleshipIndex 		= i++;
	kNumPieces 				= i++;

	kBattleshipFake 	= new battleshipFakeOriginal();
	kInfantry 			= new infantryOriginal();
	kArtillery 			= new artilleryOriginal();
	kTank 				= new tankOriginal();
	kTransport 			= new transportOriginal();
	kSubmarine 			= new submarineOriginal();
	kFighter 			= new fighterOriginal();
	kDestroyer 			= new destroyerOriginal();
	kCruiser 			= new cruiserOriginal();
	kBomber 			= new bomberOriginal();
	kAircraftCarrier 	= new aircraftCarrierOriginal();
	kBattleship 		= new battleshipOriginal();
	
	var rows = getElementsByClass("rulesClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "none";
	}

	// i don't think there are any that are original only actually ... except tank name
	rows = getElementsByClass("originalClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "";
	}
	
	selectBattleType();
}

// same as 50 basically but no research
function init1942Rules() {

	var i=0;
	kBattleShipFakeIndex	= i++;
	kInfIndex 				= i++;
	kMechInfIndex			= i++;
	kArtIndex 				= i++;
	kTankIndex 				= i++;
	kSubmarineIndex 		= i++;
	kDestroyerIndex 		= i++;
	kFighterIndex 			= i++;
	kTacticalBomberIndex	= i++;
	kCruiserIndex 			= i++;	// cruiser and bomber have the same IPC, but if we are an attacking group, we drop the cruiser first
	kBomberIndex 			= i++;	// on defense it doesn't matter, because you won't have bombers + cruisers on defense at the same time
	kAircraftCarrierIndex 	= i++;
	kBattleshipIndex 		= i++;
	kTransportIndex 		= i++;	// transports are only allowed to take hits last
	kNumPieces 				= i++;

	var improved = false;
	kBattleshipFake 		= new battleshipFake50();
	kInfantry 				= new infantry50();
	kArtillery 				= new artillery50();
	kTank 					= new tank50();
	kTransport 				= new transport50(improved);
	kSubmarine 				= new submarine50(improved);
	kFighter 				= new fighter50();
	kDestroyer 				= new destroyer50(improved);
	kCruiser 				= new cruiser50(improved);
	kBomber 				= new bomber50();
	kAircraftCarrier 		= new aircraftCarrier50(improved);
	kBattleship 			= new battleship50(improved);
	
	var rows = getElementsByClass("rulesClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "none";
	}

	var rows = getElementsByClass("forty2Class");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "";
	}
	
	selectBattleType();
}

function init1940Rules() {

	var i=0;
	kBattleShipFakeIndex	= i++;
	kInfIndex 				= i++;
	kMechInfIndex			= i++;
	kArtIndex 				= i++;
	kTankIndex 				= i++;
	kSubmarineIndex 		= i++;
	kDestroyerIndex 		= i++;
	kFighterIndex 			= i++;
	kTacticalBomberIndex	= i++;
	kCruiserIndex 			= i++;	// cruiser and bomber have the same IPC, but if we are an attacking group, we drop the cruiser first
	kBomberIndex 			= i++;	// on defense it doesn't matter, because you won't have bombers + cruisers on defense at the same time
	kAircraftCarrierIndex 	= i++;
	kBattleshipIndex 		= i++;
	kTransportIndex 		= i++;	// transports are only allowed to take hits last
	kNumPieces 				= i++;

	var improved = false;
	kBattleshipFake 		= new battleshipFake50();
	kInfantry 				= new infantry50();
	kMechanizedInfantry		= new mechanizedInfantry();
	kArtillery 				= new artillery50();
	kTank 					= new tank1940();
	kTransport 				= new transport50(improved);
	kSubmarine 				= new submarine50(improved);
	kFighter 				= new fighter50();
	kTacticalBomber			= new tacticalBomber();
	kDestroyer 				= new destroyer50(improved);
	kCruiser 				= new cruiser50(improved);
	kBomber 				= new bomber50();
	kAircraftCarrier 		= new aircraftCarrier1940();
	kBattleship 			= new battleship50(improved);
	
	var rows = getElementsByClass("rulesClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "none";
	}

	var rows = getElementsByClass("fortyClass");
	for ( i=0; i<rows .length; i++ ) {
		rows[i].style.display = "";
	}
	
	selectBattleType();
}

function changeRules( rules ) {
	kRulesVersion = rules;
	
	if ( kRulesVersion == kRulesOriginal ) {
		initOriginalValues();
	} else if ( kRulesVersion == kRulesRevised ) {
		initRevisedValues();
	} else if ( kRulesVersion == kRules1942 ) {
		init1942Rules();
	} else if ( kRulesVersion == kRules1940 ) {
		init1940Rules();
	} else {
		// 50th anniversary
		init50Values();
	}
	
	document.getElementById( "rulesSelect" ).value = kRulesVersion;
	
	setTechMarks();
	updateStats();
	calcIPCs();
}

function setRowVis( row, vis ) {
	document.getElementById( row ).style.display = (vis ? '' : 'none');
}

function selectBattleType( type ) {
	
	if ( type == undefined ) {
		type = document.getElementById( "battleType" ).value;
	} else {
		// set this here in case it's from the URL
		document.getElementById( "battleType" ).value = type;
	}
	
	if ( (type == 0) || (type == "0") ) {
		// land
		setRowVis( 'infRow', true );
		setRowVis( 'mechInfRow', is1940Rules() );
		setRowVis( 'artRow', !(isOriginalRules()) );
		setRowVis( 'tankRow', true );
		setRowVis( 'fighterRow', true );
		setRowVis( 'tacticalBomberRow', is1940Rules() );
		setRowVis( 'bomberRow', true );
		
		setRowVis( 'transportRow', false );
		setRowVis( 'submarineRow', false );
		setRowVis( 'destroyerRow', false );
		setRowVis( 'cruiserRow', false );
		setRowVis( 'aircraftCarrierRow', false );
		setRowVis( 'battleshipRow', false );
		
	} else if ( (type == 1) || (type == "1")  ) {
		// amphibious assault

		setRowVis( 'infRow', true );
		setRowVis( 'mechInfRow', is1940Rules() );
		setRowVis( 'artRow', !(isOriginalRules()) );
		setRowVis( 'tankRow', true );
		setRowVis( 'fighterRow', true );
		setRowVis( 'tacticalBomberRow', is1940Rules() );
		setRowVis( 'bomberRow', true );
		
		setRowVis( 'transportRow', false );
		setRowVis( 'submarineRow', false );
		setRowVis( 'destroyerRow', true );
		setRowVis( 'cruiserRow', !(isOriginalRules() || isRevisedRules()) );
		setRowVis( 'aircraftCarrierRow', false );
		setRowVis( 'battleshipRow', true );
		
	} else {
		// sea
		
		setRowVis( 'infRow', false );
		setRowVis( 'mechInfRow', false );
		setRowVis( 'artRow', false );
		setRowVis( 'tankRow', false );
		setRowVis( 'fighterRow', true );
		setRowVis( 'tacticalBomberRow', is1940Rules() );
		setRowVis( 'bomberRow', true );
		
		setRowVis( 'transportRow', true );
		setRowVis( 'submarineRow', true );
		setRowVis( 'destroyerRow', true );
		setRowVis( 'cruiserRow', !(isOriginalRules() || isRevisedRules()) );
		setRowVis( 'aircraftCarrierRow', true );
		setRowVis( 'battleshipRow', true );
	}
	
	calcIPCs();
}

function updateStats() {
	setStatValue( "infStats", kInfantry );
	setStatValue( "mechInfStats", kMechanizedInfantry );
	setStatValue( "artStats", kArtillery );
	setStatValue( "tankStats", kTank );
	setStatValue( "fighterStats", kFighter );
	setStatValue( "tacticalBomberStats", kTacticalBomber );
	setStatValue( "bomberStats", kBomber );
	setStatValue( "transportStats", kTransport );
	setStatValue( "subStats", kSubmarine );
	setStatValue( "destroyerStats", kDestroyer );
	setStatValue( "cruiserStats", kCruiser );
	setStatValue( "accStats", kAircraftCarrier );
	setStatValue( "batStats", kBattleship );
}

function setStatValue( theID, theObject ) {
	if ( theObject != null ) {
		var str = "<span style='font-weight:normal;'> [" + theObject.att + "/" + theObject.def + "/" + theObject.cost + "]</span>";
		// looks ugly
		//	document.getElementById( theID ).innerHTML = str;
	}
}

function swap() {
	// swap attacker and defender values here
	
	swapValues( "attInfantry", 				"defInfantry" );
	swapValues( "attMechanizedInfantry", 	"defMechanizedInfantry" );
	swapValues( "attArtillery", 			"defArtillery" );
	swapValues( "attTank", 					"defTank" );
	swapValues( "attTransport", 			"defTransport" );
	swapValues( "attSubmarine", 			"defSubmarine" );
	swapValues( "attFighter", 				"defFighter" );
	swapValues( "attTacticalBomber", 		"defTacticalBomber" );
	swapValues( "attDestroyer", 			"defDestroyer" );
	swapValues( "attCruiser", 				"defCruiser" );
	swapValues( "attBomber", 				"defBomber" );
	swapValues( "attAircraftCarrier", 		"defAircraftCarrier" );
	swapValues( "attBattleship", 			"defBattleship" );
	
	var temp = kAlliesColor;
	kAlliesColor = kAxisColor;
	kAxisColor = temp;

	allies = getElementsByClass( "allies" );
	for ( i=0; i<allies.length; i++ ) {
		allies[i].style.backgroundColor = kAlliesColor;
	}
	axis = getElementsByClass( "axis" );
	for ( i=0; i<axis .length; i++ ) {
		axis[i].style.backgroundColor = kAxisColor;
	}

	
	calcIPCs();
	//runSim();	// cause why else would you swap
}

function swapValues( att, def ) {
	
	attValue = document.getElementById( att ).value;
	document.getElementById( att ).value = document.getElementById( def ).value;
	document.getElementById( def ).value = attValue;
}

function setPieceValue( piece, value ) {

	if ( (value == 0) || (value == null) )
		value = "";
		
	document.getElementById( piece ).value = value;
}

function setSimOptionCheck( str, inChecked ) {
	
	if ( (inChecked == null) || (inChecked == "false") )
		inChecked = false;

	document.getElementById( str ).checked = inChecked;
}

// only revised and 50 have research options
// so we just put it in here
function getSimOption( str ) {
	if ( isRevisedRules() || is50Rules() || (str==ktechAAGuns) ) {
		return document.getElementById( str ).checked;
	}
	
	return false;
}

function isLandBattle() {
	return document.getElementById( "battleType" ).value == 0;
}

function isAmphibiousAssault() {
	return document.getElementById( "battleType" ).value == 1;
}

function isSeaBattle() {
	return document.getElementById( "battleType" ).value == 2;
}

function is1940Rules() {
	return kRulesVersion == kRules1940;
}

function isRevisedRules() {
	return kRulesVersion == kRulesRevised;
}

function is50Rules() {
	return kRulesVersion == kRules50;
}

function is50PlusRules() {
	// 50th anniversary rules + 1942 rules and future rules with cruisers etc.
	return ( !isOriginalRules() && !isRevisedRules() );
}

function isOriginalRules() {
	return kRulesVersion == kRulesOriginal;
}

function isRevisedOr50() {
	return isRevisedRules() || is50Rules();
}

// revised rules only
function removeBombardmentCasualties() {
	var hits = calcHits( unitsArray[0][kDestroyerIndex], kDestroyer.att );
	hits += calcHits( unitsArray[0][kBattleshipIndex], kBattleship.att );
	
	subtractHits( 1, hits, unitsArray );
}

function hasDestroyers( side, unitsArray ) {
	return unitsArray[side][kDestroyerIndex] > 0;
}

function otherSide( side ) {
	if ( side == 0 )
		return 1;
	return 0;
}

function calcSubHits( side, unitsArray ) {
	// super subs only for attack option
	if ( (side==0) && getSimOption(ktechSuperSubmarines) )
		return calcHits( unitsArray[side][kSubmarineIndex], 3 );
	else if ( side == 0 )
		return calcHits( unitsArray[side][kSubmarineIndex], kSubmarine.att );		
	
	return calcHits( unitsArray[side][kSubmarineIndex], kSubmarine.def );
}

function applySubHitsBy( side, hits, unitsArray ) {
	// subs can only hit water, so we ignore any air ...
	var power = otherSide(side);
	
	for ( var i=0; i<kNumPieces; i++ ) {
		
		// should't be any land pieces here, and just skip air
		// if 50 rules, have to take hits on transports last
		if ( (i == kFighterIndex) ||
			 (i == kBomberIndex) ||
			 (i == kTacticalBomberIndex) ||
			 (i == kTransportIndex && is50PlusRules()) )
			 continue;
	
		if ( unitsArray[power][i] >= hits ) {
			unitsArray[power][i] -= hits;
			break;
		} else {
			hits -= unitsArray[power][i];
			unitsArray[power][i] = 0;
			// and then loop to the next less costly unit
		}
	}
	
	if ( is50PlusRules() ) {
		// check for transports now
		var i = kTransportIndex;
		
		if ( unitsArray[power][i] >= hits ) {
			unitsArray[power][i] -= hits;
		
		} else {
			hits -= unitsArray[power][i];
			unitsArray[power][i] = 0;
		}
	}
}
				

function runSim() {

	try {
		simBegins();

		unitsArray = createUnitArray();
		document.getElementById( "mutualDestruction" ).value = 0;
		document.getElementById( "attVictory" ).value = 0;
		document.getElementById( "defVictory" ).value = 0;
		
		// 0 is attacker win, 1 is mut dest, 2 is def wins, 3 is ipc loss attacker, 4 is ave ipc loss defender
		var resultsArray = new Array(5);
		for ( var i=0; i<5; i++ )
			resultsArray[i] = 0;
			
		// calculate pristine IPCs for ave losses
		fillUnitsArray( unitsArray );
		var attIPCStart = calcIPC( 0, unitsArray );
		var defIPCStart = calcIPC( 1, unitsArray );

		for ( var ctr=0; ctr<kNumSimRuns; ctr++ ) {

			// run sim 1000 times ...				
			fillUnitsArray( unitsArray );
			
			// 50th editions state bombardment casualties get to fire back, so revised
			// we removed immediately, and 50th we give some free hits
			var oneTimeBombard = 0;
			if ( isAmphibiousAssault() && isRevisedRules() )
				removeBombardmentCasualties();
			else if ( isAmphibiousAssault() ) {
				
				oneTimeBombard += calcHits( unitsArray[0][kDestroyerIndex], kDestroyer.att );
				oneTimeBombard += calcHits( unitsArray[0][kCruiserIndex], kCruiser.att );
				oneTimeBombard += calcHits( unitsArray[0][kBattleshipIndex], kBattleship.att );
			}
			
			// run once only per sim 
			if ( getSimOption( ktechAAGuns ) ) {
				removeAACasualties( unitsArray );
			}

			// now calculate sim values
			// add up all hits
			var totalAttack, totalDefense;
			while ( true ) {
				
				if ( !isSeaBattle() ) {
					// land or amphibious
					var hitsAtt = oneTimeBombard;
					
					hitsAtt +=  calcHitsAttack( unitsArray, false );
					var hitsDef = calcHitsDefense( unitsArray, false );
					
					totalDefense = subtractHits( 1, hitsAtt, unitsArray );
					totalAttack = subtractHits( 0, hitsDef, unitsArray );
					
				} else {
					// sea battle only. calc sub hits. if the other side has
					// destroyers, don't apply them until later. otherwise 
					// apply them preemptively
					var subHitsAtt = calcSubHits(0,unitsArray);
					var subHitsDef = calcSubHits(1,unitsArray);
					
					if ( !hasDestroyers(1,unitsArray) ) {
						applySubHitsBy( 0, subHitsAtt, unitsArray );
						subHitsAtt = 0;
					}
					
					if ( !hasDestroyers(0,unitsArray) ) {
						applySubHitsBy( 1, subHitsDef, unitsArray );
						subHitsDef = 0;
					}
					
					var hitsAtt = calcHitsAttack( unitsArray, true );
					var hitsDef = calcHitsDefense( unitsArray, true );
					
					// now apply sub hits
					applySubHitsBy( 0, subHitsAtt, unitsArray );
					applySubHitsBy( 1, subHitsDef, unitsArray );
					
					totalDefense = subtractHits( 1, hitsAtt, unitsArray );
					totalAttack = subtractHits( 0, hitsDef, unitsArray );
				}
				
				oneTimeBombard = 0;

				// check to see if we can continue
				if ( totalAttack == 0 && totalDefense == 0 ) {
					resultsArray[1] += 1;
					break;
				} else if ( totalDefense == 0 ) {
					resultsArray[0] += 1;
					break;
				} else if ( totalAttack == 0 ) {
					resultsArray[2] += 1;
					break;
				}
				
				var punchAttack = punchValueGreaterThan0( 0, unitsArray, true );
				var punchDefense = punchValueGreaterThan0( 1, unitsArray, false );
				
				// draw if neither side can damage the other
				if ( !punchAttack && !punchDefense ) {
					resultsArray[1] += 1;
					break;
				}
				
				// if they both only have transports left, call it a draw cause they ain't got no attack
				/*
				if ( is50PlusRules() && unitsArray[0][kTransportIndex] > 0 && unitsArray[1][kTransportIndex] > 0 ) {
					
					var onlyTransports1 = true;
					// wow. declaring var i inside the for loop is the same scope as the for loop above and hangs the sim. ewwww
					for ( var i=0; i<kNumPieces; i++ ) {
						if ( i != kTransportIndex ) {
							if ( unitsArray[0][i] > 0 ) {
								onlyTransports1 = false;
								break;
							}
						}
					}
					
					var onlyTransports2 = true;
					for ( var i=0; i<kNumPieces; i++ ) {
						if ( i != kTransportIndex ) {
							if ( unitsArray[1][i] > 0 ) {
								onlyTransports2 = false;
								break;
							}
						}
					}
					
					if ( onlyTransports1 && onlyTransports2 ) {
						resultsArray[1] += 1;
						break;
					}
				}
				*/
				// or if one side only has subs and the other side only has air
				
				/*
				attHits = calcHitsAttack( unitsArray );		
				defHits = calcHitsDefense( unitsArray );
			
				// subtract pieces
				totalAttack = subtractHits( 0, defHits, unitsArray );
				totalDefense = subtractHits( 1, attHits, unitsArray );
				*/
			}
			
			
			// calculate IPC totals for each AFTER battle so we can do average losses
			resultsArray[3] += attIPCStart - calcIPC( 0, unitsArray );
			resultsArray[4] += defIPCStart - calcIPC( 1, unitsArray );
		}
		
		document.getElementById( "mutualDestruction" ).value = ( (resultsArray[1]/kNumSimRuns)*100).toFixed(1) + " %";
		document.getElementById( "attVictory" ).value = ( (resultsArray[0]/kNumSimRuns)*100).toFixed(1) + " %";
		document.getElementById( "defVictory" ).value = ( (resultsArray[2]/kNumSimRuns)*100).toFixed(1) + " %";
		
		document.getElementById( "attAveIPCLoss" ).value = (resultsArray[3]/kNumSimRuns).toFixed(0);
		document.getElementById( "defAveIPCLoss" ).value = (resultsArray[4]/kNumSimRuns).toFixed(0);
		
		simEnds();
	
	} catch ( e ) {
		alert( "An error occurred: " + e );
	}
}

// calculates to see if we have any units left with an attack (or defense)
// value greater than 0. If each side has units left with no attack power then we draw
// returns true or false
function punchValueGreaterThan0( side, unitsArray, attack ) {
	var total = 0;
	if ( attack ) {
		
		// don't calc fake stuff - 1940 rules have fake hits on aircraft carriers but they got no attack
		//if ( isSeaBattle() ) {
		//	total += unitsArray[side][kBattleShipFakeIndex]	* kBattleship.att;
		//}
		
		if ( isLandBattle() || isAmphibiousAssault() ) {
			total += unitsArray[side][kInfIndex]				* kInfantry.att;
			if ( is1940Rules() )
				total += unitsArray[side][kMechInfIndex]		* kMechanizedInfantry.att;
			total += unitsArray[side][kArtIndex]				* kArtillery.att;
			total += unitsArray[side][kTankIndex]				* kTank.att;
		}
		
		if ( isSeaBattle() ) {
			total += unitsArray[side][kSubmarineIndex]			* kSubmarine.att;
			total += unitsArray[side][kDestroyerIndex]			* kDestroyer.att;
			if ( is50PlusRules() )
				total += unitsArray[side][kCruiserIndex]		* kCruiser.att;
			total += unitsArray[side][kAircraftCarrierIndex]	* kAircraftCarrier.att;
			total += unitsArray[side][kBattleshipIndex]			* kBattleship.att;
			total += unitsArray[side][kTransportIndex]			* kTransport.att;
		}
		
		// air for everybody
		total += unitsArray[side][kFighterIndex]				* kFighter.att;
		total += unitsArray[side][kBomberIndex]					* kBomber.att;
		if ( is1940Rules() )
			total += unitsArray[side][kTacticalBomberIndex]		* kTacticalBomber.att;
		
	} else {
			
		// don't calc fake stuff - 1940 rules have fake hits on aircraft carriers but they got no attack
		//if ( isSeaBattle() ) {
		//	total += unitsArray[side][kBattleShipFakeIndex]	* kBattleship.att;
		//}
		
		if ( isLandBattle() || isAmphibiousAssault() ) {
			total += unitsArray[side][kInfIndex]				* kInfantry.def;
			if ( is1940Rules() )
				total += unitsArray[side][kMechInfIndex]		* kMechanizedInfantry.def;
			total += unitsArray[side][kArtIndex]				* kArtillery.def;
			total += unitsArray[side][kTankIndex]				* kTank.def;
		}
		
		if ( isSeaBattle() ) {
			total += unitsArray[side][kSubmarineIndex]			* kSubmarine.def;
			total += unitsArray[side][kDestroyerIndex]			* kDestroyer.def;
			if ( is50PlusRules() )
				total += unitsArray[side][kCruiserIndex]		* kCruiser.def;
			total += unitsArray[side][kAircraftCarrierIndex]	* kAircraftCarrier.def;
			total += unitsArray[side][kBattleshipIndex]			* kBattleship.def;
			total += unitsArray[side][kTransportIndex]			* kTransport.def;
		}
		
		// air for everybody
		total += unitsArray[side][kFighterIndex]				* kFighter.def;
		total += unitsArray[side][kBomberIndex]					* kBomber.def;
		if ( is1940Rules() )
			total += unitsArray[side][kTacticalBomberIndex]		* kTacticalBomber.def;
		
	}
	
	return total > 0;
}

// calculate AA attacks against attacking fighters and bombers
function removeAACasualties( unitsArray ) {
	
	// rules state separate shots for both fighters and bombers
	var aaGunsAttack = 1;
	
	if ( is50Rules() && getSimOption( ktechRadar ) ) {
		aaGunsAttack = 2;
	}
	
	var fighterHits 		= calcHits( unitsArray[0][kFighterIndex], aaGunsAttack );
	var bomberHits 			= calcHits( unitsArray[0][kBomberIndex], aaGunsAttack );
	var tacticalBomberHits 	= calcHits( unitsArray[0][kTacticalBomberIndex], aaGunsAttack );
	
	unitsArray[0][kFighterIndex] 		-= fighterHits;
	unitsArray[0][kBomberIndex] 		-= bomberHits;
	unitsArray[0][kTacticalBomberIndex] -= tacticalBomberHits;
	
}

function calcResults( which, resultsArray, numSimRuns ) {
	var total = 0;
	for ( i=0; i<numSimRuns ; i++ ) {
		total += resultsArray[i][which];
	}

	return total/numSimRuns;
}

function clearly() {
	
	var array = getElementsByClass( "allies" );
	for ( i=0; i<array.length; i++ ) {
		array[i].value = "";
	}

	var array = getElementsByClass( "axis" );
	for ( i=0; i<array.length; i++ ) {	
		array[i].value = "";
	}
	
	var array = getElementsByClass( "victory" );
	for ( i=0; i<array.length; i++ ) {	
		array[i].value = "";
	}
}

// takes the number of hits and subtracts the number of units we have
// returns the number of pieces left
// the pieces are arranged in numerical order from lowest cost to highest, so we 
// just kill the smallest cost pieces first

function subtractHits( power, hits, unitsArray ) {
	for ( i=0; i<kNumPieces; i++ ) {
		
		// if we are an amphibious assault, we do not take hits on any of these guys
		if ( isAmphibiousAssault() && (i==kDestroyerIndex || i==kCruiserIndex || i==kBattleshipIndex) )
			continue;
		
		if ( unitsArray[power][i] >= hits ) {
			unitsArray[power][i] -= hits;
			break;
		} else {
			hits -= unitsArray[power][i];
			unitsArray[power][i] = 0;
			// and then loop to the next less costly unit
		}
	}
	

	var numLeft = 0;

	for ( i=0; i<kNumPieces; i++ ) {
		
		// if we are an amphibious assault, we do not count any of these guys in our total pieces left
		if ( isAmphibiousAssault() && (i==kDestroyerIndex || i==kCruiserIndex || i==kBattleshipIndex) )
			continue;
			
		numLeft += unitsArray[power][i];
	}

	return numLeft;
}

// returns 0 for miss, 1 for hit
function calcHits( numUnits, attack ) {
	var hits = 0;

	for ( i=0; i<numUnits; i++ ) {	
		if ( getRandom(1,6) <= attack ) {
			hits += 1;
		}
	}

	return hits;
}

// it's inclusive, that's why we add 1 to hi
function getRandom( lo, hi ) {

	var ranNum = Math.floor(Math.random()*((hi+1)-lo));
	return lo+ranNum;
}

function calcHitsAttack( unitsArray, excludeSubs ) {
	
	var totalHits = 0;	
	
	// infantry and artillery attack at a 1-1 ratio on a 2
	var numInfantry = unitsArray[0][kInfIndex];
	var numArtillery = unitsArray[0][kArtIndex];
	
	if ( is1940Rules() ) 
		numInfantry +=	unitsArray[0][kMechInfIndex];
	
	var numInfantryWithBonus = 0, numInfantryLeftover;
		
	if ( is50Rules() && getSimOption( ktechAdvancedArtillery ) )
		numInfantryWithBonus = (numInfantry >= numArtillery*2) ? numArtillery*2 : numInfantry;
	else if ( !isOriginalRules() )	// original rules don't get infantry bonus
		numInfantryWithBonus = (numInfantry >= numArtillery) ? numArtillery : numInfantry;

	numInfantryLeftover = numInfantry - numInfantryWithBonus;
	
	totalHits += calcHits( numInfantryLeftover, kInfantry.att );
	totalHits += calcHits( numInfantryWithBonus, kArtillery.att );		// same as artillery attack
	if ( !isOriginalRules() )
		totalHits += calcHits( unitsArray[0][kArtIndex], kArtillery.att );
	totalHits += calcHits( unitsArray[0][kTankIndex], kTank.att );
	//totalHits += calcHits( unitsArray[0][kTransportIndex], kTransport.att );
	// super subs attack on a 3, not a 2
	if ( !excludeSubs ) {
		if ( getSimOption( ktechSuperSubmarines ) )
			totalHits += calcHits( unitsArray[0][kSubmarineIndex], 3 );
		else
			totalHits += calcHits( unitsArray[0][kSubmarineIndex], kSubmarine.att );
	}

	if ( isSeaBattle() && is50PlusRules() )
		totalHits += calcHits( unitsArray[0][kCruiserIndex], kCruiser.att );
	
	
	// 50th edition jetfighters attack on a 4
	if ( is50Rules() && getSimOption( ktechJetFightersAtt ) )
		totalHits += calcHits( unitsArray[0][kFighterIndex], 4 );
	else
		totalHits += calcHits( unitsArray[0][kFighterIndex], kFighter.att );
	
	if ( isSeaBattle() )
		totalHits += calcHits( unitsArray[0][kDestroyerIndex], kDestroyer.att );
	
	// 50th rules have been updated, heavy bombers roll 2 dice but select the highest
	if ( is50Rules() && getSimOption( ktechHeavyBombers ) ) {
		
		var hit1 = calcHits( unitsArray[0][kBomberIndex], kBomber.att);
		var hit2 = calcHits( unitsArray[0][kBomberIndex], kBomber.att);
		
		totalHits += (hit1 > hit2) ? hit1 : hit2;
		
	} else if ( getSimOption( ktechHeavyBombers ) ) {
		totalHits += calcHits( unitsArray[0][kBomberIndex], kBomber.att);
		totalHits += calcHits( unitsArray[0][kBomberIndex], kBomber.att);
	} else {
		totalHits += calcHits( unitsArray[0][kBomberIndex], kBomber.att);
	}
	
	// tactical bombers
	// attack on a 4 if paired with a tank
	// attack on a 4 if paired with a fighter
	if ( is1940Rules() ) {
		var numTacBombers = unitsArray[0][kTacticalBomberIndex];
		var numTacBonus	= unitsArray[0][kFighterIndex] + unitsArray[0][kTankIndex];
		
		var numTacBombersWithBonus = 0, numTacBombersLeftover;
		
		numTacBombersWithBonus = (numTacBombers >= numTacBonus) ? numTacBonus : numTacBombers;
		numTacBombersLeftover = numTacBombers - numTacBombersWithBonus;
		
		totalHits += calcHits( numTacBombersLeftover, kTacticalBomber.att );
		totalHits += calcHits( numTacBombersWithBonus, 4 );			// they attack on a 4
	}
	
	totalHits += calcHits( unitsArray[0][kAircraftCarrierIndex], kAircraftCarrier.att);
	
	if ( isSeaBattle() )
		totalHits += calcHits( unitsArray[0][kBattleshipIndex], kBattleship.att);

	return totalHits;
}

function calcHitsDefense( unitsArray, excludeSubs ) {

	var totalHits = 0;

	totalHits += calcHits( unitsArray[1][kInfIndex], kInfantry.def );
	
	if ( is1940Rules() )
		totalHits += calcHits( unitsArray[1][kMechInfIndex], kMechanizedInfantry.def );

	if ( !isOriginalRules() )
		totalHits += calcHits( unitsArray[1][kArtIndex], kArtillery.def );
	totalHits += calcHits( unitsArray[1][kTankIndex], kTank.def );
	totalHits += calcHits( unitsArray[1][kTransportIndex], kTransport.def );
	if ( !excludeSubs )
		totalHits += calcHits( unitsArray[1][kSubmarineIndex], kSubmarine.def );
	
	// jet fighters defend on a 5
	if ( getSimOption( ktechJetFightersDef ) )
		totalHits += calcHits( unitsArray[1][kFighterIndex], 5 );
	else
		totalHits += calcHits( unitsArray[1][kFighterIndex], kFighter.def );
	
	if ( isSeaBattle() )
		totalHits += calcHits( unitsArray[1][kDestroyerIndex], kDestroyer.def );
	
	if ( isSeaBattle() && is50PlusRules() )
		totalHits += calcHits( unitsArray[1][kCruiserIndex], kCruiser.def );
	
	totalHits += calcHits( unitsArray[1][kBomberIndex], kBomber.def );
	
	if ( is1940Rules() )
		totalHits += calcHits( unitsArray[1][kTacticalBomberIndex], kTacticalBomber.def );
	
	if ( isSeaBattle() ) {
		totalHits += calcHits( unitsArray[1][kAircraftCarrierIndex], kAircraftCarrier.def );
		totalHits += calcHits( unitsArray[1][kBattleshipIndex], kBattleship.def );
	}
	
	return totalHits;
}

function fillUnit( unitsArray, side, index, yesFill, which ) {
	if ( yesFill ) {
		unitsArray[side][index] = getIntValue( which );
	} else {
		unitsArray[side][index] = 0;
	}
}

// fills in our units from our form
function fillUnitsArray( unitsArray ) {
	
	var side = 0;
	var pre = "att";
	fillUnit( unitsArray, side, kInfIndex, isLandBattle() || isAmphibiousAssault(), pre + "Infantry" );
	fillUnit( unitsArray, side, kMechInfIndex, is1940Rules() && (isLandBattle() || isAmphibiousAssault()), pre + "MechanizedInfantry" );
	fillUnit( unitsArray, side, kArtIndex, isLandBattle() || isAmphibiousAssault(), pre + "Artillery" );
	fillUnit( unitsArray, side, kTankIndex, isLandBattle() || isAmphibiousAssault(), pre + "Tank" );
	
	fillUnit( unitsArray, side, kFighterIndex, true, pre + "Fighter" );
	fillUnit( unitsArray, side, kTacticalBomberIndex, is1940Rules(), pre + "TacticalBomber" );
	fillUnit( unitsArray, side, kBomberIndex, true, pre + "Bomber" );
	
	fillUnit( unitsArray, side, kTransportIndex, isSeaBattle(), pre + "Transport" );
	fillUnit( unitsArray, side, kSubmarineIndex, isSeaBattle(), pre + "Submarine" );
	fillUnit( unitsArray, side, kDestroyerIndex, isSeaBattle() || isAmphibiousAssault(), pre + "Destroyer" );
	fillUnit( unitsArray, side, kCruiserIndex, is50PlusRules() && (isSeaBattle() || isAmphibiousAssault()), pre + "Cruiser" );
	fillUnit( unitsArray, side, kAircraftCarrierIndex, isSeaBattle(), pre + "AircraftCarrier" );
	
	// only fill the fake battleship if we are purely a sea battle
	// 1940 rules, aircraft carriers also take 2 hits
	if ( isSeaBattle() && is1940Rules() )
		unitsArray[side][kBattleShipFakeIndex] = getIntValue( pre + "Battleship" ) + getIntValue( pre + "AircraftCarrier" );
	else
		fillUnit( unitsArray, side, kBattleShipFakeIndex, isSeaBattle(), pre + "Battleship" );
	
	fillUnit( unitsArray, side, kBattleshipIndex, isSeaBattle() || isAmphibiousAssault(), pre + "Battleship" );
	
	// defender
	side = 1;
	pre = "def";
	
	fillUnit( unitsArray, side, kInfIndex, isLandBattle() || isAmphibiousAssault(), pre + "Infantry" );
	fillUnit( unitsArray, side, kMechInfIndex, is1940Rules() && (isLandBattle() || isAmphibiousAssault()), pre + "MechanizedInfantry" );
	fillUnit( unitsArray, side, kArtIndex, isLandBattle() || isAmphibiousAssault(), pre + "Artillery" );
	fillUnit( unitsArray, side, kTankIndex, isLandBattle() || isAmphibiousAssault(), pre + "Tank" );
	
	fillUnit( unitsArray, side, kFighterIndex, true, pre + "Fighter" );
	fillUnit( unitsArray, side, kTacticalBomberIndex, is1940Rules(), pre + "TacticalBomber" );
	fillUnit( unitsArray, side, kBomberIndex, !isSeaBattle(), pre + "Bomber" );	// don't load bombers on sea battles
	
	fillUnit( unitsArray, side, kTransportIndex, isSeaBattle(), pre + "Transport" );
	fillUnit( unitsArray, side, kSubmarineIndex, isSeaBattle(), pre + "Submarine" );
	fillUnit( unitsArray, side, kDestroyerIndex, isSeaBattle() || isAmphibiousAssault(), pre + "Destroyer" );
	fillUnit( unitsArray, side, kCruiserIndex, is50PlusRules() && (isSeaBattle() || isAmphibiousAssault()), pre + "Cruiser" );
	fillUnit( unitsArray, side, kAircraftCarrierIndex, isSeaBattle(), pre + "AircraftCarrier" );
	
	// only fill the fake battleship if we are purely a sea battle
	if ( isSeaBattle() && is1940Rules() )
		unitsArray[side][kBattleShipFakeIndex] = getIntValue( pre + "Battleship" ) + getIntValue( pre + "AircraftCarrier" );
	else
		fillUnit( unitsArray, side, kBattleShipFakeIndex, isSeaBattle(), pre + "Battleship" );
	fillUnit( unitsArray, side, kBattleshipIndex, isSeaBattle() || isAmphibiousAssault(), pre + "Battleship" );

	
/*	unitsArray[0][kInfIndex] = getIntValue("attInfantry");
	unitsArray[0][kArtIndex] = getIntValue("attArtillery");
	unitsArray[0][kTankIndex] = getIntValue("attTank");
	unitsArray[0][kTransportIndex] = getIntValue("attTransport");
	unitsArray[0][kSubmarineIndex] = getIntValue("attSubmarine");
	unitsArray[0][kFighterIndex] = getIntValue("attFighter");
	unitsArray[0][kDestroyerIndex] = getIntValue("attDestroyer");
	if ( kRulesVersion == kRules50 )
		unitsArray[0][kCruiserIndex] = getIntValue("attCruiser");	
	unitsArray[0][kBomberIndex] = getIntValue("attBomber");
	unitsArray[0][kAircraftCarrierIndex] = getIntValue("attAircraftCarrier");
	
	unitsArray[0][kBattleShipFakeIndex] = getIntValue("attBattleship");
	unitsArray[0][kBattleshipIndex] = getIntValue("attBattleship");
	
	unitsArray[1][kInfIndex] = getIntValue("defInfantry");
	unitsArray[1][kArtIndex] = getIntValue("defArtillery");
	unitsArray[1][kTankIndex] = getIntValue("defTank");
	unitsArray[1][kTransportIndex] = getIntValue("defTransport");
	unitsArray[1][kSubmarineIndex] = getIntValue("defSubmarine");
	unitsArray[1][kFighterIndex] = getIntValue("defFighter");
	unitsArray[1][kDestroyerIndex] = getIntValue("defDestroyer");
	if ( kRulesVersion == kRules50 )
		unitsArray[1][kCruiserIndex] = getIntValue("defCruiser");	
	unitsArray[1][kBomberIndex] = getIntValue("defBomber");
	unitsArray[1][kAircraftCarrierIndex] = getIntValue("defAircraftCarrier");
	
	unitsArray[1][kBattleShipFakeIndex] = getIntValue("defBattleship");
	unitsArray[1][kBattleshipIndex] = getIntValue("defBattleship");
*/
}

function getIntValue( elementID ) {
	var val = document.getElementById(elementID).value;	
	
	// deal with null strings
	if ( val.length == 0 )
		val = 0;

	//if ( isNaN( val ) ) {
	//	val = 0;
	//}
	return parseInt(val);
}

function totalUnits( power, unitsArray ) {
	
	var total = 0;
	for ( i=0; i<5; i++ ) {
		total += parseInt( unitsArray[power][i] );
	}
	return total;
}

function createUnitArray() {
	unitsArray = new Array(2);
	for ( n=0; n<2; n++ ) {
		unitsArray[n] = new Array(kNumPieces);
	}
	
	for ( j=0; j<2; j++ ) {
		for ( k=0; k<kNumPieces; k++ ) {
			unitsArray[j][k] = "";	// not 0 because we don't want to fill zeros in for all values.. looks bad
		}
	}

	return unitsArray;
}

function calcIPCs() {
	unitsArray = createUnitArray();
	
	fillUnitsArray( unitsArray );
	document.getElementById( "attIPC" ).value = calcIPC( 0, unitsArray );
	document.getElementById( "defIPC" ).value = calcIPC( 1, unitsArray );
	
	// crammed this in here ... sorry
	document.getElementById( "mutualDestruction" ).value = 0;
	document.getElementById( "attVictory" ).value = 0;
	document.getElementById( "defVictory" ).value = 0;
}

function calcIPC( power, unitsArray ) {
	var total = 0;
	if ( isLandBattle() || isAmphibiousAssault() ) {
		total += unitsArray[power][kInfIndex] * kInfantry.cost;
		if ( is1940Rules() )
			total += unitsArray[power][kMechInfIndex] * kMechanizedInfantry.cost;
		total += unitsArray[power][kArtIndex] * kArtillery.cost;
		total += unitsArray[power][kTankIndex] * kTank.cost;
	}
	
	total += unitsArray[power][kFighterIndex] * kFighter.cost;
	
	// bombers don't defend at sea ... jeeez people are sticklers for this one
	if ( !(power==1 && isSeaBattle()) )	
		total += unitsArray[power][kBomberIndex] * kBomber.cost;
	
	if ( is1940Rules() )
		total += unitsArray[power][kTacticalBomberIndex] * kTacticalBomber.cost;
	
	if ( isSeaBattle() ) {
		total += unitsArray[power][kTransportIndex] * kTransport.cost;
		total += unitsArray[power][kSubmarineIndex] * kSubmarine.cost;
		total += unitsArray[power][kDestroyerIndex] * kDestroyer.cost;
		
		if ( is50PlusRules() )
			total += unitsArray[power][kCruiserIndex] * kCruiser.cost;
	
		total += unitsArray[power][kAircraftCarrierIndex] * kAircraftCarrier.cost;
		total += unitsArray[power][kBattleshipIndex] * kBattleship.cost;
	}
	
	return total;
}

function setTechMarks() {
	clearTechMarks();
	
	// our tech marks based on rules and settings
	// heavy bombers
	// super submarines
	// aa guns
	// advanced artillery
	// radar
	// jet fighters def
	// jet fighters off
	
	setTechMark( getSimOption(ktechAAGuns), "techMark"+"Fighter" );
	setTechMark( getSimOption(ktechAAGuns), "techMark"+"Bomber" );
	setTechMark( is1940Rules() && getSimOption(ktechAAGuns), "techMark"+"TacticalBomber" );

	setTechMark( isRevisedOr50() && getSimOption(ktechHeavyBombers), "techMark"+"Bomber" );
	setTechMark( isRevisedOr50() && getSimOption(ktechSuperSubmarines), "techMark"+"Submarine" );
	setTechMark( isRevisedOr50() && getSimOption(ktechJetFightersDef), "techMark"+"Fighter" );
	
	setTechMark( is50Rules() && getSimOption(ktechAdvancedArtillery), "techMark"+"Infantry" );
	setTechMark( is50Rules() && getSimOption(ktechAdvancedArtillery), "techMark"+"Artillery" );
	setTechMark( is50Rules() && getSimOption(ktechAAGuns) && getSimOption(ktechRadar), "techMark"+"Fighter" );
	setTechMark( is50Rules() && getSimOption(ktechAAGuns) && getSimOption(ktechRadar), "techMark"+"Bomber" );
	setTechMark( is1940Rules() && getSimOption(ktechAAGuns) && getSimOption(ktechRadar), "techMark"+"TacticalBomber" );

	setTechMark( is50Rules() && getSimOption(ktechJetFightersAtt), "techMark"+"Fighter" );
	
}


function battleshipFake() {
	this.att = 0;
	this.def = 0;
	this.cost = 0;
}

function infantry() {
	this.att = 1;
	this.def = 2;
	this.cost = 3;
}
function artillery() {
	this.att = 2;
	this.def = 2;
	this.cost = 4;
}

function tank() {
	this.att = 3;
	this.def = 3;
	this.cost = 5;
}
function transport() {
	this.att = 0;
	this.def = 1;
	this.cost = 8;
}
function submarine() {
	this.att = 2;
	this.def = 2;
	this.cost = 8;
}

function fighter() {
	this.att = 3;
	this.def = 4;
	this.cost = 10;
}
function destroyer() {
	this.att = 3;
	this.def = 3;
	this.cost = 12;
}
function bomber() {
	this.att = 4;
	this.def = 1;
	this.cost = 15;
}
function aircraftCarrier() {
	this.att = 1;
	this.def = 3;
	this.cost = 16;
}
function battleship() {
	this.att = 4;
	this.def = 4;
	this.cost = 24;
}


function battleshipFake50() {
	this.att = 0;
	this.def = 0;
	this.cost = 0;
}

function infantry50() {
	this.att = 1;
	this.def = 2;
	this.cost = 3;
}
function artillery50() {
	this.att = 2;
	this.def = 2;
	this.cost = 4;
}

function tank50() {
	this.att = 3;
	this.def = 3;
	this.cost = 5;
}

// improved shipyards
 // battleship 17
 // aircraft carrier 11
 // cruiser 10
 // destroyer 7
 // transport 6
 // submarine 5

 
function transport50( improved ) {
	this.att = 0;
	this.def = 0;
	this.cost = improved ? 6 : 7;
}
function submarine50(improved) {
	this.att = 2;
	this.def = 1;
	this.cost = improved ? 5 :6;
}

function fighter50() {
	this.att = 3;
	this.def = 4;
	this.cost = 10;
}
function destroyer50(improved) {
	this.att = 2;
	this.def = 2;
	this.cost = improved ? 7 :8;
}
function cruiser50(improved) {
	this.att = 3;
	this.def = 3;
	this.cost = improved ? 10 :12;
}

function bomber50() {
	this.att = 4;
	this.def = 1;
	this.cost = 12;
}
function aircraftCarrier50(improved) {
	this.att = 1;
	this.def = 2;
	this.cost = improved ? 11 :14;
}
function battleship50(improved) {
	this.att = 4;
	this.def = 4;
	this.cost = improved ? 17 :20;
}

// ORIGINAL -------------------------------------------


function battleshipFakeOriginal() {
	this.att = 0;
	this.def = 0;
	this.cost = 0;
}

function infantryOriginal() {
	this.att = 1;
	this.def = 2;
	this.cost = 3;
}
function artilleryOriginal() {
	this.att = 0;
	this.def = 0;
	this.cost = 0;
}

function tankOriginal() {
	this.att = 3;
	this.def = 2;
	this.cost = 5;
}

function fighterOriginal() {
	this.att = 3;
	this.def = 4;
	this.cost = 12;
}

function bomberOriginal() {
	this.att = 4;
	this.def = 1;
	this.cost = 15;
}

function transportOriginal() {
	this.att = 0;
	this.def = 1;
	this.cost = 8;
}
function submarineOriginal() {
	this.att = 2;
	this.def = 2;
	this.cost = 8;
}

function destroyerOriginal() {
	this.att = 0;
	this.def = 0;
	this.cost = 0;
}
function cruiserOriginal() {
	this.att = 0;
	this.def = 0;
	this.cost = 0;
}

function aircraftCarrierOriginal() {
	this.att = 1;
	this.def = 3;
	this.cost = 18;
}
function battleshipOriginal() {
	this.att = 4;
	this.def = 4;
	this.cost = 24;
}


// end ORIGINAL

// 1940
function mechanizedInfantry() {
	this.att 	= 1;
	this.def 	= 2;
	this.cost 	= 4;
}

function tacticalBomber() {
	this.att 	= 3;
	this.def 	= 3;
	this.cost 	= 11;
}

function tank1940() {
	this.att	= 3;
	this.def	= 3;
	this.cost	= 6;
}

function aircraftCarrier1940() {
	this.att	= 0;
	this.def	= 2;
	this.cost	= 16;
}

// end 1940


function loadPreset( unitsArray) {
	
	document.getElementById("attInfantry").value = unitsArray[0][kInfIndex];
	document.getElementById("attArtillery").value = unitsArray[0][kArtIndex];
	document.getElementById("attTank").value = unitsArray[0][kTankIndex];
	document.getElementById("attTransport").value = unitsArray[0][kTransportIndex];
	document.getElementById("attSubmarine").value = unitsArray[0][kSubmarineIndex];
	document.getElementById("attFighter").value = unitsArray[0][kFighterIndex];
	document.getElementById("attDestroyer").value = unitsArray[0][kDestroyerIndex];
	document.getElementById("attCruiser").value = unitsArray[0][kCruiserIndex];	
	document.getElementById("attBomber").value = unitsArray[0][kBomberIndex];
	document.getElementById("attAircraftCarrier").value = unitsArray[0][kAircraftCarrierIndex];
	document.getElementById("attBattleship").value = unitsArray[0][kBattleshipIndex];

	document.getElementById("defInfantry").value = unitsArray[1][kInfIndex];
	document.getElementById("defArtillery").value = unitsArray[1][kArtIndex];
	document.getElementById("defTank").value = unitsArray[1][kTankIndex];
	document.getElementById("defTransport").value = unitsArray[1][kTransportIndex];
	document.getElementById("defSubmarine").value = unitsArray[1][kSubmarineIndex];
	document.getElementById("defFighter").value = unitsArray[1][kFighterIndex];
	document.getElementById("defDestroyer").value = unitsArray[1][kDestroyerIndex];
	document.getElementById("defCruiser").value = unitsArray[1][kCruiserIndex];	
	document.getElementById("defBomber").value = unitsArray[1][kBomberIndex];
	document.getElementById("defAircraftCarrier").value = unitsArray[1][kAircraftCarrierIndex];
	document.getElementById("defBattleship").value = unitsArray[1][kBattleshipIndex];

	calcIPCs();

}

// preset examples
function presetA() {
	this.unitArray = createUnitArray();
	this.unitArray[0][kInfIndex] = 6;
	this.unitArray[0][kArtIndex] = 3;
	this.unitArray[0][kTankIndex] = 1;

	this.unitArray[1][kInfIndex] = 5;
	this.unitArray[1][kTankIndex] = 3;
}

function presetA1() {
	this.unitArray = createUnitArray();
	this.unitArray[0][kInfIndex] = 5;
	this.unitArray[0][kTankIndex] = 4;

	this.unitArray[1][kInfIndex] = 5;
	this.unitArray[1][kTankIndex] = 3;
}

function presetA2() {
	this.unitArray = createUnitArray();
	this.unitArray[0][kTankIndex] = 7;

	this.unitArray[1][kInfIndex] = 5;
	this.unitArray[1][kTankIndex] = 3;
}

function presetB() {
	this.unitArray = createUnitArray();
	this.unitArray[0][kFighterIndex] = 5;

	this.unitArray[1][kTransportIndex] = 5;
	this.unitArray[1][kDestroyerIndex] = 3;
}

function presetB1() {
	this.unitArray = createUnitArray();
	this.unitArray[0][kFighterIndex] = 8;

	this.unitArray[1][kTransportIndex] = 5;
	this.unitArray[1][kDestroyerIndex] = 3;
}

function presetB2() {
	this.unitArray = createUnitArray();
	this.unitArray[0][kFighterIndex] = 5;
	this.unitArray[0][kBomberIndex] = 2;

	this.unitArray[1][kTransportIndex] = 5;
	this.unitArray[1][kDestroyerIndex] = 3;
}

function presetC() {
	this.unitArray = createUnitArray();
	this.unitArray[0][kInfIndex] = 11;

	this.unitArray[1][kBattleshipIndex] = 3;
}

function parseURL() {
		
		if ( !(getQueryVariable("rules") === null) ) {
			
			changeRules( getQueryVariable("rules") );
			
			// do rules options
			setSimOptionCheck( "heavyBombers", 		getQueryVariable("heavyBombers") );
			setSimOptionCheck( "superSubmarines", 	getQueryVariable("superSubmarines") );
			setSimOptionCheck( "aaGuns", 			getQueryVariable("aaGuns") );
			setSimOptionCheck( "advancedArtillery", getQueryVariable("advancedArtillery") );
			setSimOptionCheck( "radar", 			getQueryVariable("radar") );
			setSimOptionCheck( "jetFightersAtt", 	getQueryVariable("jetFightersAtt") );
			setSimOptionCheck( "jetFightersDef", 	getQueryVariable("jetFightersDef") );

			// set battle type
			selectBattleType( getQueryVariable("battleType") );
			
			// set unit pieces
			var pre = "att";
			setPieceValue( pre+"Infantry", 			getQueryVariable(pre+"Infantry") );
			setPieceValue( pre+"MechanizedInfantry",getQueryVariable(pre+"MechanizedInfantry") );
			setPieceValue( pre+"Artillery", 		getQueryVariable(pre+"Artillery") );
			setPieceValue( pre+"Tank", 				getQueryVariable(pre+"Tank") );
			setPieceValue( pre+"Transport", 		getQueryVariable(pre+"Transport") );
			setPieceValue( pre+"Submarine", 		getQueryVariable(pre+"Submarine") );
			setPieceValue( pre+"Fighter", 			getQueryVariable(pre+"Fighter") );
			setPieceValue( pre+"TacticalBomber",	getQueryVariable(pre+"TacticalBomber") );
			setPieceValue( pre+"Destroyer", 		getQueryVariable(pre+"Destroyer") );
			setPieceValue( pre+"Cruiser", 			getQueryVariable(pre+"Cruiser") );
			setPieceValue( pre+"Bomber", 			getQueryVariable(pre+"Bomber") );
			setPieceValue( pre+"AircraftCarrier",	getQueryVariable(pre+"AircraftCarrier") );
			setPieceValue( pre+"Battleship", 		getQueryVariable(pre+"Battleship") );
			
			pre = "def";
			setPieceValue( pre+"Infantry", 			getQueryVariable(pre+"Infantry") );
			setPieceValue( pre+"MechanizedInfantry",getQueryVariable(pre+"MechanizedInfantry") );
			setPieceValue( pre+"Artillery", 		getQueryVariable(pre+"Artillery") );
			setPieceValue( pre+"Tank", 				getQueryVariable(pre+"Tank") );
			setPieceValue( pre+"Transport", 		getQueryVariable(pre+"Transport") );
			setPieceValue( pre+"Submarine", 		getQueryVariable(pre+"Submarine") );
			setPieceValue( pre+"Fighter", 			getQueryVariable(pre+"Fighter") );
			setPieceValue( pre+"TacticalBomber",	getQueryVariable(pre+"TacticalBomber") );
			setPieceValue( pre+"Destroyer", 		getQueryVariable(pre+"Destroyer") );
			setPieceValue( pre+"Cruiser", 			getQueryVariable(pre+"Cruiser") );
			setPieceValue( pre+"Bomber", 			getQueryVariable(pre+"Bomber") );
			setPieceValue( pre+"AircraftCarrier", 	getQueryVariable(pre+"AircraftCarrier") );
			setPieceValue( pre+"Battleship", 		getQueryVariable(pre+"Battleship") );
			
		} else {
			
			// default 
			changeRules(kRules50);
		}
	}
	
	function getURL() {
		
		var url = location.href.split("rules")[0];
		var firstPiece = false;
		
		if ( url.indexOf("?") == -1 )
			url += "?";
		
		if ( url.match(/\&$/) )
			firstPiece = true;	// don't add the &
		
		// rules options
		url += urlPiece( firstPiece, "rules", kRulesVersion, true );
		
		url += urlPiece( false, "heavyBombers", getSimOption("heavyBombers") );
		url += urlPiece( false, "superSubmarines", getSimOption("superSubmarines") );
		url += urlPiece( false, "aaGuns", getSimOption("aaGuns") );
		url += urlPiece( false, "advancedArtillery", getSimOption("advancedArtillery") );
		url += urlPiece( false, "radar", getSimOption("radar") );
		url += urlPiece( false, "jetFightersAtt", getSimOption("jetFightersAtt") );
		url += urlPiece( false, "jetFightersDef", getSimOption("jetFightersDef") );
		
		// battle type
		url += urlPiece( false, "battleType", document.getElementById("battleType").value );
		
		// pieces
		var pre = "att";
		url += urlPiece( false, pre+"Infantry", 			getIntValue(pre+"Infantry") );
		url += urlPiece( false, pre+"MechanizedInfantry", 	getIntValue(pre+"MechanizedInfantry") );
		url += urlPiece( false, pre+"Artillery", 			getIntValue(pre+"Artillery") );
		url += urlPiece( false, pre+"Tank", 				getIntValue(pre+"Tank") );
		url += urlPiece( false, pre+"Fighter", 				getIntValue(pre+"Fighter") );
		url += urlPiece( false, pre+"TacticalBomber", 		getIntValue(pre+"TacticalBomber") );
		url += urlPiece( false, pre+"Bomber", 				getIntValue(pre+"Bomber") );
		url += urlPiece( false, pre+"Transport", 			getIntValue(pre+"Transport") );
		url += urlPiece( false, pre+"Submarine", 			getIntValue(pre+"Submarine") );
		url += urlPiece( false, pre+"Destroyer", 			getIntValue(pre+"Destroyer") );
		url += urlPiece( false, pre+"Cruiser", 				getIntValue(pre+"Cruiser") );
		url += urlPiece( false, pre+"AircraftCarrier", 		getIntValue(pre+"AircraftCarrier") );
		url += urlPiece( false, pre+"Battleship", 			getIntValue(pre+"Battleship") );
		
		pre = "def";
		url += urlPiece( false, pre+"Infantry", 			getIntValue(pre+"Infantry") );
		url += urlPiece( false, pre+"MechanizedInfantry", 	getIntValue(pre+"MechanizedInfantry") );
		url += urlPiece( false, pre+"Artillery", 			getIntValue(pre+"Artillery") );
		url += urlPiece( false, pre+"Tank", 				getIntValue(pre+"Tank") );
		url += urlPiece( false, pre+"Fighter", 				getIntValue(pre+"Fighter") );
		url += urlPiece( false, pre+"TacticalBomber", 		getIntValue(pre+"TacticalBomber") );
		url += urlPiece( false, pre+"Bomber", 				getIntValue(pre+"Bomber") );
		url += urlPiece( false, pre+"Transport", 			getIntValue(pre+"Transport") );
		url += urlPiece( false, pre+"Submarine", 			getIntValue(pre+"Submarine") );
		url += urlPiece( false, pre+"Destroyer", 			getIntValue(pre+"Destroyer") );
		url += urlPiece( false, pre+"Cruiser", 				getIntValue(pre+"Cruiser") );
		url += urlPiece( false, pre+"AircraftCarrier", 		getIntValue(pre+"AircraftCarrier") );
		url += urlPiece( false, pre+"Battleship", 			getIntValue(pre+"Battleship") );

		return url;
	}
	
	function urlPiece( firstPiece, type, value, required ) {
		
		if ( !required ) {
			// don't add url pieces for stuff not used
			if ( (value==0) || (value == false) )
				return "";
		}
		
		var p = "";
		
		if ( !firstPiece ) 
			p += "&";
		
		p += type;
		p += "=";
		p += value;
		
		return p;
	}
	
	function getQueryVariable( variable ) {
		var query = window.location.search.substring(1);
		var vars = query.split("&");
		
		for (var i=0;i<vars.length;i++) {
			var pair = vars[i].split("=");
		
			if ( pair[0].toLowerCase() == variable.toLowerCase() ) {
				return pair[1];
			}
		}
		
		return null;
	}
