/**
 *  Clear Forms
 *  A crude safety net in case the user hits refresh.
 *  Last modified: 2010-03-08 {pf}
 */
function clearForms() {
    
    $('input[type=text]').val('');
    $('input[type=radio], input[type=checkbox]').attr('checked', false);
    $('select').attr('selectedIndex', 0);
    
}

/**
 *  Global currency symbol, here in case of later refactoring
 */
var currencySymbol = '<span title="Great British Pounds (Sterling)">&pound;</span>';


/**
 *  Render Price
 *  Simple function that rounds a given number, prefixes it with the
 *  given curreny symbol and returns as a string for printing.
 *  Last modified: 2010-03-10 {pf}
 */
function renderPrice(figure) {
    
    var price;
    
    //  Round to 2 decimals
    var round = figure.toFixed(2);
    
    //  Remove any trailing double zeroes for cleanliness
    var priceSplit = round.split('.');
    var units = priceSplit[1];
    if (units == '00') {
        price = priceSplit[0];
    }
    else {
        price = round;
    }
    
    //  Automatically add commas and prefix with currency symbol
    price = currencySymbol + price.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    
    return price;
    
}


/**
 *  Update Prices
 *  Simple functions that identifies all relevant option values and
 *  displays the relevant plan prices.
 *  Last modified: 2010-03-08 {pf}
 */
function updatePrices() {
    
    var coverFunding;
    var coverOption;
    
    //  Gather funding and cover values
    coverFunding = $("input[name$='$funding']:checked").val();
    if ( $("input[name$='$coverEssExt']:checked").length >= 1 ) {
        coverOption = $("input[name$='$coverEssExt']:checked").val();
    }
    else {
        coverOption = $("input[name$='$cover']:not([value=essExt]):checked").val();
    }
    
    if ( coverFunding !== undefined && coverOption !== undefined) {        
        //  Create plan, rates and prices objects
        var plan;
        var rates;
        var prices;
        
        //  Search JSON data for matching plan
        $(plans).each( function(p) {
            
            //  If this is the correct plan, copy it into 'plan'
            if ( $(plans)[p].Name == coverFunding ) {
                plan = $(plans)[p];
            }
            
        });
        
        $(plan.Options).each( function(o) {
            
            //  If this is the correction cover option, copy it into 'cover'
            if ( $(plan.Options)[o].Name == coverOption ) {
                
                rates = $(plan.Options)[o].Rates;
                
                $(rates).each( function(r) {
					
                    if ( $(rates)[r].Lower <=  $('#employeesNumber input').val() && $(rates)[r].Upper >= $('#employeesNumber input').val() ) {
                        prices = $(rates)[r];
                    }
                    
                });
                
            }
            
        });
        
        // Get the optionID into a hidden field
        $('#selectedOption').val($(prices)[0].RateId);
        
        //  Employee prices
        $('#pricesEmployee .month').html( renderPrice($(prices)[0].Employee) );
        $('#pricesEmployee .year').html( renderPrice($(prices)[0].Employee * 12) );
        $('#pricesEmployee .all').html( renderPrice($(prices)[0].Employee * 12 * $('#employeesNumber input').val()) );
        
        //  Employee and partner prices
        $('#pricesEmployeePartner .month').html( renderPrice($(prices)[0].EmployeePartner) );
        $('#pricesEmployeePartner .year').html( renderPrice($(prices)[0].EmployeePartner * 12) );
        $('#pricesEmployeePartner .all').html( renderPrice($(prices)[0].EmployeePartner * 12 * $('#employeesNumber input').val()) );
        
        //  Single parent family prices
        $('#pricesSingleParent .month').html( renderPrice($(prices)[0].SingleParent) );
        $('#pricesSingleParent .year').html( renderPrice($(prices)[0].SingleParent * 12) );
        $('#pricesSingleParent .all').html( renderPrice($(prices)[0].SingleParent * 12 * $('#employeesNumber input').val()) );
        
        //  Single parent family prices
        $('#pricesFamily .month').html( renderPrice($(prices)[0].Family) );
        $('#pricesFamily .year').html( renderPrice($(prices)[0].Family * 12) );
        $('#pricesFamily .all').html( renderPrice($(prices)[0].Family * 12 * $('#employeesNumber input').val()) );
        
		$.ajax({
			type: "POST",
			contentType: "application/json; charset=utf-8",
			url: "/services/PlansPrices.asmx/LatestRefGet",
			data: "{}",
			dataType: "json",
			success: function(results) {
				LatestReferenceUpdate(results);
			},
			error: function(xhr, status, error) {
				AjaxQuoteError();
			}
		});
    }
}

