/*
======================================================================
 Liquid Nails: Calculator Functions.
 requires: prototype.js, formUtilities.js,
           areaTool.js, perimeterTool.js
======================================================================
*/

function my_init() {

	var body = $( 'body' );

	// Start page.
	if ( body.hasClassName( 'adhesiveCalcStart' ) ) {
		my_initStart();

	// Specs page.
	} else if ( body.hasClassName( 'adhesiveCalcSpecs' ) ) {
		my_initSpecs();

	// Success page.
	} else if ( body.hasClassName( 'adhesiveCalcSuccess' ) ) {
		my_initSuccess();

	// Error page.
	} else if ( body.hasClassName( 'adhesiveCalcError' ) ) {
		my_initError();

	} // End if.

} // End my_init().

// Utility function.
// Returns true if using IE6.
//
function my_util_isIE6() {

	return ( ( navigator.appName == "Microsoft Internet Explorer" ) && !( window.XMLHttpRequest ) );

} // End my_util_isIE6().

// Submits the entered data and navigates to the specified view.
//
function my_goToView( view ) {

	var my_calculatorForm = $( 'my_calculatorForm' );
	var my_view = $( 'my_view' );

	my_view.value = view;
	my_calculatorForm.submit();

} // End my_goToView().

// Resets the calculator.
//
function my_startOver() {

	window.location.href = 'calculator.do';

} // End my_startOver().

/*
----------------------------------------------------------------------
 Start page functions.
----------------------------------------------------------------------
*/

// Initializes the start page.
//
function my_initStart() {

	// Track the start page.
	pageTracker._trackPageview( '/products/calculator.do/start' );

} // End my_initStart().

// Validates the start page's form.
//
function my_validateStart() {

	var my_calculatorForm = $( 'my_calculatorForm' );

	// Check if at least one project is selected.
	var projectSelected = false;
	var projectsCheckBoxes = $$( 'div#my_startProjectsList input' );
	for ( var i = 0; i < projectsCheckBoxes.length; i++ ) {
		if ( projectsCheckBoxes[ i ].checked ) {
			projectSelected = true;
			break;
		} // End if.
	} // End for.

	// If not projects are selected, show an error message.
	if ( projectSelected == false ) {
		alert( 'Please select a project.' );
		return false;
	} // End if.

	return true;

} // End my_validateStart().

// Show the starting project description for the specified project ID.
//
function my_showStartDesc( projectId ) {

	// Hide all project descriptions.
	var items = $$( 'div.my_startDesc' ); 
	for ( var i = 0; i < items.length; i++ ) {
		var item = items[ i ];
		item.removeClassName( 'my_startDescOn' );
		item.addClassName( 'my_startDescOff' );
	} // End for.

	// Show the specified project description.
	var selectedItem = $( 'my_startDesc_' + projectId );
	if ( selectedItem != null ) {
		selectedItem.removeClassName( 'my_startDescOff' );
		selectedItem.addClassName( 'my_startDescOn' );
	} // End if.

} // End my_showStartDesc().

// Selects/deselects a starting project list item.
//
function my_selectedProjectListItem( listItem, selected ) {

	listItem.className = ( ( selected ) ? 'my_projectsListItemOn' : 'my_projectsListItemOff' );

} // End my_selectedProjectListItem().

/*
----------------------------------------------------------------------
 Specs page functions.
----------------------------------------------------------------------
*/

var my_tools = new Array();
var my_currentTool = null;
var my_currentFieldId = null;
var my_savedSegmentLists = new Array();

// Initializes the specs page.
//
function my_initSpecs() {

	// Track the specs page.
	pageTracker._trackPageview( '/products/calculator.do/specs' );

	// Have the paneling type control the function of the wainscoting
	// area and chair rail length.
	var panelingType = $( 'panelingType' );
	if ( panelingType != null ) {
		Event.observe( panelingType, 'change', my_onPanelingTypeChange );
		my_onPanelingTypeChange();
	} // End if.

	// Add the tools.
	my_tools[ 'area' ] = new AreaTool();
	my_tools[ 'perimeter' ] = new PerimeterTool();
	my_tools[ 'window' ] = new WindowTool();
	my_tools[ 'door' ] = new DoorTool();

	// Add an onScroll event for IE6 to position the tools.
	if ( my_util_isIE6() ) {
		my_onScrollSpecs();
		Event.observe( window, 'scroll', my_onScrollSpecs );
	} // End if.

} // End my_initSpecs().

