﻿/*================================
	Form functions
==================================*/
/* Setting Current Validation Group to limit client side validation to one form*/
var currentValidationGroup;

function setCurrentValidationGroup(vGroupName) {
    currentValidationGroup = vGroupName;
}


$J(document).ready(function()
{

    //Custom form items
    $J('.custom-radios input[type=radio]').customInput();
    $J('.custom-checks input[type=checkbox]').customInput();



    //Focus text fields
    $J('.textfieldWrapper input').focus(function()
    {

        //remove the filled class or clear the watermark
        if ($J(this).hasClass('filled') == true) $J(this).removeClass('filled');
        else $J(this).val('');

        //if the field isn't in error state, change to focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().addClass('fieldFocus');

    });

    //Blur text fields
    $J('.textfieldWrapper input').blur(function()
    {

        //if the field isn't in error state, remove focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().removeClass('fieldFocus');

        if ($J(this).val() != "")
        {
            //Keep text black and don't add watermark
            $J(this).addClass('filled');

        } else if ($J(this).attr('type') != 'password')
        {
            //If the text isn't a password field, insert title as the watermark
            temp = $J(this).attr('title');
            $J(this).val(temp);

        } else if ($J(this).attr('type') == 'password')
        {
            //Shouldn't do anything to mess validation
        }
    });

    //Set filled states on load
    $J('.textfieldWrapper input').each(function()
    {
        if ($J(this).val() != "" && $J(this).val() != $J(this).attr('title'))
        {
            //Keep text black and don't add watermark
            $J(this).addClass('filled');
        }

        if ($J(this).attr('type') == 'password') $J(this).val("");
    });

    //Select field focus
    $J('.dropdownFullWrapper select').focus(function()
    {
        //if the field isn't in error state, change to focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().addClass('fieldFocus');

    });

    //Select field blur - misc size
    $J('.dropdownMiscWrapper select').blur(function()
    {
        //if the field isn't in error state, remove focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().removeClass('fieldFocus');
    });
    
    //Select field focus - misc size
    $J('.dropdownMiscWrapper select').focus(function()
    {
        //if the field isn't in error state, change to focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().addClass('fieldFocus');
    });

    //Select field blur
    $J('.dropdownFullWrapper select').blur(function()
    {
        //if the field isn't in error state, remove focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().removeClass('fieldFocus');
    });


    //Focus text areas
    $J('.textareaWrapper textarea').focus(function()
    {

        //remove the filled class or clear the watermark
        if ($J(this).hasClass('filled') == true) $J(this).removeClass('filled');
        else $J(this).val('');

        //if the field isn't in error state, change to focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().addClass('fieldFocus');

    });

    //Blur text fields
    $J('.textareaWrapper textarea').blur(function()
    {

        //if the field isn't in error state, remove focus state
        if ($J(this).parent().hasClass('fieldError') == false) $J(this).parent().removeClass('fieldFocus');

        if ($J(this).val() != "" && $J(this).val() != $J(this).attr('title'))
        {
            //Keep text black and don't add watermark
            $J(this).addClass('filled');
        } else
        {
            temp = $J(this).attr('title');
            $J(this).val(temp);
        }
    });
    
    

    $J('.communityOptions .groupTable td input').click(function()
    {

        var e = $J('.communityOptions .groupTable td input');
        var howManySelectedTopics = 0;
        var totalCommunityGroups = e.length;

        //iterate through input fields
        for (i = 0; i < e.length; i++)
        {
            if (e[i].checked == false)
            {
                howManySelectedTopics++;
            }
        }

        // Check if counter is the same as amount of fields
        if (howManySelectedTopics == totalCommunityGroups)
        {
            //disable button
            $J('.btnJoinCommunity').attr('disabled', 'disabled');
            $J('.communityOptions').prepend('<p class="error">You must select at least one interest to join this community</p>');
        }
        else
        {
            if ($J('.btnJoinCommunity').attr('disabled'))
            {
                $J('.btnJoinCommunity').removeAttr('disabled');
                $J('.communityOptions .error').remove();
            }

        }

    });



    /* Attach the validation handler to the form's submit event*/
    
    
    if($J('div.naturopathRequest').length > 0 && $J('.requestStep11').length <= 0){
        //Naturopath request but not the details page 
        $J("form").submit(function(){ return naturopathValidation(); });    
             
    }else{
        $J("form").submit(function() { updateValidatorStyles(); });
    }

    
    backupValidationMessages();


});


/*====================================================================
    Create backup properties for errormessage values on validators 
    (IE7 onchange validation workaround)
======================================================================*/
function backupValidationMessages() {

    if (typeof (Page_Validators) == "undefined" || Page_Validators == null) return;

    for (var i = 0; i < Page_Validators.length; i++) {

        var validator = Page_Validators[i];
        if (validator.errormessage != null) validator.errormessagebackup = validator.errormessage;

    }

}