/**
 *  'Plan and quote'
 *  Sets up and actuates the 'Plan and quote' form behaviours.
 *  Last modified: 2010-03-08 {pf}
 */
function planAndQuote() {
    //  By default, disable funding choices and hide cover options + prices
    $('#planFunding input[type=radio]').attr('disabled', true);
    $('#planFunding label').addClass('disabled');
    $('#coverOptionsOuter').parent().removeClass('hide');
    $('#coverOptionsOuter').hide();
    $('#essExtRates').parent().removeClass('hide');
    $('#essExtRates').hide();
    $('#pricing').parent().removeClass('hide');
    $('#pricing').hide();
    
    //  Limit employees input to numbers only
    $('#employeesNumber input').bind('keypress', function(e) {
        return ( e.which !=8 && e.which !=0 && (e.which < 48 || e.which > 57)) ? false : true ;
    });
    
    //  Immediately evaluate employee numbers upon entry
    $('#employeesNumber input').bind('keyup', function() {

        if ($('#employeesNumber input').val() >= 500) {
            //  Clear previous selection (in case of revising figures up after initial entry lower than 500)
            //  Disable min funding only and check
            $('#planFunding p.min label').addClass('disabled');
            $('#planFunding p.min input[type=radio]').attr('disabled', true);
            //  Enable other funding
            $('#planFunding p:not(.min) label').removeClass('disabled');
            $('#planFunding p:not(.min) input[type=radio]').attr('disabled', false);

            $('#over500').show();
        }
        else if ($('#employeesNumber input').val() >= 100) {
            $('#planFunding label').removeClass('disabled');
            $('#planFunding input[type=radio]').attr('disabled', false);

            $('#over500').hide();
        }
        else if ($('#employeesNumber input').val() >= 3 && $('#employeesNumber input').val() < 100) {

            $('#planFunding label').addClass('disabled');
            $('#planFunding input[type=radio]').attr('disabled', true);
            $('#planFunding input[type=radio]').attr('checked', false);
            $('input.coverOption').attr('checked', false);
            $('#essExtRates:visible').animate(
                    {
                        'height': 'toggle',
                        'opacity': 'toggle'
                    },
                    function() {
                        $('#coverOptionsOuter:visible').animate({
                            'height': 'toggle',
                            'opacity': 'toggle'
                        });
                    }
                );
            $('#pricing:visible').animate({
                'height': 'toggle',
                'opacity': 'toggle'
            });        
            
            
            //  Clear previous selection (in case of revising figures down after initial entry greater than 99)
            //  Enable min funding only and check
            $('#planFunding p.min label').removeClass('disabled');
            $('#planFunding p.min input[type=radio]').attr('disabled', false);
            //  Disable other funding
            $('#planFunding p:not(.min) label').addClass('disabled');
            $('#planFunding p:not(.min) input[type=radio]').attr('disabled', true);

            $('#over500').hide();
        }
        else {
            $('#planFunding label').addClass('disabled');
            $('#planFunding input[type=radio]').attr('disabled', true);
            $('#planFunding input[type=radio]').attr('checked', false);
            $('input.coverOption').attr('checked', false);
            $('#essExtRates:visible').animate(
                {
                    'height': 'toggle',
                    'opacity': 'toggle'
                },
                function() {
                    $('#coverOptionsOuter:visible').animate({
                        'height': 'toggle',
                        'opacity': 'toggle'
                    });
                }
            );
            $('#pricing:visible').animate({
                'height': 'toggle',
                'opacity': 'toggle'
            });

            $('#over500').hide();
        }

        updatePrices();

    });
    
    //  Calculate prices based on cover option clicked
    $('input.coverFunding').click( function() {
        
        $('#coverOptionsOuter:hidden').animate( {
            'height': 'toggle',
            'opacity': 'toggle'
        });
        
        updatePrices();
        
    });
    
    //  Show or hide extra cover options depending on cover plan clicked
    $('input.coverPlan').click( function() {
        
        if ( $(this).attr('value') == 'essExt' ) {
            $('#essExtRates:hidden').animate(
                {
                    'height': 'toggle',
                    'opacity': 'toggle'
                },
                function () {
                    $('#essExtRates input[type=radio]:first').attr('checked', true);
                    updatePrices();//recalculate to account for auto-checked first option [prev line]
                }
            );
        }
        else if ( $('#essExtRates:visible') ) {
            $('#essExtRates:visible').animate(
                {
                    'height': 'toggle',
                    'opacity': 'toggle'
                },
                function() {
                    $("input[name$='$coverEssExt']").attr('checked', false);
                }
            );
            $('#essExtRates input[type=radio]').attr('checked', false);
        }
        
        //  Reveal prices layout if hidden
        $('#pricing:hidden').animate( {
            'height': 'toggle',
            'opacity': 'toggle'
        });
        
        updatePrices();
        
    });
    
    //  Ensure prices get updated when a 'Essential/Extensive' option is clicked
    $("input[name$='$coverEssExt']").click( function() {
        updatePrices();
    });
    
}

