// code to use the jquery paginate plugin to provide optional pagination support for widgets
//  inserted into the FormControllerWidget

var first = true;

// callback for page selection
function pageSelectCallback(page_index, jq) {
	var do_paginate = first || validate();
	first = false;
	if (do_paginate) {
	  // hide all the pagination_sections, and then show the one for the selected page
	  $j('#enclosing_pages div.pagination_section').hide();
	  $j('#enclosing_pages div.pagination_section:eq('+page_index+')').show();
	  // if this is the last page, show the submit button
	  show_hide_submit(page_index);
		setProgressBar(page_index);
	}
  return do_paginate;
}
         
/** 
 * setup for the pagination plugin
*/
function initPagination(prev_text, next_text) {
  // don't bother to do anything if we only have 1 pagination section
	rewrite_hidden_input_containers();
  var num_entries = $j(".pagination_section").length;
  if (num_entries <= 1) {
     return num_entries;
  }
  wrap_display_area();	// create containers to display pagination, etc.
  var current_page = first_error_page();
  // Create pagination element
  $j("#pagination_area").pagination(num_entries, {
    num_edge_entries: 0,
    num_display_entries: 0,
    current_page: current_page,
    prev_show_always: false,
    next_show_always: false,
		prev_text: prev_text,
		next_text: next_text,
    callback: pageSelectCallback,
    items_per_page:1
  });
  return num_entries;
}

// provide the html for the progress bar
function progressBarHtml() {
	html = "<div class='meter-wrap'> \
				<div class='meter-value' style='background-color: #0a0; width: 0%;'> \
	        <div class='meter-text'> \
	            Progress \
	        </div> \
	    </div> \
	</div>";
	return html;
}

function wrap_display_area() {
  // wrap the pagination sections in a parent div - not strictly necessary, but it makes things a bit more tidy
  $j(".pagination_section:first").before("<div id='enclosing_pages'> </div>");
  $j(".pagination_section").appendTo("#enclosing_pages");
  // the pagination_area will be filled in by the plugin
	$j("#enclosing_pages").before(progressBarHtml());
  $j("#enclosing_pages").after("<div id='pagination_area' class='questions_pagination'> </div>");
	//$j("#pagination_area").after(progressBarHtml());
}

// iterate over 
function rewrite_hidden_input_containers() {
	$j('.pagination_section').each(function() {
		var visible_input_elements = false;
		var section = $j(this);
	  section.find(':visible :input').each(function() {
 		  if ((this.type == 'text' || this.type == 'select-one') && (this.offsetWidth > 0 || this.offsetHeight > 0)) {
 				visible_input_elements = true;
 			}
		});
		if (!visible_input_elements) {
			section.removeClass('pagination_section');
			section.addClass('no_pagination_section');
		}
	});
}

// hide/disable the submit button until we are on the last section
function show_hide_submit(index) {
  var num_sections = $j(".pagination_section").length;
  // get the form sibling of the parent of our sections and its submit child
  var submit_button = $j(".pagination_section:first").parent().siblings(":buttonContainer").children(":submit");
  if (index == num_sections - 1) {
		submit_button.removeAttr('disabled');
		submit_button.show();
	} else {
		submit_button.hide();
		submit_button.attr('disabled', 'disabled');
	}
};

// find the index of the first section with an error on it, if any
function first_error_page() {
  var error_index = -1;
  $j(".pagination_section").each(function(i) {
    errors = $j(this).find('label.error');
    if (errors.length > 0 && error_index < 0) {
      error_index = i;
    }
  });  
  return error_index < 0 ? 0 : error_index;
}

// do js validation of visible text and single-select inputs
// ensure that their values are non-blank and not 'pleaseselect', respectively
// mostly taken from Raphael's code, this will provide 95% of the desired functionality now
// TODO - do an ajax call back to the server to do Rails model validation on all inputs
function validate() {
	var errors = false;

  $j('#enclosing_pages .pagination_section :visible :input').each(function() {
	  if ((this.type == 'text' || this.type == 'select-one') && (this.offsetWidth > 0 || this.offsetHeight > 0)) {
			// if an element has a container which is hidden, it will still be selected above (pre jQuery1.3.2)
			input = $j(this);
			if (input.attr('class').indexOf('optional') < 0 &&
          ((this.type == 'text' && input.val() == '') || (this.type == 'select-one' && input.val() == 'pleaseselect'))) {
				$j('label[for=' + input.attr('id') +']').addClass('error');
				errors = true;
			} else {
				$j('label[for=' + input.attr('id') +']').removeClass('error');
			}
	}
	});
  return !errors;
}

// set the progress bar
function setProgressBar(page_index) {
	currentStep = page_index;
	pct = ((currentStep / $j(".pagination_section").length)) * 100 | 0;
	$j('.meter-value').css('width', pct + '%');
	return false;
}

jQuery.extend(
  jQuery.expr[ ":" ], 
  { reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);
