﻿/*
* Functionality for microform. 
* Requires:
*   - prototype.js
*   - scriptaculous
*   - microform-slide-controller
*   - microform-progress-controller
* Tom Elmore
*/


// attaches the auto progress events to all radiobuttons in the DOM
function attachRadioButtonOnClicks(clickEvent) {
    $$('input').each(function(inputBox){
        if(inputBox.getAttribute('type') == 'radio' && inputBox.value != '##other') {
	        Event.observe(inputBox, 'click', clickEvent);
        }
    });
}

// display:block on all fieldsets. part of the antiflicker measures
function displayHiddenFieldsets() {
    $$('fieldset').each(function(page){
        page.style.display = "block";
    }); 
}

// returns a control's validator based on its id
function getValidatorById(id) {
    for (var i = 0; i < Page_Validators.length; i++) {
        if( Page_Validators[i].controltovalidate == id ) {
            return Page_Validators[i];
        }
    }
    return null; // no validator found - perfectly possible since not all controls have validation
}

// returns a controls id based on the page it is on (alternatively, the index of fieldset within the dom)
function getControlByIndex(index) {
    var AllFieldsets = $$('fieldset');
    var Control = null;
    
    if (AllFieldsets[index].getElementsByTagName('textarea').length > 0){
        Control =  AllFieldsets[index].getElementsByTagName('textarea')[0].id;
    } else if (AllFieldsets[index].getElementsByTagName('select').length > 0) {
        Control = AllFieldsets[index].getElementsByTagName('select')[0].id;
    } else if(AllFieldsets[index].getElementsByTagName('input').length > 0) {
        Control = AllFieldsets[index].getElementsByTagName('input')[0].id;
    }
    
    return Control.replace(/_\d$/gi, ''); // radio and check box controls follow an id convention which needs correction
}


function getFirstUnansweredQuestionIndex () {
    var FirstEmptyInputId = null;

    // check the asp.net js validator objects and stop at first that fails
    for (var i = 0; i < Page_Validators.length; i++) {
        if( !Page_Validators[i].isvalid ) {
            FirstEmptyInputId = Page_Validators[i].controltovalidate;
            break;
        }
    }
    
    if( FirstEmptyInputId == null ) { return -1; }

    // manipulate the DOM to get the containing fieldset
    var FirstUnansweredQuestionFieldset = $(FirstEmptyInputId).parentNode.parentNode;

    // find the indexed position of our fieldset within the DOM
    var AllFieldsets = $$('fieldset');
    for (var j = 0; j < AllFieldsets.length; j++) {
        if(AllFieldsets[j] == FirstUnansweredQuestionFieldset) {
            return j;
        }
    }

    // return -1 if nothing found
    return -1;
}



function initialiseSlider() {
    
    var numberOfQuestions = $('slide').getElementsByTagName('fieldset').length; // a fieldset is a page in the sliding mechanism

    $('NumberOfPages').value = numberOfQuestions; // so can post to next page of multiview
    
    var controller = new SlideController($('slide'), 390, numberOfQuestions); // instantiate slide controller object
    
    // keep a note of the asp.net validation event so can use it in our own event (checkPageMoveLeftEvent)
    var validationEvent = $('ctl00_ContentHolder_SlidingForm_ButtonContinue').onclick;

    // movement events
    var moveLeftEvent = function(){ controller.delayIncPage(500); } // 500 ms delay
    var moveRightEvent = function(){controller.decPage();}

    // continue button has two functions; move the form along and submit when on last page.
    // this event checks which behaviour to use and checks validation if necessary
    var checkPageMoveLeftEvent = function () { 
                if( controller.isFinalPage() ) {  // fire the validation only if final page
                    if (!validationEvent()) {
                        var FailingPage = getFirstUnansweredQuestionIndex();
                        if( FailingPage > -1 ) { // -1 means could not find fieldset
                            controller.goToPage( FailingPage + 1 ); // controller is 1 based, index is 0 based
                            return false; 
                        }
                    } return true;
                } else { 
                    var ControlId = getControlByIndex(controller.page-1);
                    var Validator = getValidatorById(ControlId);
                    if( Validator != null ) {
                        ValidatorValidate(Validator);
                        if( !Validator.isvalid ) {
                            alert( Validator.errormessage  ); // display validation message
                            return false;
                        }
                    }
                    controller.incPage();
                    return false; // block post
                }
            } 

    var BackButtonHider = function (page) {
                if( page == 1 ) {
                    $('backButton').style.display = 'none';
                } else {
                    $('backButton').style.display = 'block';
                }
            }

    Event.observe($('backButton'), 'click', moveRightEvent);
   
    // links the back button to the form controller so can hide it on first page
    controller.observe(BackButtonHider);
    
    // attached directly so as to overwrite the validation
    $('ctl00_ContentHolder_SlidingForm_ButtonContinue').onclick = checkPageMoveLeftEvent;

    attachRadioButtonOnClicks(moveLeftEvent);
    
    // back button on contact page was clicked
    if (typeof ReturningFromContactPage != "undefined" && ReturningFromContactPage == true) {
        controller.jumpToLastPage();
    }

    return controller;
}