function LatestReferenceUpdate(results) {
	if (results.d > 0) {
		$('span#quoteRef').text(results.d);
	} else {
		clearForms();
		swapDialogClass('stateQuoteFailure');
	    $('.dialog').dialog( 'open' );
	}
}

function AjaxQuoteError() {
	clearForms();
	swapDialogClass('stateQuoteFailure');
	$('.dialog').dialog( 'open' );
}

// Reset CSS classes to initial state
function resetDialogClass() {
	$('.ui-dialog').removeClass('stateSuccess');
	$('.ui-dialog').removeClass('stateFailure');
	$('.ui-dialog').removeClass('stateQuoteFailure');
}

// Set CSS classes to a new state
function swapDialogClass(newClass) {
	resetDialogClass();
	$('.ui-dialog').addClass(newClass);
	
}

// Callback function that makes a AJAX request to a web method
function submitEmailSummaryRequest() {
	// Create params to send to web method
	$params  = "{";
	$params += "    'rateID':'" + $('input#selectedOption').val() + "',";
	$params += "    'numEmployees':'" + $('#employeesNumber input').val() + "',";
	$params += "    'reference':'" + $('span#quoteRef').text() + "',";
	$params += "    'email':'" + $('#summaryEmailRequest input:text').val() + "',";
	$params += "    'dpa':" + $("[id$='_chkDPA']").attr('checked') + "";
	$params += "}";
	
	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: "/services/PlansPrices.asmx/SummaryEmailRequestSubmit",
		data: $params,
		dataType: "json",
		success: function(results) {
			EmailRequestSucceeded(results);
		},
		error: function(xhr, status, error) {
			AjaxSendError();
		}
	});
}

// Successful AJAX response handling
function EmailRequestSucceeded(results) {
	if (results.d != 'true' && results.d != true) {
		AjaxSendError();
		return;
	}
	
	swapDialogClass('stateSuccess');
	$('.dialog').dialog( 'open' );
}

// Generic AJAX Error Handler
function AjaxSendError() {
	swapDialogClass('stateFailure');
	$('.dialog').dialog( 'open' );
}

// Implements the jQuery UI dialog control
function emailOverlays() {
	//	Set dialog options and behaviour
	var dialogOptions = {
		'autoOpen': false,
		'draggable': false,
		'modal': true,
		'resizable': false,
		'width': 640
	};
	
	//	Setup form as dialog in overlay
	$('.dialog').dialog( dialogOptions );
	$('#summaryDialog').removeClass('hide');

	$('p#summaryEmailRequest input:submit').click(function() {
	    $("form").submit();
	    return false;
	});
	
}

function completeQuoteRequest() {
    resetDialogClass();
    submitEmailSummaryRequest();
    return false;
}

function hideFallbackControls() {
    $('.noscript').hide();
}

var plans;

$(document).ready( function() {
    clearForms();
    hideFallbackControls();
    emailOverlays();

    $("form").validate({
        errorPlacement: function(error, element) {
            element.before(error);
        },
        errorClass: "enquiryError",
        showErrors: function(errorMap, errorList) {
            $("#messageBox").html("Your form contains "
                                       + this.numberOfInvalids()
                                       + " error(s), see details below.");
            this.defaultShowErrors();
        },
        messages: {
            txtEmail: {
                required: "Email address",
                email: "Your email address must be in the format of name@domain.com"
            }
        },
        submitHandler: completeQuoteRequest
    });
	
	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: "/services/PlansPrices.asmx/PlanDetailsGet",
		data: "{}",
		dataType: "json",
		success: function(results) {
			plans = results.d;
			planAndQuote();
		},
		error: function(xhr, status, error) {
			AjaxQuoteError();
		}
	});
});
