﻿"use strict";

/**
 * @fileOverview Contains functions used by complete packages section of site
 * @author 
 */

/*global $,document */


/**
 * document ready function
 *
 */
$(document).ready(function () {
  setupPackagesForm(formdata);
  populateInputFields(formdata);
  setupOptionsForm(formdata);

  calculatePackagesForm(formdata);

  // Setup events to update the form
  $('#order-travel-insurance').bind('change', function () {
    calculatePackagesForm(formdata);
  });
  $('#shipping-country').bind('change', function () {
    calculatePackagesForm(formdata);
  });
  $('select.choose-hotel').bind('change', function () {
    calculatePackagesForm(formdata);
  });
  $('select.package-level').bind('change', function () {
    calculatePackagesForm(formdata);
  });
  $('input.package-people').bind('keyup', function () {
    calculatePackagesForm(formdata);
  });
  $('select.package-people').bind('change', function () {
    calculatePackagesForm(formdata);
  });

  $('.package-name').bind('change', function() {
      populateInputFields(formdata);
      calculatePackagesForm(formdata);
    
      $('select.choose-hotel').bind('change', function () {
        calculatePackagesForm(formdata);
      });
      $('select.package-level').bind('change', function () {
        calculatePackagesForm(formdata);
      });
      $('input.package-people').bind('keyup', function () {
        calculatePackagesForm(formdata);
      });
  });

  $('#checkout').bind('click', function() {
    return validatePackageForm(formdata);
  });
});


/**
 * Populate the packages order form
 *
 * @param {Object} data Data used by the form
 */
function setupPackagesForm(data) {
  var i, h, l, html = '';

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

  // Populate packages and options
  if (typeof data.packages === 'object') {
    for (i = 0; i < data.packages.length; i = i + 1) {
      html += '<tr>';
      html += '<td class="centered"><input type="radio" class="package-name" name="package-selector" id="package-selector-' + i + '" value="' + i + '" ';
      
      if (i == 0) {
        html += 'checked';
      }
      
      html += '/></td>';
      
      html += '<td class="centered" id="package-tour-code-' + i + '">';
      html += data.packages[i].tourCode;
      html += '<input type="hidden" name="package-tour-code-' + i + '" value="' + data.packages[i].tourCode + '" />'; 
      html += '</td>';

      html += '<td></td>';
      
      html += '<td class="centered">' + data.packages[i].nights + '</td>';
      html += '<td class="centered">' + data.packages[i].dates;
      html += '<input type="hidden" name="package-date-' + i + '" value="' + data.packages[i].dates + '" />';
      html += '</td>';
      html += '<td class="c5">' + data.packages[i].rounds;
      html += '<input type="hidden" name="package-round-' + i + '" value="' + data.packages[i].rounds + '" />';
      html += '</td>';
      html += '<td>' + data.packages[i].days + '</td>';
      
      html += '<td></td>';
      html += '<td class="centered"></td>';
      html += '<td></td>';
      html += '<td></td>';
      
      html += '</tr>';
    }

    $('#package-table tbody').append(html);
    $('#package-table').after('<input type="hidden" name="number-rows" value="' + data.packages.length + '" />');
  }

  setupPackageShippingForm(data);
}

/**
 * Populate the packages order form
 *
 * @param {Object} data Data used by the form
 */
function setupOptionsForm(data) {
  var i, h, l, html = '';

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

  // Populate packages and options
  if (typeof data.options === 'object') {
    for (i = 0; i < data.options.length; i = i + 1) {
      html += '<tr>';
      html += '<td class="c1" id="option-name-' + i + '">';
      html += data.options[i].name;
      html += '<input type="hidden" name="option-name-' + i + '" value="' + data.options[i].name + '" />'; 
      html += '<input type="hidden" name="option-id-' + i + '" value="' + data.options[i].id + '" />'; 
      html += '</td>';
      html += '<td class="c2" id="option-desc-' + i + '">$';
      html += data.options[i].description;
      html += '<input type="hidden" name="option-description-' + i + '" value="' + data.options[i].description + '" />'; 
      html += '<input type="hidden" name="option-price-' + i + '" id="option-price-' + i + '" value="' + data.options[i].price + '" />'; 
      html += '</td>';
      html += '<td class="c9 user"><input id="option-qty-' + i + '" name="option-qty-' + i + '" class="package-people" type="text" style="text-align: center;">';      
      html += '<td class="c10" id="option-subtotal-' + i + '"></td>';
      html += '</tr>';
    }

    $('#orderform-options-table tbody').append(html);
    $('#orderform-options-table').after('<input type="hidden" name="number-options" value="' + data.options.length + '" />');
  }

  setupPackageShippingForm(data);
}

