/* @copyright  Copyright (c) 2007 August Ash Inc. (http://www.augustash.com)
 * @version    $Id: aailib.js 72 2009-03-17 13:31:01Z pmcwilliams $
 */

/* Prepare Links - using jQuery
 * Checks the document, when ready, for all link nodes with a class name "external" and opens them in a new window when clicked.
 */
$(document).ready(function(){
    $("a").filter(".external").click(function (){
        var NewWindow = new OpenWindow($(this).attr("href"));
        return NewWindow.open();
    })
    .end();
});

/* OpenWindow Class
 * Creates an OpenWindow object that allows you to define the URL, window name, and features for firing a pop-up window. @param {String} href
 */
function OpenWindow(href)
{
    // Set default values
    var _href     = href;
    var _name     = "external";
    var _features = "";
    
    function __construct() {
        // Define methods       
        this.getHref     = function() { return _href; }
        this.setHref     = function(href) { _href = href; }
        this.getName     = function() { return _name; }
        this.setName     = function(name) { _href = name; }
        this.getFeatures = function() { return _features; }
        this.setFeatures = function(features) { _features = features; }
        
        this.open = function() {
            window.open(_href, _name, _features);
            return false;
        }
    };
    
    return new __construct();
}

/* Son of Suckerfish Drop Down Menu - http://www.htmldog.com/ */
$(document).ready(function(){
    var sfEls = $("ul#nav li");
    for (var i = 0; i < sfEls.length; i++) {
        $(sfEls[i]).mouseover(function(){
            $(this).addClass("sfhover");
        });
        $(sfEls[i]).mouseout(function(){
            $(this).removeClass("sfhover");
        });
    }
});

