"use strict";

/**
 * @fileOverview Contains functions used by us open individual tickets page
 */



/**
* Removes whitespace from a string
*/
function trim(str) {
    return str.split(' ').join('');
}

/**
 * Populate the ticket order form
 *
 * @param {Object} data Data used by the form
 */
function setupUSOpenTicketForm(data) {
  var l, j = 0, html = '', i = 0, levelNames = {
    grounds: 'Grounds',
    promenade: 'Promenade',
    loge_df: 'Loge D-F',
    loge_ac: 'Loge A-C',
    courtside: 'Courtside'
  };

  // Bad data
  if (typeof data !== 'object') {
    return false;
  }

  // Populate events and level options
  if (typeof data.events === 'object') {
    for (i = 0; i < data.events.length; i = i + 1) {
      if (data.events[i].session != 'NO PLAY') {
      html += '<tr' + ((i % 2 === 0) ? ' class="even"' : '') + '>';
      html += '<td class="c1">';
      html += '<input type="hidden" name="ticket-date-' + i + '" value="' + data.events[i].date + ', ' + data.events[i].time + '" />';
      html += '<input type="hidden" name="ticket-cost-' + i + '" id="ticket-cost-' + i + '" value="0" />';
      html += '<input type="hidden" name="ticket-round-' + i + '" value="' + data.events[i].session + '" />'; 
      html += '<input type="hidden" id="ticket-session-' + i + '" value="' + data.events[i].session + '" />';
      html += '<strong>' + data.events[i].date + '</strong><br>' + data.events[i].time;
      html += '</td>';

      if (typeof data.events[i].session === 'undefined') {
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
        html += '<td style="text-align:center;">N/A</td>';
      } else {
        if (data.events[i].session != 'NO PLAY') {	    
            html += '<td class="c2"><strong>' + data.events[i].session + '</strong><br>' + data.events[i].round + '</td>';
        } else {
	        html += '<td class="c2"><div style="text-align:center;">N/A</div></td>';
	    }
	
	    j = 3;
    	
	    html += '<td class="c3a">';

        if (data.events[i].session != 'NO PLAY') {	    
    	    html +='<input style="float:left;display:block;" class="choose-level" checked="checked" type="radio" name="ticket-level-' + i + '" id="ticket-level-' + i + '" value="None">';
	        html += '<div style="float:left;"><label for="choose-ticket-' + i + '-0"><strong>None</strong></div>';
	    } else {
	        html +='<div style="text-align:center;">N/A</div>';
	    }
	    
	    html += '</td>';
	
	    if (typeof data.events[i].prices === 'object') {
	      for (l in data.events[i].prices) {

	        if (data.events[i].prices.hasOwnProperty(l)) {
	          html += '<td class="c' + j + '" id="choose-ticket-cell-' + i + '-' + trim(l) + '">';
	          
	          if (typeof data.events[i].prices[l] !== 'undefined' && data.events[i].session != 'NO PLAY' && data.events[i].prices[l] != 'Sold Out' && data.events[i].prices[l] != 'N/A') {
	            html += '<input style="float:left;display:block;" class="choose-level" type="radio" name="ticket-level-' + i + '" id="ticket-level-' + i + '" value="' + l + '">';
	            html += '<div style="float:left;"><label for="ticket-level-' + i + '"><strong>' + l + '</strong><br>';
		        html += '$' + data.events[i].prices[l] + ' ea.</label></div>';
	          } else {
	            if (data.events[i].prices[l] == 'Sold Out') {
	                html += '<div style="text-align:center;">Sold Out</div>';
	            } else {
    	            html += '<div style="text-align:center;">N/A</div>';
    	        }
	          }
	          
	          html += '</td>';
	          j = j + 1;
	        }
	      }
	      
            if (data.events[i].session != 'NO PLAY') {	    
	          html += '<td class="c8"><input id="ticket-quantity-' + i + '" name="ticket-quantity-' + i + '" class="ticket-quantity" type="text" style="text-align:center;"></td>';
	          html += '<td class="c9" id="ticket-subtotal-' + i + '"></td>';
	        } else {
	            html +='<td><div style="text-align:center;">N/A</div></td>';
	            html +='<td><div style="text-align:center;">N/A</div></td>';
	        }
	    } else {
	      html += '<td colspan="7"></td>';
	    }
      }
      
      html += '</tr>';
      }
    }
    $('#orderform-table tbody').append(html);
    $('#orderform-table').after('<input type="hidden" name="number-rows" value="' + data.events.length + '" />');
  }

  setupShippingForm(data);
}

/** 
 * Calculate totals for ticket form
 * 
 * @param {Object} formdata Data for the form
 */
