function resetError() {
  $( "reflector-alert" ).update().setStyle({
    padding: 0,
    backgroundColor: "#FFF"
  });
}

function handleError() {
  $( "reflector-alert" ).setStyle({
    padding: "10px",
    backgroundColor: "#900",
    color: "#FFF",
    fontWeight: "bold",
    textAlign: "center"
  });
  $( "totalsqft" ).clear();
  $( "costsqft" ).clear();
  $( "totalcost" ).clear();
  $( "shiphandle" ).clear();
  $( "grandtotal" ).clear();
}

function validatePricing() {
  if ( !$( "deluxe" ).checked && !$( "plus" ).checked && !$( "standard" ).checked ) {
    $( "reflector-alert" ).update( "Please select the desired reflector type." );
  } else if ( $F( "width" ).blank() ) {
    $( "reflector-alert" ).update( "Please enter the desired width, in inches." );
  } else if ( isNaN( $F( "width" ) ) ) {
    $( "reflector-alert" ).update( "Please enter a numeric value, in inches, for the desired width." );
  } else if ( $F( "height" ).blank() ) {
    $( "reflector-alert" ).update( "Please enter the desired height, in inches." );
  } else if ( isNaN( $F( "height" ) ) ) {
    $( "reflector-alert" ).update( "Please enter a numeric value, in inches, for the desired height." );
  } else if ( Math.ceil( ( $F( "width" ) * $F( "height" ) ) / 144 ) < 1 ) {
    $( "reflector-alert" ).update( "The dimensions must be greater than or equal to one square foot." );
  } else if ( Math.ceil( ( $F( "width" ) * $F( "height" ) ) / 144 ) > 16 ) {
    $( "reflector-alert" ).update( "For any reflectors greater than 16 feet, please contact Frigo Design for special shipping/handling costs." );
  } else {
    return true;
  }
  return false;
}

function calculate() {
  resetError();
  
  if ( validatePricing() ) {
    var totalSqFt = Math.ceil( ( $F( "width" ) * $F( "height" ) ) / 144 );
    $( "totalsqft" ).value = totalSqFt;
    
    var costPerSqFt = 0;
    if ( $( "deluxe" ).checked ) costPerSqFt = 12;
    else if ( $( "plus" ).checked ) costPerSqFt = 10;
    else if ( $( "standard" ).checked ) costPerSqFt = 8;
    $( "costsqft" ).value = costPerSqFt + ".00";
    
    var totalCost = totalSqFt * costPerSqFt;
    $( "totalcost" ).value = totalCost + ".00";
    
    var shipHand = 0;
    if ( $F( "totalsqft" ) <= 6 ) shipHand = 24;
    else if ( $F( "totalsqft" ) <= 9 ) shipHand = 34;
    else if ( $F( "totalsqft" ) <= 16 ) shipHand = 49;
    $( "shiphandle" ).value = shipHand + ".00";
    
    var grandTotal = totalCost + shipHand;
    $( "grandtotal" ).value = grandTotal + ".00";
    
    $( "calc" ).value = "Recalculate";
    
    $( "place-order" ).focus();
  } else {
    handleError();
  }
}

Event.observe( window, "load", function() {
  $( "clear-btn" ).observe( "click", function() {
    resetError();
    $( "calc" ).value = "Calculate Pricing";
  } );
  $( "calc" ).observe( "click", calculate );
  $( "shipping" ).observe( "click", function() { $( "ship_info" ).toggle(); } );
});