// Added scroll event for IE6 only.
//
function my_onScrollSpecs() {

	// Keep the tools on the screen. IE6 does not support fixed positioning.
	var iebody = ( document.compatMode && document.compatMode != "BackCompat" )? document.documentElement : document.body;
	var dsoctop = document.all? iebody.scrollTop : pageYOffset;
	var my_toolsContainer = $( 'my_toolsContainer' );
	my_toolsContainer.style[ 'top' ] =dsoctop;

} // End my_onScrollSpecs().

// Validates the specs page's form.
// If validateAll is false, only the integer values are validated.
//
function my_validateSpecs( validateAll ) {

	// Specify all the fields that have integer values.
	var integerFields = new Array(
		'wallIncludedArea',
		'wallExcludedArea',
		'ceilingIncludedArea',
		'ceilingExcludedArea',
		'floorIncludedArea',
		'floorExcludedArea',
		'cornerBeadLengthFeet',
		'cornerBeadLengthInches',
		'wainscotingArea',
		'chairRailLengthFeet',
		'chairRailLengthInches',
		'crownIncludedPerimFeet',
		'crownIncludedPerimInches',
		'crownExcludedPerimFeet',
		'crownExcludedPerimInches',
		'crownLayerCount',
		'baseboardIncludedPerimFeet',
		'baseboardIncludedPerimInches',
		'baseboardExcludedPerimFeet',
		'baseboardExcludedPerimInches',
		'windowIncludedPerimFeet',
		'windowIncludedPerimInches',
		'doorIncludedPerimFeet',
		'doorIncludedPerimInches'
	);

	// Make sure all integer fields have integer values.
	// Note: convToInteger is located in 'formUtilities.js'.
	for ( var i = 0; i < integerFields.length; i++ ) {
		var field = $( integerFields[ i ] );
		if ( field != null ) field.value = convToInteger( field.value );
	} // End for.

	if ( validateAll ) {

		// Determine if the user is requesting the full results.
		var showFullResults = $( 'showFullResults' );
		var showFullResultsValue = false;
		if ( showFullResults != null ) showFullResultsValue = ( showFullResults.value == 'true' );

		// Check the drywall thickness dropdown.
		var drywallProductId = $( 'drywallProductId' );
		if ( showFullResultsValue && ( drywallProductId != null ) && ( drywallProductId.value == '' ) ) {
			alert( 'Please select a drywall sheet thickness.' );
			drywallProductId.focus();
			return false;
		} // End if.

		// Check the paneling type dropdown.
		var panelingType = $( 'panelingType' );
		if ( panelingType != null ) {
	
			// Make sure a value is selected.
			if ( panelingType.value == '' ) {
				alert( 'Please select a paneling type.' );
				panelingType.focus();
				return false;
	
			// If wainscoting is used, make sure there is a specified wainscoting area.
			} else if ( panelingType.value == 'wainscoting' ) {
				var wainscotingArea = $( 'wainscotingArea' );
				if ( ( wainscotingArea != null ) && ( wainscotingArea.value == 0 ) ) {
					alert( 'Please specify a wainscoting wall area.' );
					wainscotingArea.focus();
					return false;
				} // End if. 
	
			} // End if.
		} // End if.

		// Make sure the crown layer count is at least 1.
		var crownLayerCount = $( 'crownLayerCount' );
		if ( ( crownLayerCount != null ) && ( crownLayerCount.value < 1 ) ) {
			alert( 'The number of crown molding layers must be at least 1.' );
			crownLayerCount.focus();
			return false;
		} // End if.

	} // End if.

	return true;

} // End my_validateSpecs().

// Change event for the paneling type dropdown.
//
function my_onPanelingTypeChange() {

	var panelingType = $( 'panelingType' );
	var wainscotingArea = $( 'wainscotingArea' );
	var chairRailLengthFeet = $( 'chairRailLengthFeet' );
	var chairRailLengthInches = $( 'chairRailLengthInches' );

	// Determine if the user selected wainscoting.
	var useWainscoting = ( panelingType.value == 'wainscoting' );

	// Enable/disable the fields that depend on wainscoting.
	if ( wainscotingArea != null ) wainscotingArea.disabled = !useWainscoting;
	if ( chairRailLengthFeet != null ) chairRailLengthFeet.disabled = !useWainscoting;
	if ( chairRailLengthInches != null ) chairRailLengthInches.disabled = !useWainscoting;

} // End my_onPanelingTypeChange().

