function showInputSection(parentContainer) {
	jQuery(".callmeback-fields", parentContainer).show();
}

function hideInputSection(parentContainer) {
	jQuery(".callmeback-fields", parentContainer).hide();
}

function afterSendSuccess(parentContainer) {
	jQuery(".callmeback-aftersend", parentContainer).each(function(){
		jQuery(this).show();
		hideInputSection(parentContainer);
	});
}

function processSendApplicationResult(data, parentContainer) {
	var result = jQuery("result", data).text();
	
	if (result == "success") {
		// alert("Uw aanmelding is ontvangen");		
		afterSendSuccess(parentContainer);
	} else if (result == "error") {
		var errors = "";
		jQuery("errorMessage", data).each(function() {
			errors = errors + "\n * " + jQuery(this).text();
		});
		alert("Uw aanmelding kon niet worden verstuurd. De server meldt:" + errors);
	} else {
		alert("Onbekende fout opgetreden");
	}
}

/**
 * Called when the 'send' button is clicked : perform ajax-call to the action that
 * does the actual sending. 
 */
function sendApplication() {
	var parentContainer = jQuery(this).parents(".callmeback-container");
	var name = jQuery("input[name=name]", parentContainer).val();
	var email= jQuery("input[name=email]", parentContainer).val();
	var phone = jQuery("input[name=phone]", parentContainer).val();
	var sendTo = jQuery("input[name=sendTo]", parentContainer).val();
	var subject = jQuery("input[name=subject]", parentContainer).val();
	
	var params = {
		callerName : name,
		callerEmail : email,
		callerPhone : phone,
		sendTo : sendTo,
		subject : subject
	};
	
	var url = contextPath + "/callmeback/sendCallMeBackMail.action";
	jQuery.post(url, params, function(data) {
		processSendApplicationResult(data, parentContainer);
    });	
}

AJS.toInit(function(){
	jQuery(".callmeback-expandable").mouseover(function() {
		showInputSection(this);	
	});
	jQuery(".callmeback-expandable").mouseout(function() {
		hideInputSection(this);
	});
	jQuery(".call-me-back-input").focus(function() {
		jQuery(this).parents(".callmeback-expandable").unbind("mouseout");
		if (jQuery(this).val() == "[" + jQuery(this).attr("id") + "]") {
			jQuery(this).val("");
		}
	});	
	jQuery(".call-me-back-input").blur(function() {
		jQuery(this).parents(".callmeback-expandable").bind("mouseout", function (){
			hideInputSection(this);
		});
		if (jQuery.trim(jQuery(this).val()) == "") {			
			jQuery(this).val("[" + jQuery(this).attr("id") + "]");
		}
	});	
	
	jQuery(".callmeback-send").click(sendApplication);
});

