"use strict";

/**
 * @fileOverview Contains global functions used by CTT site
 * @author <a href="mailto:dennyd@triple-d.us">Denny Daugherty</a>
 */

/*global $,document */


<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 8;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 0;
// -----------------------------------------------------------------------------
// -->


/**
 * Display the "Our Promise To You" div and hide the button that opens it
 */
function showPromise() {
  $('#our-promise-button').hide();
  $('#our-promise').show();

  return false;
}

/**
 * Hide the "Our Promise To You" div and show the button to open it
 */
function hidePromise() {
  $('#our-promise').hide();
  $('#our-promise-button').show();

  return false;
}

/**
 * Toggle the login form
 */
function toggleLoginForm() {
  $('#top-menu-login').toggle();

  return false;
}

/**
 * Sets up the "Our Promise To You" div
 */
function setupPromise() {
  // Display elements requiring javascript
  $('#our-promise-button').show();

  // Setup events
  $('#our-promise-button').bind('click', showPromise);
  $('#our-promise-close-button').bind('click', hidePromise);
}

/**
 * Sets up the loging form
 */
function setupLoginForm() {
  // Setup placeholders
  $('#login-username').placeholder();
  $('#login-password').placeholder();

  $('#top-login #top-login-anchor').bind('click', toggleLoginForm);
  $('#top-login #top-logout-anchor').bind('click', logout);
  $('#top-menu-login-submit').bind('click', login);


  $('html > *').click(function (e) {
    var $clicked = $(e.target);
    
    if ($clicked.is('#top-menu-login-container') || $clicked.parents().is('#top-menu-login-container')) {
      return false;
    }

    $('#top-menu-login').hide();
  });
}

/**
 * Shows or hides the shipping information fieldset
 */
function updateBookingShipping() {
  if ($('#shipping-different').attr('checked')) {
    $('#shipping-information').show();
  }
  else {
    $('#shipping-information').hide();
  }
}

/**
 * Shows or hides the wire transfer information fieldset
 */
function updateBookingWireTransfer() {
  if ($('#payment-credit-card').attr('checked')) {
    $('#credit-card-info').show();
    $('#wire-info').hide();
    $('#check-info').hide();
  } else if ($('#payment-wire').attr('checked')) {
    $('#credit-card-info').hide();
    $('#wire-info').show();
    $('#check-info').hide();
  } else {
    $('#credit-card-info').hide();
    $('#wire-info').hide();
    $('#check-info').show();
  }
}

/**
 * Set up events for booking form
 */
function setupBookingForm() {
  $('#shipping-different').change(updateBookingShipping);
  $('#payment-credit-card').change(updateBookingWireTransfer);
  $('#payment-wire').change(updateBookingWireTransfer);
  $('#payment-check').change(updateBookingWireTransfer);

  updateBookingShipping();
  updateBookingWireTransfer();
}

/**
 * Populate values for the shipping options
 * 
 * @param {Object} data Data used by the form
 */
function setupShippingForm(data) {
  // Populate shipping countries
  if (typeof data.countries === 'object') {
    html = '';
    for (c in data.countries) {
      if (data.countries.hasOwnProperty(c)) {
        html += '<option value="' + c + '"';
        html += (c === 'US') ? ' selected="selected"' : '';
        html += '>' + data.countries[c].name + '</option>';
      }
    }
    $('#shipping-country').append(html);
  }
}

/**
 * Populate values for the shipping options
 * 
 * @param {Object} data Data used by the form
 */
function setupBillingShippingForm(data, country) {
  // Populate shipping countries
  if (typeof data.countries === 'object') {
    html = '';
    for (c in data.countries) {
      if (data.countries.hasOwnProperty(c)) {
        html += '<option value="' + c + '"';
        html += (c === country) ? ' selected="selected"' : '';
        html += '>' + data.countries[c].name + '</option>';
      }
    }
    $('#shipping-country').append(html);
    $('#billing-country').append(html);
  }
}


/**
 * Populate the ticket order form
 *
 * @param {Object} data Data used by the form
 */
