// ********************************************* //
// Overlay and AJAX methods for voucher requests //
// ********************************************* //

// Implements the jQuery UI dialog control
function voucherDialogs() {
			
	//	Set dialog options and behaviour
	var dialogOptions = {
		'autoOpen': false,
		'draggable': false,
		'modal': false,
		'resizable': false,
		'width': 386
	};
	
	$('#voucherDialog').dialog( dialogOptions );
	
	//	Bind voucher dialog to "Email me voucher" buttons
	$('a.voucher').click( function() {
		
		resetDialogClass()
		
		//  Set the voucher ID, which is stored in the 'rel' of each voucher button
		$('#voucherID').val( $(this).attr('rel') );
		
		//  Reveal voucher dialog in order to evaluate dimensions for placement
		$('#voucherDialog').dialog( 'open' );
		
		//  Position voucher dialog relative to voucher button clicked
		var voucherDialogX = $(this).position().left - $(this).outerWidth();
		var voucherDialogY = $(this).position().top - ( $(document).scrollTop() + $('.ui-dialog').outerHeight() );
		$('#voucherDialog').dialog( 'option', 'position', [voucherDialogX, voucherDialogY] );
		
		//  Prevent default hyperlink action
		return false;
		
	});
	
}

// Reset CSS classes to initial state
function resetDialogClass() {
	$('.ui-dialog').removeClass('stateSuccess');
	$('.ui-dialog').removeClass('stateFailure');
}

// Set CSS classes to a new state
function swapDialogClass(newClass) {
	resetDialogClass();
	$('.ui-dialog').addClass(newClass);
	
}

// Callback function after validation that makes a AJAX request to a web method
function submitVoucherRequest() {
	// Create params to send to web method
	$params  = "{";
	$params += "    'voucherID':'" + $('#voucherDialog input#voucherID').attr('value') + "',";
	$params += "    'emailAddress':'" + $('#voucherDialog input#voucherEmail').val() + "',";
	$params += "    'firstname':'" + $('#voucherDialog input#voucherFirstname').val() + "',";
	$params += "    'surname':'" + $('#voucherDialog input#voucherSurname').val() + "',";
	$params += "    'newsletter':'" + $('#voucherDialog input#voucherNewsletter').val() + "'";			
	$params += "}";
	
	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: "/services/AjaxWebServices.asmx/VoucherRequestSubmit",
		data: $params,
		dataType: "json",
		success: function(results) {
			AjaxSucceeded(results);
		},
		error: function(xhr, status, error) {
			AjaxError();
		}
	});
}

// Successful AJAX response handling
function AjaxSucceeded(results) {
	if (results.d != 'true' && results.d != true) {
		AjaxError();
		return;
	}
	
	swapDialogClass('stateSuccess');
}

// Generic AJAX Error Handler
function AjaxError() {
	swapDialogClass('stateFailure');
}

$(document).ready( function() {
    voucherDialogs();
});