/**
 * Populate values for the shipping options
 * 
 * @param {Object} data Data used by the form
 */
function setupPackageShippingForm(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 active row that is available for editing
 * 
 * @param {Object} data Data used by the form
 */
function populateInputFields(data) {
    
    hotel = '';
    level = '';
    costPerPerson = 0;

    i = $("input[name=package-selector]:checked").val();

    // Populate packages and options
    if (typeof data.packages === 'object') {
        for (j = 0; j < data.packages.length; j++) {
            for (h in data.packages[j].prices) {
                if (data.packages[j].prices.hasOwnProperty(h)) {
                    if (typeof frenchOpen != "undefined") {
                        if (h == 'Jardin de L\'Odeon') {
                            hotel = h;
                            break;
                        }
                    } else if (typeof wimbledon != "undefined") {
                        if (h == 'Millinneum (3 star)' || h == 'Millinneum  (3 star)') {
                            hotel = h;
                            break;
                        }
                    } else if (typeof usOpen != "undefined") {
                        if (h == 'W Hotel') {
                            hotel = h;
                            break;
                        }
                    } else {
                        hotel = h;
                        break;
                    }
                }
            }
            
            var exit = false;
            
            for (l in data.packages[j].prices) {
                for (t in data.packages[j].prices[l]) {
                    if (data.packages[j].prices[l].hasOwnProperty(t)) {
                        if (typeof usOpenShipping != "undefined") {
                            if (t == 'Promenade') {
                                level = t;
                                exit = true;
                                break;
                            }
                        } else if (typeof frenchOpen != "undefined") {
                            if (t == 'Upper Level') {
                                level = t;
                                exit = true;
                                break;
                            }
                        } else {
                            level = t;
                            exit = true;
                            break;
                        }
                    }
                }
                
                if (exit) {
                    break;
                }
            }
        
            costperperson = data.packages[j].prices[hotel][level];
        
            $('#package-table tbody tr:eq(' + (j) + ') td:eq(2)').html(hotel);
            $('#package-table tbody tr:eq(' + (j) + ') td:eq(7)').html(level);
            $('#package-table tbody tr:eq(' + (j) + ') td:eq(8)').html('$' + costperperson);
            $('#package-table tbody tr:eq(' + (j) + ') td:eq(9)').html('');
            $('#package-table tbody tr:eq(' + (j) + ') td:eq(10)').html('');
        }
    
        html = '<select class="choose-hotel" name="package-hotel" id="package-hotel">';

        if (typeof data.packages[i].prices === 'object') {
            for (h in data.packages[i].prices) {
                if (data.packages[i].prices.hasOwnProperty(h)) {
                    html += '<option value="' + h + '" ';
                    
                    if (typeof frenchOpen != "undefined") {
                        if (h == 'Jardin de L\'Odeon') {
                            html += 'selected';
                        }
                    } else if (typeof wimbledon != "undefined") {
                        if (h == 'Millinneum (3 star)' || h == 'Millinneum  (3 star)') {
                            html += 'selected';
                        }
                    } else if (typeof usOpen != "undefined") {
                        if (h == 'W Hotel') {
                            html += 'selected';
                        }
                    } else {
                        if (typeof $('#package-hotel').val() !== 'undefined') {
                            if ($('#package-hotel').val() == h) {
                                html += 'selected';
                            }
                        }
                    }
                    
                    html += '>' + h + '</option>';
                }
            }
        }

        html += '</select>';
    
        $('#package-table tbody tr:eq(' + (i) + ') td:eq(2)').html(html);
        
        var ticketsAvailable = false
        var levelCount = 0;
        html = '';

        if (typeof data.packages[i].prices === 'object') {
            html = '<select class="package-level" id="package-level" name="package-level">';

            var level

            for (l in data.packages[i].prices) {
                level = l
                break;
            }

            for (t in data.packages[i].prices[l]) {
                levelCount++;
                ticketprice = data.packages[i].prices[l][t];
                
                if (ticketprice != 0) { 
                    ticketsAvailable = true

                    if (data.packages[i].prices[l].hasOwnProperty(t)) {
                        html += '<option value="' + t + '" ';
                        
                        // If the tournament is the US Open and this is the promenade level
                        // set it to selected by default
                        if (typeof usOpenShipping != "undefined") {
                            if (t == 'Promenade') {
                            html += 'SELECTED';
                            }
                        } else if (typeof frenchOpen != "undefined") {
                            if (t == 'Upper Level') {
                                html += 'SELECTED';
                            }
                        } else {
                            if (typeof $('#package-level').val() !== 'undefined') {
                                if ($('#package-level').val() == t) {
                                    html += 'selected';
                                }
                            }
                        }                        

                        
                        html += '>' + t + '</option>';
                    }
                }
            }

            html += '</select>';
        }
        
        // If we don't have at least one level done display the drop down list
        if (levelCount < 2) {
            $('#package-table thead th:nth-child(8)').hide();
            $('#package-table tbody td:nth-child(8)').hide();
        }

        if (ticketsAvailable) {
            $('#package-table tbody tr:eq(' + (i) + ') td:eq(7)').html(html);
        }
        
        html = '<input id="package-people" name="package-people" class="package-people" type="text" style="text-align: center;">';
        
        $('#package-table tbody tr:eq(' + (i) + ') td:eq(8)').html('<label id="package-cost-per-person"></label');
        $('#package-table tbody tr:eq(' + (i) + ') td:eq(9)').html(html);
        $('#package-table tbody tr:eq(' + (i) + ') td:eq(10)').html('<label id="package-subtotal"></label>');
    }
}

/**
 * Calculate totals for packages form
 *
 * @param {Object} formdata DAta for the form
 */
function calculatePackagesForm(data) {
  var i, subtotal = 0, insurance = 0, shipping = 0, costperperson = 0, hotel, level, code, packagetotal, html, j = 0;

    i = $("input[name=package-selector]:checked").val();

    // Add up package totals
    if (typeof $('#package-people').val() !== 'undefined') {
      hotel = $('#package-hotel').val();
      level = $('#package-level').val();
      costperperson = data.packages[i].prices[hotel][level];
      $('#package-cost-per-person').html('<input type="hidden" name="package-cost" value="' + costperperson + '" /> $' + costperperson + '&nbsp;&nbsp;');

      packagetotal = costperperson * $('#package-people').val();
      subtotal += packagetotal;

      if (packagetotal === 0) {
        $('#package-subtotal').html('');
      }
      else {
        $('#package-subtotal').html('$' + packagetotal.toFixed(2));
      }
    }
    else {
      $('#package-cost-per-person').html('');
    }
    
  // Add up option totals
  for (i = 0; i < data.options.length; i = i + 1) {
    if (typeof $('#option-qty-' + i).val() !== 'undefined') {
        price = $('#option-price-' + i).val();
        qty = $('#option-qty-' + i).val();

      if (qty != '') {
          optiontotal = price * qty;
          subtotal += optiontotal;

          if (optiontotal === 0) {
            $('#option-subtotal-' + i).html('');
          }
          else {
            $('#option-subtotal-' + i).html('$' + optiontotal.toFixed(2));
          }
       } else {
            $('#option-subtotal-' + i).html('');
       }
    }
  }

  // Set the subtotal
  $('#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-travel-insurance').attr('checked')) {
    insurance = subtotal * $('#insurance-rate').val();
  }
  
  $('#travel-insurance-value').html('$' + 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 package form
 * 
 * @param {Object} formdata Data for the form
 */
function validatePackageForm(data) {
    var ticketprice, roundtotal, packagetotal = 0, i;

    i = $("input[name=package-selector]:checked").val();

    if (typeof $('#package-people').val() !== 'undefined') {
      hotel = $('#package-hotel').val();
      level = $('#package-level').val();
      costperperson = data.packages[i].prices[hotel][level];
      packagetotal = costperperson * $('#package-people').val();
    }

    if (!packagetotal) {
        alert ('Please select a package to purchase before continuing.');
        return false;
    } else {
        return true;
    }
}
