$(document).ready(function()
{

  function enableItem(item, has_focus)
  {
    $(item).removeAttr('disabled').removeClass('disabled');
    if (has_focus)
      $(item).focus();
  }


  function disableItem(item, clear_value)
  {
    $(item).attr('disabled', 'disabled').addClass('disabled');
    if (clear_value)
      $(item).val('');
  }


  function updateFieldCheckbox(checkbox, changed_item)
  {
    if (checkbox.attr('checked'))
      enableItem(changed_item, true);
    else
      disableItem(changed_item, true);
  }


  function updateFieldRadio(radio, changed_item, true_value)
  {
    if (radio.val() == true_value)
      enableItem(changed_item, false);
    else
      disableItem(changed_item, false);
  }


  function updateNetWorth()
  {
    var applicant_assets = $('input.applicant_asset').sum();
    var applicant_liabilities = $('input.applicant_liability').sum();
    var co_applicant_assets = $('input.co_applicant_asset').sum();
    var co_applicant_liabilities = $('input.co_applicant_liability').sum();

    if (applicant_assets < applicant_liabilities)
      $('span#franchise_applicant_total_net_worth').addClass('red');
    else
      $('span#franchise_applicant_total_net_worth').removeClass('red');

    if (co_applicant_assets < co_applicant_liabilities)
      $('span#franchise_co_applicant_total_net_worth').addClass('red');
    else
      $('span#franchise_co_applicant_total_net_worth').removeClass('red');

    var applicant_net_worth = Math.abs(applicant_assets - applicant_liabilities);
    var co_applicant_net_worth = Math.abs(co_applicant_assets - co_applicant_liabilities);

    $('span#franchise_applicant_total_net_worth').html('$' + applicant_net_worth);
    $('span#franchise_co_applicant_total_net_worth').html('$' + co_applicant_net_worth);
  }


  //|
  //| FORM 2 - TEXT AREA
  //|
  //|  This set of functionality deals with the textarea on Form 2.
  //|  Basically, it's disabled unless you hit the "other" radio
  //|  button (at which time, it becomes enabled and usable).
  //|  Initially, we check to see if that textarea is empty; if so
  //| the user hasn't entered anything there and we disable it.
  //|
  //------------------------
  updateFieldRadio($('input[name=franchise[co_relationship_to_applicant]]:checked'),
                     'textarea#franchise_co_other_text',
                     'other');

  $('input:[name=franchise[co_relationship_to_applicant]]').click(function()
  {
      updateFieldRadio($(this), 'textarea#franchise_co_other_text', 'other');
  });
  //------------------------


  //|
  //| FORM 5 - ACCOMPANYING TEXT FIELDS
  //|
  //|  This set of functionality deals with the text fields
  //| that accompany certain checkboxes on Form 5. If we
  //| check one of these boxes, we should shift the focus
  //| to the text field; if we uncheck a box, the value
  //| in the text field should be cleared.
  //|
  //------------------------
  $('input.franchise_hear_about_multi[type=checkbox]').each(function()
  {
    updateFieldCheckbox($(this), '#' + $(this).attr('id') + '_name');
  });

  $('input.franchise_hear_about_multi').click(function()
  {
    updateFieldCheckbox($(this), '#' + $(this).attr('id') + '_name');
  });
  //------------------------

  //|
  //| FORM 6 - RADIO BUTTONS, TEXT FIELDS, AND TEXT AREA
  //|
  //|  This set of functionality does similar things as the
  //| previous forms, but for Form 6.
  //|
  //------------------------
  // U.S. Citizen/Work Authorization check
  updateFieldRadio($('input[name=franchise[us_citizen]]:checked'),
                     'input[name=franchise[authorized_to_work]]',
                     'no');

  $('input[name=franchise[us_citizen]]').click(function()
  {
    updateFieldRadio($(this), 'input[name=franchise[authorized_to_work]]', 'no');
  });

  // Hired Trainer/Manager Check
  updateFieldRadio($('input[name=franchise[operator]]:checked'),
                       'input[name=franchise[manager_name]]',
                       'manager');

  $('input[name=franchise[operator]]').click(function()
  {
    updateFieldRadio($('input[name=franchise[operator]]:checked'),
                       'input[name=franchise[manager_name]]',
                       'manager');
  });

  // Current Franchise Check
  updateFieldRadio($('input[name=franchise[current_own_franchise]]:checked'),
                       'textarea#franchise_franchise_name_list',
                       'yes');

  $('input:[name=franchise[current_own_franchise]]').click(function()
  {
    updateFieldRadio($('input[name=franchise[current_own_franchise]]:checked'),
                         'textarea#franchise_franchise_name_list',
                         'yes');
  });
  //------------------------

  //|
  //| FORM 7 - ADDING OF FINANCIAL DATA
  //|
  //|  This set of functionality continuously updates
  //| assets, liabilities, and total equity.
  //|
  //------------------------
  // Applicant Assets
  $('input.applicant_asset').sum({
    bind: 'change',
    selector: 'td#franchise_applicant_total_assets',
    oncalc: function(value, settings) {
      $(settings.selector).html("$" + value.toFixed(2));
      updateNetWorth();
    }
  });

  // Co-Applicant Assets
  $('input.co_applicant_asset').sum({
    bind: 'change',
    selector: 'td#franchise_co_applicant_total_assets',
    oncalc: function(value, settings) {
      $(settings.selector).html("$" + value.toFixed(2));
      updateNetWorth();
    }
  });

  // Applicant Liabilities
  $('input.applicant_liability').sum({
    bind: 'change',
    selector: 'span#franchise_applicant_total_liabilities',
    oncalc: function(value, settings) {
      $(settings.selector).html("$" + value.toFixed(2));
      updateNetWorth();
    }
  });

  // Co-Applicant Liabilities
  $('input.co_applicant_liability').sum({
    bind: 'change',
    selector: 'span#franchise_co_applicant_total_liabilities',
    oncalc: function(value, settings) {
      $(settings.selector).html("$" + value.toFixed(2));
      updateNetWorth();
    }
  });
  //------------------------

  //|
  //| FORM 8 - "IF YES" QUESTIONS
  //|
  //|  Similar to before.
  //|
  //------------------------
  // Using Partner Check
  updateFieldRadio($('input[name=franchise[use_partner]]:checked'),
                       'input#franchise_use_partner_name',
                       'yes');

  $('input[name=franchise[use_partner]]').click(function()
  {
    updateFieldRadio($('input[name=franchise[use_partner]]:checked'),
                         'input#franchise_use_partner_name',
                         'yes');
  });

  // Home Loan Check
  updateFieldRadio($('input[name=franchise[borrow_against_home]]:checked'),
                       'input#franchise_home_loan_amount',
                       'yes');

  $('input[name=franchise[borrow_against_home]]').click(function()
  {
    updateFieldRadio($('input[name=franchise[borrow_against_home]]:checked'),
                         'input#franchise_home_loan_amount',
                         'yes');
  });

  // Other Loan Check
  updateFieldRadio($('input[name=franchise[other_loan]]:checked'),
                       'input#franchise_other_loan_amount',
                       'yes');

  $('input[name=franchise[other_loan]]').click(function()
  {
    updateFieldRadio($('input[name=franchise[other_loan]]:checked'),
                         'input#franchise_other_loan_amount',
                         'yes');
  });
  //------------------------

  //|
  //| FORM 9 - ADDITIONAL INCOME
  //|
  //|  Similar to Form 7.
  //|
  //------------------------
  $('input.income_item').sum({
    bind: 'change',
    selector: 'td#total_continuing_income',
    oncalc: function(value, settings) {
      $(settings.selector).html("$" + value);
      updateNetWorth();
    }
  });





  //------------------------
  //|
  //| BMI Widget
  //|
  var form = $('form#bmi_form')

  $('form#bmi_calculator').submit(function(event)
  {
    if ($('input#bmi_ft').val() && $('input#bmi_lbs').val())
    {
      var height = (parseInt($('input#bmi_ft').val()) * 12) + parseInt($('input#bmi_in').val() ? $('input#bmi_in').val() : 0);
      var weight = parseInt($('input#bmi_lbs').val());
      var bmi = ((weight / ( height * height )) * 703).toFixed(1);
      var weight_classification;
      if (bmi < 18.5) { weight_classification = 'underweight' };
      if (bmi >= 18.5 && bmi < 25) { weight_classification = 'normal' };
      if (bmi >= 25 && bmi < 30) { weight_classification = 'overweight' };
      if (bmi >= 30) { weight_classification = 'obese' };
      $('p#bmi_container').removeClass('red').html('Your BMI is <b class="red">' + bmi + '</b>.<br /> Your weight classification is <b class="red">' + weight_classification + '</b>.');
    }
    else
    {
      $('p#bmi_container').addClass('red').html('Height and Weight are required.');
    }
    event.preventDefault();
    return false;
  });

  //------------------------

  //------------------------
  //|
  //| Franchise Callout Form
  //|
  $('#franchise_callout_form').submit(function()
  {
    var phoneRegex = /^([0-9]){10}$/;
    var emailRegex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;

    var name = $('#franchise_callout_name').val();
    var email = $('#franchise_callout_email').val();
    var phone = $('#franchise_callout_phone').val();
    var state = $('#franchise_callout_state').val();

    var errors = "";
    if (name == "")
      errors += 'Please enter your name<br />';

    if (email == "")
      errors += 'Please enter your email<br />';
    else if (email.match(emailRegex) == null)
      errors += 'Please enter a valid email<br />';

    if (phone == "")
      errors += 'Please enter your phone<br />';
    else if (phone.replace(/[^0-9]/g, '').match(phoneRegex) == null)
      errors += 'Please enter a valid phone<br />';

    if (errors != "")
    {
      $("#franchise_callout_errors").html('<span class="brightRed">' + errors + '</span>');
    }
    else
    {
      jQuery.get('/franchise/warm-lead-form/', { 'name': name, 'email': email, 'phone': phone, 'state': state }, function (response)
        {
          if ( response == "true")
          {
            // google
            $('#content').append('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1066722635/?label=hNh5CNOKsgEQy8rT_AM&amp;guid=ON&amp;script=0"/>');

            pageTracker._trackPageview("/funnel_G2/request-info/");

            // yahoo
            if (window.ysm_customData)
            {
              window.ysm_customData = new Object();
              window.ysm_customData.conversion = "transId=,currency=,amount=";
              window.ysm_accountid  = "1KOAEQ1GGDULIQGRCGSRLOQSUKK";

              fbmvc.loadScript("http://srv2.wa.marketingsolutions.yahoo.com/script/ScriptServlet?aid=" + ysm_accountid, function() { return null; } );
            }

            // bing
            $('#content').append('<IMG width=1 height=1 SRC="http://650069.r.msn.com/?type=1&cp=1"/>');

            $("#franchise_callout_errors").html('');
            $('#form_content').html('<p class="big green">Thank you for contacting us! Someone will be in touch with you soon.</p>');
          }
        });


    }

    return false;
  });
});