/* random calculator form goodness
--------------------------------------------------------------- */
$(document).ready(function(){
    // Set inital var
    var iteration = 1;
    var wodYear = 0;
    
    
    // Add a class to the calculator's submit button formRow
    $('div.formRow input#submit').parent().addClass('submitRow');
    
    // append disclaimer text to the empty white space in the form
    var disclaimer_text = "<p id='wo-disclaimer'>The Work Optional Date Calculator is for informational purposes only. By clicking the submit button you acknowledge and understand that the information resulting from the use of this calculator, is not, and should not be construed, in any manner whatsoever, as the receipt of, or a substitute for, personalized individual advice from Work Optional, Inc., or from any other investment professional.</p>";
    $("form#calculator fieldset#fieldset-group").append(disclaimer_text);
    
    
    // Hide results box
    $('.calculator-results').hide();
    $('.calculator-calculating').hide();
    
    // hide dependent fields
    $('.dependent').parent().hide();
    
    /* Toggle the ability to disable Spouse form
    ------------------------------------------------------------------------------------------- */
    var spouse_form = $('div.spouse');
    $(spouse_form).prepend('<div class="disabled-area"> </div>');
    var disabled_area = $("div.disabled-area");
    $(disabled_area).prepend('<a class="toggle-disabled-area">Click to Add Spouse Information</a>');
    var spouse_form_elements = $("div.spouse input");
    $(spouse_form_elements).each(function(){
      $(this).attr("disabled", "disabled");
      $(this).parent().find("span.description").hide();
    });
    
    
    $("a.toggle-disabled-area").click(function(){
      $(spouse_form_elements).each(function(){
        // add required class to spouse's name, dob, and gross income
        if ($(this).attr("name") == "spouse_name" || $(this).attr("name") == "spouse_dob" || $(this).attr("name") == "spouse_gross_income") {
          $(this).addClass('required');
        }
        $(this).removeAttr('disabled');
        $(this).parent().find("span.description").show();
      })
      $(disabled_area).hide();
    })
    
    /* Toggling of Client Fields
    ------------------------------------------------------------------------------------------- */
    // toggle display of home owner fields
    $('#client_ownHome_check-Yes').click(function(){
      $("input[id^='client_mortgage']").parent().slideDown();
    });
    // toggle display of home owner fields 
    $('#client_ownHome_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='client_mortgage']").val('');
      $("input[id^='client_mortgage']").parent().slideUp();
    });
    
    // toggle display of business owner fields
    $('#client_ownBusiness_check-Yes').click(function(){
      $("input[id^='client_business']").parent().slideDown();
    });
    // toggle display of business owner fields 
    $('#client_ownBusiness_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='client_business']").val('');
      $("input[id^='client_business']").parent().slideUp();
    });

    // toggle display of rental owner fields 
    $('#client_ownRental_check-Yes').click(function(){
      $("input[id^='client_net_rental']").parent().slideDown();
      $("input[id^='client_rental_mortgage']").parent().slideDown();
    });
    // toggle display of rental owner fields 
    $('#client_ownRental_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='client_net_rental']").val('');
      $("input[id^='client_rental_mortgage']").val('');
      $("input[id^='client_rental_mortgage']").parent().slideUp();
      $("input[id^='client_net_rental']").parent().slideUp();
    });

    // toggle display of lump sum fields
    $('#client_lumpSum_check-Yes').click(function(){
      $("input[id^='client_lump_sum']").parent().slideDown();
    });
    // toggle display of lump sum fields
    $('#client_lumpSum_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='client_lump_sum']").val('');
      $("input[id^='client_lump_sum']").parent().slideUp();
    });

    // toggle display of social security fields 
    $('#client_ss_check-Yes').click(function(){
      $("input[id^='client_current_ss']").parent().slideDown();
      $("input[id^='client_ss_income']").parent().slideUp();
      $("input[id^='client_ss_income']").val('');
    });
    // toggle display of social security fields 
    $('#client_ss_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='client_current_ss']").val('');
      $("input[id^='client_ss_income']").parent().slideDown();
      $("input[id^='client_current_ss']").parent().slideUp();
    });
    
    // toggle display of pension fields 
    $('#client_pension_check-Yes').click(function(){
      $("input[id^='client_current_pension']").parent().slideDown();
      $("input[id^='client_pension_income']").parent().slideUp();
      $("input[id^='client_pension_income']").val('');
    });
    // toggle display of pension fields 
    $('#client_pension_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='client_current_pension']").val('');
      $("input[id^='client_current_pension']").parent().slideUp();
      $("input[id^='client_pension_income']").parent().slideDown();
    });
    
    /* Toggling of Spouse Fields
    ------------------------------------------------------------------------------------------- */
    // toggle display of home owner fields
    $('#spouse_ownHome_check-Yes').click(function(){
      $("input[id^='spouse_mortgage']").parent().slideDown();
    });
    // toggle display of home owner fields 
    $('#spouse_ownHome_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='spouse_mortgage']").val('');
      $("input[id^='spouse_mortgage']").parent().slideUp();
    });
    
    // toggle display of business owner fields
    $('#spouse_ownBusiness_check-Yes').click(function(){
      $("input[id^='spouse_business']").parent().slideDown();
    });
    // toggle display of business owner fields 
    $('#spouse_ownBusiness_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='spouse_business']").val('');
      $("input[id^='spouse_business']").parent().slideUp();
    });

    // toggle display of rental owner fields 
    $('#spouse_ownRental_check-Yes').click(function(){
      $("input[id^='spouse_net_rental']").parent().slideDown();
      $("input[id^='spouse_rental_mortgage']").parent().slideDown();
    });
    // toggle display of rental owner fields 
    $('#spouse_ownRental_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='spouse_net_rental']").val('');
      $("input[id^='spouse_rental_mortgage']").val('');
      $("input[id^='spouse_rental_mortgage']").parent().slideUp();
      $("input[id^='spouse_net_rental']").parent().slideUp();
    });

    // toggle display of lump sum fields
    $('#spouse_lumpSum_check-Yes').click(function(){
      $("input[id^='spouse_lump_sum']").parent().slideDown();
    });
    // toggle display of lump sum fields
    $('#spouse_lumpSum_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='spouse_lump_sum']").val('');
      $("input[id^='spouse_lump_sum']").parent().slideUp();
    });

    // toggle display of social security fields 
    $('#spouse_ss_check-Yes').click(function(){
      $("input[id^='spouse_current_ss']").parent().slideDown();
      $("input[id^='spouse_ss_income']").parent().slideUp();
      $("input[id^='spouse_ss_income']").val('');
    });
    // toggle display of social security fields 
    $('#spouse_ss_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='spouse_current_ss']").val('');
      $("input[id^='spouse_ss_income']").parent().slideDown();
      $("input[id^='spouse_current_ss']").parent().slideUp();
    });
    
    // toggle display of pension fields 
    $('#spouse_pension_check-Yes').click(function(){
      $("input[id^='spouse_current_pension']").parent().slideDown();
      $("input[id^='spouse_pension_income']").parent().slideUp();
      $("input[id^='spouse_pension_income']").val('');
    });
    // toggle display of pension fields 
    $('#spouse_pension_check-No').click(function(){
      // reset the value of the fields to blank to make sure we're not submitting errant data
      $("input[id^='spouse_current_pension']").val('');
      $("input[id^='spouse_current_pension']").parent().slideUp();
      $("input[id^='spouse_pension_income']").parent().slideDown();
    });
    
    // Reformat Tips
    $('span.description').each(function(){
        var comment = $(this).html();
        $(this).html('<a class="hint-toggle">Hint</a><span class="hint"><a class="hint-close">Close Hint</a><span class="hint-top"></span><span class="hint-content-wrap"><span class="hint-content">' + comment + '</span></span><span class="hint-bottom"></span></span>');
    });
    
    // Add element controls and the array brackets
    $('.businessIncome, .netRentalIncome, .lumpSumIncome, .debt').append("<a class='add-element'>+</a>");

    // Add Array Syntax to Starting Elements
    var inputs = ['.businessIncome', '.netRentalIncome', '.lumpSumIncome', '.debt'];
    $.each(inputs, function() {
        $(this + ' label').attr('for', $(this + ' label').attr('for') + '[0]');
        $(this + ' input').each(function() {
            $(this).attr('id', $(this).attr('id') + '[0]');
            $(this).attr('name', $(this).attr('name') + '[0]');
        });
    });
    

    // Listen for clicks
    $('.add-element').live('click', function(){
        // Clone parent and print after the parent
        $(this).parent().clone().hide().insertAfter($(this).parent()).slideDown();
        // Store the new element
        var newElement = $(this).parent().next();
        // Add remove button
        newElement.append("<a class='remove-element'>x</a>");
        // Remove add button
        newElement.children('a.add-element').remove();
        // Update attributes
        // Clear Value
        newElement.children('input').val('');
        // Change iteration number
        // newElement.children('label').prepend('Another ');
        newElement.children('label').attr('for', newElement.children('label').attr('for').replace('[0]', '[' + iteration + ']'));
        newElement.children('input').each(function(){
            $(this).attr('id', $(this).attr('id').replace('[0]', '[' + iteration + ']'));
            $(this).attr('name', $(this).attr('name').replace('[0]', '[' + iteration + ']'));
        });
        newElement.children('span.description').hide();
        // Update overall iteration
        iteration++;
    });
    
    $('.remove-element').live('click', function(){
        // Pull classes of parent and massage into jQuery string
        var classes = $(this).parent().attr('class');
        classes = '.' + classes.replace(' ', '.');
        // Check if there are any more form elements of the same type before allowing a removal
        if ($(this).parent().siblings(classes).length > 0) {
            $(this).parent().slideUp('normal', function(){
                // remove once the animation is done
                $(this).remove();
            });
        }
    });
    
    $('.back-to-form').live('click', function(){
        $('.calculator-results').hide();
        $('.calculator-form').show();
        return false;
    });
    
    /*
     * I used a "Publishing to Facebook" generator on the facebook
     * connect playground in the Facebook Developers area which gave
     * all the code, then I just tweaked to fit.
     */
    $('.facebook-share').live('click', function() {
      var prod_base_url = 'http://www.workoptionaldate.com';
      if (wodYear > 0) {
        FB.ensureInit(function () {
          FB.Connect.streamPublish(
            'When is your Work Optional date?',
            {
              'media': [{
                'type':'image',
                'src': prod_base_url + '/img/facebook-graphic.jpg',
                'href': prod_base_url
              }],
              'name':'I will be Work Optional in ' + wodYear + ', when will you?',
              'href': prod_base_url + '/work-optional.php',
              'description':'Use this work optional calculator to figure out when you will be able to support your lifestyle and not have to work anymore!'
            },
            [{
              'text':'Use the Calculator',
              'href': prod_base_url + '/work-optional.php'
            }],
            null,
            'Share your thoughts:'
          );
        });
      } else {
        alert('Your date has not been calculated yet.')
      }
      return false;
    });
    
    $('.share-twitter').live('click', function(){
        if (wodYear > 0) {
            window.open($(this).attr('href'));
        } else {
            alert('Your date has not been calculated yet.')
        }
        return false;
    });
    
    
    // Validate the form
    $("form#calculator").validate({
      rules: {
        // client related rules
        "client_name": { minlength:2 },
        "client_dob": { required:true, date:true },
        "client_gross_income": { required:true, number:true },
        "client_current_ss_income": { number:true, required: "#client_ss_check-Yes:checked" },
        "client_current_pension_income": { number:true, required: "#client_pension_check-Yes:checked" },
        "client_ss_income": { number:true },
        "client_pension_income": { number:true },
        // spouse related rules
        "spouse_name": { minlength:2 },
        "spouse_dob": { date:true },
        "spouse_gross_income": { number:true },
        "spouse_current_ss_income": { number:true, required: "#spouse_ss_check-Yes:checked" },
        "spouse_current_pension_income": { number:true, required: "#spouse_pension_check-Yes:checked" },
        "spouse_ss_income": { number:true },
        "spouse_pension_income": { number:true },
        // savings & investments rules
        "invested_assets": { number:true },
        "personal_annual_savings": { number:true },
        "employer_annual_savings": { number:true }
      },
      messages: {
        // client related messages
        "client_name": { required: "Please enter your first name", minlength: $.format("At least {0} characters are required!") },
        "client_dob": { date: "Enter the DOB in MM/DD/YYYY format" },
        "client_gross_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "client_current_ss_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "client_current_pension_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "client_ss_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "client_pension_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        // spouse related messages
        "spouse_name": { minlength: $.format("At least {0} characters are required!") },
        "spouse_dob": { date: "Enter the DOB in MM/DD/YYYY format" },
        "spouse_gross_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "spouse_current_ss_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "spouse_current_pension_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "spouse_ss_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "spouse_pension_income": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        // savings & investments messages
        "invested_assets": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "personal_annual_savings": { number: "Please enter only numbers as either whole numbers or in decimal format" },
        "employer_annual_savings": { number: "Please enter only numbers as either whole numbers or in decimal format" }
      }
    });
    
    $.validator.addClassRules("year4", {
        minlength:4,
        maxlength:4
    });
    
    
    // AJAX
    // Stop the form and do our magic.
    $('form#calculator').submit(function (){
      if ($('form#calculator').valid() == true) {
        // Store Form
        $('.calculator-form').hide();
        $('.calculator-calculating').show();
        
        // var data =  $('form#calculator').serialize();
        // console.log(data);

        // Send Request
        $.post('/app/index', $('form#calculator').serialize(), function(r) {
            var result = "<div class='results'>";
            if (r.success == 'true') {
                // Store date for sharing
                wodYear = r.data.wod;
                // Build Results HTML
                result += "<div class='wod-date'>Your work optional date is <strong>" + r.data.wod + "</strong></div>";
                result += "<div class='client-age'>" + r.data.clientName + " will be <strong>" + r.data.clientAge + "</strong></div>";
                if (r.data.spouseAge != '') {
                    result += "<div class='spouse-age'>" + r.data.spouseName + " will be <strong>" + r.data.spouseAge + "</strong></div>";
                }
                result += "<div class='years-till'><strong>" + r.data.years + "</strong> years until your work optional date</div>";
            } else {
                result += "<div class='wod-error'>" + r.error + "</div>";
            }
            result += "</div>";
            // Set Twitter Link
            $('a.share-twitter').attr('href', '/twitter/?wod=' + r.data.wod);
            // Display changes
            $('.results-wrapper').html(result);
            $('.calculator-calculating').hide();
            $('.calculator-results').show();
        }, "json");
        return false;
      }
    });
});