// Opens the specified tool.
//
function my_openTool( toolId, fieldId, toolParam ) {

	// Do not open more than one tool at one time.
	if ( my_currentTool != null ) return;

	// Get the specified tool.
	var tool = my_tools[ toolId ];
	if ( tool == null ) return;

	// Track the tool usage.
	pageTracker._trackPageview( '/products/calculator.do/specs/tools/' + fieldId );

	// Reference the current tool.
	my_currentTool = tool;

	// Reset the tool.
	my_currentTool.reset();

	// Restore the field's saved segments.
	var savedSegments = my_savedSegmentLists[ fieldId ];
	my_currentTool.setSegments( savedSegments );

	// Save the ID of the field that will be populated.
	my_currentFieldId = fieldId;

	// Show the tools container.
	var my_toolsContainer = $( 'my_toolsContainer' );
	my_toolsContainer.className = 'my_toolsContainerOn';

	// Show the tools backround.
	var my_toolBg = $( 'my_toolBg' );
	my_toolBg.className = 'my_toolBgOn';
	my_controlAllSelectLists( false );

	// Set the custom tool parameter.
	my_currentTool.setParam( toolParam );

	// Show the tool.
	my_currentTool.show();

	// Make sure the tool is on the screen for IE6.
	if ( my_util_isIE6() ) my_onScrollSpecs();

}// End my_openTool().

// Closes the current tool
//
function my_closeTool( populateField ) {

	var success = false;

	// If populating the field...
	if ( populateField && ( my_currentTool != null ) && ( my_currentFieldId != null ) ) {

		// Populate the field.
		success = my_currentTool.saveValue( my_currentFieldId );

		// Save the field's segments.
		// Be sure to copy the array -- not just reference it.
		if ( success ) {
			var segments = my_currentTool.getSegments();
			my_savedSegmentLists[ my_currentFieldId ] = segments.slice( 0 );
		} // End if.

	} else {
		success = true;
	} // End if.

	if ( success ) {

		// Hide the current tool.
		if ( my_currentTool != null ) my_currentTool.hide();

		// Clear the tool and field references.
		my_currentTool = null;
		my_currentFieldId = null;

		// Hide the tools container.
		var my_toolsContainer = $( 'my_toolsContainer' );
		my_toolsContainer.className = 'my_toolsContainerOff';

		// Hide the tools background.
		var my_toolBg = $( 'my_toolBg' );
		my_toolBg.className = 'my_toolBgOff';
		my_controlAllSelectLists( true );

	} // End if.

} // End my_closeTool().

// For IE6- only. This shows/hides all select lists.
// Select lists show through the tool background on IE6-.
//
function my_controlAllSelectLists( show ) {

	// Process this for IE6- browsers.
	if ( my_util_isIE6() == false ) {
		return;
	} // End if.

	// Show or hide all the select lists.
	var lists = $$( 'select' );
	for ( var i = 0; i < lists.length; i++ ) {
		var list = lists[ i ];
		if ( list.hasClassName( 'nocontrol' ) == false ) {
			if ( show ) {
				list.removeClassName( 'hidden' );
			} else {
				if ( list.hasClassName( 'hidden' ) == false ) list.addClassName( 'hidden' );
			} // End if.
		} // End if.
	} // End for.

} // End my_controlAllSelectLists().

/*
----------------------------------------------------------------------
 Success page functions.
----------------------------------------------------------------------
*/

// Initializes the success page.
//
function my_initSuccess() {

	// Track the success page.
	pageTracker._trackPageview( '/products/calculator.do/success' );

} // End my_initSuccess().

// Prints the calculator results.
//
function my_printResults( resultsType ) {

	var body = $( 'body' );

	// Set the proper body class to print the specified result type.
	if ( resultsType == 'invoice' ) {
		body.removeClassName( 'adhesiveCalcPrintMaterials' );
		body.addClassName( 'adhesiveCalcPrintInvoice' );
	} else {
		body.addClassName( 'adhesiveCalcPrintMaterials' );
		body.removeClassName( 'adhesiveCalcPrintInvoice' );
	} // End if.

	// Track the print usage.
	pageTracker._trackPageview( '/products/calculator.do/success/print/' + resultsType );

	// Print the page.
	print( document );

	// Set the print style back to the materials list.
	setTimeout( 'my_resetPrintResultsStyle();', 1000 );

} // End my_printResults().

function my_resetPrintResultsStyle() {

	var body = $( 'body' );

	// Set the body class back to materials list.
	body.addClassName( 'adhesiveCalcPrintMaterials' );
	body.removeClassName( 'adhesiveCalcPrintInvoice' );

} // End my_resetPrintResultsStyle().

/*
----------------------------------------------------------------------
 Error page functions.
----------------------------------------------------------------------
*/

// Initializes the error page.
//
function my_initError() {
	// Nothing to initialize.
} // End my_initError().

/*
----------------------------------------------------------------------
*/

// Initialize the calculator.
//
Event.observe( window, 'load', my_init );