/*================================
	Form validation functions
==================================*/
/* Called when the form is submitted, iterates over the validation
   controls on the page, setting their styles to display either valid or invalid
*/
function updateValidatorStyles()
{
    
    if( typeof( Page_Validators ) == "undefined" || Page_Validators == null ) return( true ); 
    
    var pageIsValid = true;
    
    for( var i = 0; i < Page_Validators.length; i++ ) 
    {
        var validator = Page_Validators[ i ];

        if ((currentValidationGroup != "" && currentValidationGroup != null && validator.validationGroup == currentValidationGroup)
            || (!currentValidationGroup || currentValidationGroup == "" || currentValidationGroup == null)) {

            // Special case for text boxes that contain default text!
            if (validator.oldErrorMessage != null && validator.oldErrorMessage.length > 0) {
                validator.errormessage = validator.oldErrorMessage;
                validator.oldErrorMessage = "";
            }

            if ((validator.type == "text" || validator.type == "textarea") && validator.value == validator.title) {
                validator.isvalid = false;
                validator.oldErrorMessage = validator.errormessage;
                validator.errormessage = validator.requiredValueMissingErrorMessage;                
            }
    
            setWrapperClassAndValidationMessage(validator);

            if (pageIsValid && !validator.isvalid) pageIsValid = false;

        } 
        
    }
    
    $J('.naturopathRequest .formContent .requestStep11 input[type=hidden]').each(function(){
        if($J(this).attr('value') == "" || $J(this).attr('value') == null){ 
            pageIsValid = false;
            $J('.naturopathRequest .requestValidation').css('display', 'block');
        }
    });
    //Reset validation group to null
    currentValidationGroup = null;
    
    //Custom subscribe form messages
    if(pageIsValid == false){
        $J('.registerFormEmailMessage').css('display', 'none');
        $J('.registerFormErrorMessage').css('display', 'block');
    }
    
    return( pageIsValid );
    
}

/* Sets the style of the wrapper div around the input field 
   to either a valid or invalid state
*/
function setWrapperClassAndValidationMessage( validator )
{

    var wrapperDiv = $J( "#" + validator.id ).parents( ".fieldWrapper" );   
    if( wrapperDiv != null && wrapperDiv.length > 0 )
    {

        var errorMessage;
        var validationText = (validator.errormessage != null) ? validator.errormessage : validator.errormessagebackup;

        errorMessage = (!validator.isvalid ? validationText : "");

        var messageDiv = wrapperDiv.siblings(".fieldValidation");

        messageDiv.html( errorMessage );

        if( validator.isvalid == false ) 
        { 
            wrapperDiv.addClass( "fieldError" );
            if( messageDiv != null && messageDiv.length > 0 ) messageDiv.addClass( "fieldValidationActive" ); 
        }
        
        else 
        { 
            wrapperDiv.removeClass( "fieldError" );
            if( messageDiv != null && messageDiv.length > 0 ) messageDiv.removeClass( "fieldValidationActive" ); 
        }
        
    }
    
}

function updateValidationGroup( validationGroup )
{
    ValidatorOnLoad();
    //Page_TestValidate( validationGroup );
    updateValidatorStyles();
}

function CheckIsRequiredWatermark(control, args) {
	if ((control.type == "text" || control.type == "textarea") && control.value == control.title) {
		args.IsValid = false;
	}
}

function CheckHasTickedCheckBox(control, args) {
	if ((control.type != "checkbox") || control.checked == false)
		args.IsValid = false;
	else
		args.IsValid = true;
}

function CheckValidThaiMobileNumber(control, args) {
    //if (!(/^ *[0-9]+ *$/.test(control.value))) {
    if (isNaN(control.value) || control.value.substring(0,2) != '08') {
        args.IsValid = false;
    }
}

function CheckValidPostcodeNumber(control, args) {
    if (isNaN(control.value) || (control.value.length != 5)) {
        args.IsValid = false;        
    }
}

function isNumber(param) {
    return(parseInt(param) && param != "");
}

function CheckValidAustralianDate(control, args) {
	if ((control.type == "text" || control.type == "textarea")){
	    if (control.value == control.title) {
	        return false;
	    }
	    else {
	        var date = new Date();
	        var dateSegments = control.value.split("/");
	        // 11 month year (0-11)
	        date.setFullYear(dateSegments[2], dateSegments[1] - 1, dateSegments[0]);
	        if (date.getFullYear() != dateSegments[2]
	            || date.getMonth() != dateSegments[1] - 1
	            || date.getDate() != dateSegments[0]) {

	            args.IsValid = false;
	        }
	    }
    }
}