function setupTicketForm(data) {
  var e, l, c, html = '', i = 0, j;

  // 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) {
      html += '<tr>';

      html += '<td class="c2">';
      html += data.events[i].date;
      html += '<input type="hidden" name="ticket-date-' + i + '" value="' + data.events[i].date + '" />';
      html += '</td>';

      html += '<td class="c1">';
      html += (typeof data.events[i].round === 'undefined') ? 'NO PLAY' : data.events[i].round;
      html += (typeof data.events[i].round === 'undefined') ? '<input type="hidden" name="ticket-round-' + i + '" value="NO PLAY" />' : '<input type="hidden" name="ticket-round-' + i + '" value="' + data.events[i].round + '" />'; 
      html += '</td>';
      
      html += '<td class="c3">';
      
      var ticketsAvailable = false
      var interHTML = ''
      
      if (typeof data.events[i].prices === 'object') {
        interHTML = '<select class="choose-level" id="ticket-level-' + i + '" name="ticket-level-' + i + '">';
        
        for (l in data.events[i].prices) {
          ticketprice = data.events[i].prices[l];

          if (ticketprice != 0) { 
            ticketsAvailable = true
          
              if (data.events[i].prices.hasOwnProperty(l)) {
                interHTML += '<option value="' + l + '" ';
                
                // If the tournament is the US Open and this is the promenade level
                // set it to selected by default
                if (typeof usOpenShipping != "undefined") {
                    if (l == 'promenade') {
                    interHTML += 'SELECTED';
                    }
                }
                
                interHTML += '>';
                interHTML += l + '</option>';
              }
          }
        }
      
        interHTML += '</select>';
      }
      
      if (ticketsAvailable) {
        html += interHTML;      
      }
      
      html += '</td><td class="c4" id="ticket-price-' + i + '"></td>';
      html += '<td class="c5">';
      
      if (typeof data.events[i].prices === 'object' && ticketsAvailable) {
        html += '<input id="ticket-quantity-' + i + '" name="ticket-quantity-' + i + '" class="ticket-quantity" type="text" style="text-align: center;">';
      }
      
      html += '</td>';
      html += '<td class="c6" id="ticket-subtotal-' + i + '"></td>';
      html += '</tr>'
    }
    
    $('#orderform-table tbody').append(html);
    $('#orderform-table').after('<input type="hidden" name="number-rows" value="' + data.events.length + '" />');
  }

  setupShippingForm(data);
}

/**
 * Populate the tickets form, step3 of customize
 *
 * @param {Object} data Data used by the form
 */
function setupCustomizeTicketsForm(data) {
  var i, l, html = '', totalEvents;

  if (typeof data !== 'object') {
    return false;
  }
  
  var checkInDate = new Date($('#check-in-date').val());
  var checkOutDate = new Date($('#check-out-date').val());

  if (typeof data.events === 'object') {
    totalEvents = data.events.length;
    
    for (i = 0; i < totalEvents; i = i + 1) {
      var ticketDate = new Date(data.events[i].dateNew);
    
      if (ticketDate >= checkInDate &&
          ticketDate <= checkOutDate) {
          html += '<tr>';

          html += '<td class="c2">';
          html += data.events[i].date;
          html += '<input type="hidden" id="ticket-date-' + i + '" value="' + data.events[i].date + '" />';
          html += '<input type="hidden" id="ticket-date-new-' + i + '" value="' + data.events[i].dateNew + '" />';
          html += '</td>';
          html += '<td class="c1">';
          html += '<label for="ticket-round-' + i + '">' + data.events[i].round + '</label>';
          html += '<input type="hidden" id="ticket-session-' + i + '" value="' + data.events[i].round + '" />';
          html += '</td>';
          
          html += '<td>';


          var ticketsAvailable = false
          var interHTML = ''
          
          if (typeof data.events[i].prices === 'object') {
            interHTML = '<select class="choose-level" id="ticket-level-' + i + '" name="ticket-level-' + i + '">';
            
            for (l in data.events[i].prices) {
              ticketprice = data.events[i].prices[l];

              if (ticketprice != 0) { 
                ticketsAvailable = true
              
                  if (data.events[i].prices.hasOwnProperty(l)) {
                    interHTML += '<option value="' + l + '" ';
                    
                    // If the tournament is the US Open and this is the promenade level
                    // set it to selected by default
                    if (typeof usOpenShipping != "undefined") {
                        if (l == 'promenade') {
                        interHTML += 'SELECTED';
                        }
                    }
                    
                    interHTML += '>';
                    interHTML += l + '</option>';
                  }
              }
            }
          
            interHTML += '</select>';
          }
          
          if (ticketsAvailable) {
            html += interHTML;      
          }

          html += '</td>';
          html += '<td class="c4">';

          if (typeof data.events[i].prices === 'object' && ticketsAvailable) {
              html += '<input id="ticket-quantity-' + i + '" name="ticket-quantity-' + i + '" class="ticket-quantity" type="text" style="text-align: center;">';
              html += '<label id="ticket-quantity-replace-' + i + '" style="text-align: center; color: #C0C0C0;"></label>';
          }

          html += '</td>';
          html += '</tr>';
      }
    }
  }

  $('#orderform-table tbody').html('');
  $('#orderform-table tbody').append(html);
  
  $('select.choose-level').bind('change', function () {
   calculateCustomTicketForm(data);
  });
}