/* toggle display of form hints
--------------------------------------------------------------- */
$(document).ready(function() {
  $('span.description:visibile').each(function () {
    // options
    var distance = 0;
    var time = 250;
    var hideDelay = 500;

    var hideDelayTimer = null;

    // tracker
    var beingShown = false;
    var shown = false;
    
    var trigger = $('.hint-toggle', this);
    var popup = $('.hint', this).css('opacity', 0);

    // set the mouseover and mouseout on both element
    $([trigger.get(0), popup.get(0)]).click(function () {
      // stops the hide event if we move from the trigger to the popup element
      if (hideDelayTimer) clearTimeout(hideDelayTimer);

      // don't trigger the animation again if we're being shown, or already visible
      if (beingShown || shown) {
        // hide the popup if the close button is clicked
        $('a.hint-close').click(function(){
          popup.hide();
        });
        return;
      } else {
        beingShown = true;

        // reset position of popup box
        popup.css({
          top: 0,
          left: 0,
          display: 'block' // brings the popup back in to view
        })

        // (we're using chaining on the popup) now animate it's opacity and position
        .animate({
          top: '-=' + distance + 'px',
          opacity: 1.0
        }, time, 'swing', function() {
          // once the animation is complete, set the tracker variables
          beingShown = false;
          shown = true;
        });
      } // end of if/else statement
      
    }).mouseout(function () {
      // reset the timer if we get fired again - avoids double animations
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      
      // store the timer so that it can be cleared in the mouseover if required
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        popup.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          // once the animate is complete, set the tracker variables
          shown = false;
          // hide the popup entirely after the effect (opacity alone doesn't do the job)
          popup.css('display', 'none');
        });
      }, hideDelay);
    });
  });
});

/* Masked Input fields
--------------------------------------------------------------- */
$(document).ready(function() {
  // set masks
  $.mask.definitions['~']='[+-]';
  $(".date").mask("99/99/9999");
});


/* jQuery Cookie Plugin
--------------------------------------------------------------- */
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