function calculateUSOpenTicketForm(data) {
  var ticketprice, roundtotal, subtotal = 0, insurance = 0, shipping = 0, i;

  // Add up ticket totals
  for (i = 0; i < data.events.length; i = i + 1) {
    roundtotal = 0;
    
    if (typeof data.events[i].prices === 'object') {
        $('input[name=\'ticket-level-' + i + '\']').each(function(){
            if (this.checked && trim($(this).val()) != 'None') {
                $('#choose-ticket-cell-' + i + '-' + trim($(this).val())).addClass('selected');
            } else {
                $('#choose-ticket-cell-' + i + '-' + trim($(this).val())).removeClass('selected');
            }
        });
    };

    if ($('input[name=ticket-level-' + i + ']:checked').val()) {
        if ($('input[name=ticket-level-' + i + ']:checked').val() != 'None') {
          ticketprice = data.events[i].prices[$('input[name=ticket-level-' + i + ']:checked').val()];

          // If these tickets are not sold out, not available or need a call
          if (ticketprice != 'Sold Out' &&
              ticketprice != 'N/A' &&
              ticketprice != 'Call') {
              $('#ticket-cost-' + i).val(ticketprice);

              // If this level is the one that has been selected, give focus to the quantity input
              if (selectedUSOpenLevel == $('input[name=ticket-level-' + i + ']').attr('id')) {
                  $('#ticket-quantity-' + i).focus();
              }
              
              roundtotal = ticketprice * ($('#ticket-quantity-' + i).val() * 1);
              $('#ticket-quantity-' + i).show();
          } else {
              //$('#ticket-price-' + i).html('<input type="hidden" name="ticket-cost-' + i + '" value="' + ticketprice + '" />' + ticketprice);
              $('#ticket-cost-' + i).val(ticketprice);
              $('#ticket-quantity-' + i).hide();
          }
        }
        
        subtotal += roundtotal;
        $('#ticket-subtotal-' + i).html(roundtotal === 0 ? '<input type="hidden" name="ticket-subtotal-amt-' + i + '" value="0" />' : '<input type="hidden" name="ticket-subtotal-amt-' + i + '" value="' + roundtotal.toFixed(2) + '" /> $' + roundtotal.toFixed(2));
      } 
    }

  // Set the subtotal
  //$('#order-subtotal').html((subtotal === 0) ? '' : '$' + subtotal.toFixed(2));
  $('#order-subtotal').html((subtotal === 0) ? '<input type="hidden" name="order-subtotal" value="0" />' : '<input type="hidden" name="order-subtotal" value="' + subtotal.toFixed(2) + '" /> $' + subtotal.toFixed(2));

  // Add weather insurance if applicable
  if ($('#order-weather-insurance').attr('checked')) {
    insurance = subtotal * $('#insurance-rate').val();
  }
  
  $('#weather-insurance-value').html('<input type="hidden" name="weather-insurance" value="' + insurance.toFixed(2) + '" /> $' + insurance.toFixed(2));

  // Based on the event and the total cost of the order apply shipping appropriately
  var applyShipping = false;

  if (typeof usOpenShipping != "undefined") {
    if (subtotal < 400) {
        applyShipping = true;
    }
  } else if (typeof frenchOpenShipping != "undefined") {
    if (subtotal < 800) {
        applyShipping = true;
    }
  } else {
    applyShipping = true;
  }

  if (applyShipping) {
    shipping = data.countries[$('#shipping-country').val()].shipping;
  }
  
  $('#shipping-total').html('<input type="hidden" name="shipping" value="' + shipping.toFixed(2) + '" /> $' + shipping.toFixed(2));
}

/** 
 * Validate ticket form
 * 
 * @param {Object} formdata Data for the form
 */
function validateUSOpenTicketForm(data) {
  var ticketprice, roundtotal, subtotal = 0, insurance = 0, shipping = 0, i;

  // Add up ticket totals
  for (i = 0; i < data.events.length; i = i + 1) {
    roundtotal = 0;
    
    if ($('input[name=ticket-level-' + i + ']:checked').val()) {
        if ($('input[name=ticket-level-' + i + ']:checked').val() != 'None') {
          ticketprice = data.events[i].prices[$('input[name=ticket-level-' + i + ']:checked').val()];

          // If these tickets are not sold out, not available or need a call
          if (ticketprice != 'Sold Out' &&
              ticketprice != 'N/A' &&
              ticketprice != 'Call') {
                  roundtotal = ticketprice * ($('#ticket-quantity-' + i).val() * 1);
          }
        }
        subtotal += roundtotal;
      }
    }

  if (!subtotal) {
    alert ('Please select tickets to purchase before continuing.');

    return false;
  } else {
    return true;
  }
}