/** 
 * Calculate totals for ticket form
 * 
 * @param {Object} formdata Data for the form
 */
function calculateTicketForm(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 ($('#ticket-level-' + i).val()) {
      ticketprice = data.events[i].prices[$('#ticket-level-' + i).val()];

      // If these tickets are not sold out, not available or need a call
      if (ticketprice != 'Sold Out' &&
          ticketprice != 'N/A' &&
          ticketprice != 'Call') {
          //$('#ticket-price-' + i).html('$' + ticketprice);
          $('#ticket-price-' + i).html('<input type="hidden" name="ticket-cost-' + i + '" value="' + ticketprice + '" /> $' + ticketprice);
          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-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 validateTicketForm(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 ($('#ticket-level-' + i).val()) {
      ticketprice = data.events[i].prices[$('#ticket-level-' + i).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;
  }
}

/** 
 * Validate custom ticket form
 * 
 * @param {Object} formdata Data for the form
 */
function validateCustomTicketForm(data) {
  var i;
  var valid = false;

  // Add up ticket totals
  for (i = 0; i < data.events.length; i = i + 1) {
    
    if ($('#ticket-level-' + i).val() && 
        $('#ticket-quantity-' + i).val()) {
        valid = true;
        break;
    }
  }

  return valid;
}


/** 
 * Calculate totals for ticket form
 * 
 * @param {Object} formdata Data for the form
 */
function calculateCustomTicketForm(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) {
    if ($('#ticket-level-' + i).val()) {
      ticketprice = data.events[i].prices[$('#ticket-level-' + i).val()];

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

/** 
 * Calculate totals for ticket form
 * 
 * @param {Object} formdata Data for the form
 */
function filterCustomTicketForm(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) {
    if ($('#ticket-level-' + i).val()) {
      ticketprice = data.events[i].prices[$('#ticket-level-' + i).val()];

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


$(document).ready(function () {
  setupLoginForm();

  $('[autofocus=""]').autofocus();
  
});

function showPopup(url) {
    newwindow=window.open(url,'name','height=500,width=650,top=200,left=300,resizable');
    if (window.focus) {newwindow.focus()}
} 

function login() {
    $.post("/login.asp", 
        { 
        username: $("#login-username").val(),
        password: $("#login-password").val() 
        },
        function(data){
            if (data != null) {
                if (data.status == "SUCCESS") {
                    $("#top-menu-login").hide();
                    $("#top-login").html("Welcome " + data.name);
                    $("#" + getLoginFormId()).submit();
                } else {
                    alert("An error was encountered logging you in, please contact customer support.");
                }
            }
        }, 
        "json"
    );
}

function logout() {
    $.post("/logout.asp", 
        function(data){
            if (data != null) {
                $("#" + getLogoutFormId()).submit();
            }
        }, 
        "json"
    );
    
    return false;
}



var _loginFormId = "login-form";
var _logoutFormId = "logout-form";

/**
 * Sets the id of the login form on the page
 */
function setLoginFormId(id) {
    _loginFormId = id;
}

/**
 * Get the id of the login form on the page
 */
function getLoginFormId() {
    return _loginFormId;
}

/**
 * Sets the id of the logout form on the page
 */
function setLogoutFormId(id) {
    _logoutFormId = id;
}

/**
 * Gets the id of the logout form on the page
 */
function getLogoutFormId() {
    return _logoutFormId;
}

/**
 * Popup a new window and display the gallery specified
 */
function showGallery(gallery) {
    window.open('/common/gallery.asp?album=' + gallery,'detailed','width=900,height=679'); 
    return false;
}
