/************************************************************************
 * Copyright © 2010, Devin DeLapp
 * All rights reserved.
 * http://www.devindelapp.com
 * 
 * Redistribution and use in source and/or binary forms, with or without
 * modification, are not permitted. Please see the included EULA for
 * additional restrictions, limitations and warranties.
 * The EULA is also available at http://www.devindelapp.com/docs/eula.pdf
 ************************************************************************/

$(document).ready(function(){	
	// set all datefields
	$(".datefield").datepicker();
	
	var root = $("#survey").scrollable({size: 1, clickable: false, keyboard:false});

	// some variables that we need
	var api = root.scrollable();
	
	// set submit button
	$('form').submit(function() {
		var validCheck1 = validatePage(root, api);
		var validCheck2 = validatePageCheckboxes(root, api);
			
		if(!validCheck1 || !validCheck2)
			return false;
	});
	 
	// validation logic is done inside the onBeforeSeek callback
	api.onBeforeSeek(function(event, i) {
	 
		// we are going 1 step backwards so no need for validation
		if (api.getIndex() < i) {
			
			var validCheck1 = validatePage(root, api);
			var validCheck2 = validatePageCheckboxes(root, api);
			
			if(!validCheck1 || !validCheck2)
				return false;
		}
		// update status bar
		$("#status li").removeClass("active").eq(i).addClass("active");
	 
	});
	// if tab is pressed on the next button seek to next page
	root.find("input.next").keydown(function(e) {
		if (e.keyCode == 9) {
	 
			// seeks to next tab by executing our validation routine
			api.next();
			e.preventDefault();
		}
	});
});
	
function validatePage(root, api)
{
	// 1. get current page
	var page = root.find(".page").eq(api.getIndex());

	 // 2. .. and all required fields inside the page
	 inputs = page.find(".required").removeClass("error");

	 // 3. .. which are empty
	 empty = inputs.filter(function() {
		return $(this).val().replace(/\s*\$$/g, '') == '';
	 });

	 // if there are empty fields, then
	if (empty.length) {

		// add a CSS class name "error" for empty & required fields
		empty.addClass("error");

		// cancel seeking of the scrollable by returning false
		return false;
	}
	return true;
}
	
function validatePageCheckboxes(root, api)
{
	// 1. get current page
	var page = root.find(".page").eq(api.getIndex());

	// 2. .. and all required fields inside the page
	var checkbox_group = page.find(".required_cb").removeClass("error");
	// If no checkbox groups found then it is obviously valid.
	if(checkbox_group.length == 0)
		return true;
	// 3. .. find all checkboxes within the checkbox group
	if (checkbox_group.find('input[type=checkbox]:checked').length == 0)
	{
		checkbox_group.addClass("error");

		// cancel seeking of the scrollable by returning false
		return false;
	}
	return true;
}
