/**
 * Valide un formulaire HTML selon une expression régulière donnée
 */                       
 
/* Parameters */
var failClass = 'failed';
var passClass = 'pass';
var reqClass  = 'required';
var timeout   = .1;

/* Validation types */
var validationTypes = new Array();
validationTypes[ 'email' ]        = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
validationTypes[ 'name' ]         = /^[-A-Za-zàÀèÈéÉïÏîÎôÔêÊçÇ]+[A-Za-z\-\sàÀèÈéÉïÏîÎôÔêÊçÇâÂ\.\,\"\'\“\”\’\‘\-\(\)]*$/;
validationTypes[ 'initial' ]      = /^[A-Za-zàÀèÈéÉïÏîÎôÔêÊçÇ]*$/;
validationTypes[ 'text' ]         = /^.+$/;
validationTypes[ 'multilinetxt' ] = /^[\s\S]+$/;
validationTypes[ 'postalCode' ]   = /^([a-z]\d[a-z]\s?\d[a-z]\d|\d{5})$/i;
validationTypes[ 'password' ]     = /^[a-zA-Z0-9]{6,35}$/; 
validationTypes[ 'date' ]         = /^[0-9]{4}(\s)?(\-|\\|\/)(\s)?[0-9]{1,2}(\s)?(\-|\\|\/)(\s)?[0-9]{2}$/;
validationTypes[ 'datetime' ]         = /^[0-9]{4}(\s)?(\-|\\|\/)(\s)?[0-9]{1,2}(\s)?(\-|\\|\/)(\s)?[0-9]{2}(\s)?([0-9]{1,2}(\s)?:(\s)?[0-9]{1,2}(\s)?:(\s)?[0-9]{1,2}(\s)?)?$/;
validationTypes[ 'title' ]        = /^.+$/; 
validationTypes[ 'nbJour' ]       = /^[1-6]{1}$/;
validationTypes[ 'microUrl' ]     = /^[a-zA-Z0-9._-]{4,40}$/;
validationTypes[ 'phone' ]        = /^([0-9]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
validationTypes[ 'ccNumber' ]     = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})$/; // Visa and MC only
validationTypes[ 'ccMonth' ]      = /^[0-1][0-9]$/;  
validationTypes[ 'ccYear' ]       = /^20[0-9]{2}$/;  
validationTypes[ 'securityCode' ] = /^[0-9]{3}$/;  

var tabChamps = new Array();
var allowVide = new Array();

function Validation( formFieldId, validationType, permetVide ) {
	if( formFieldId == 'select_province' ) {
		provinceListing = new Ajax.Updater( formFieldId, '../ajax/getProvinces.php', {method: 'get', parameters: {} } );  
	} else if( formFieldId == 'select_region' ) {
		provinceListing = new Ajax.Updater( formFieldId, '../ajax/getRegions.php', {method: 'get', parameters: { province: '' } } );
	} else {
    	if ( typeof permetVide == "undefined" || !permetVide ) {
	        permetVide = false;
	        tabChamps[ formFieldId ] = 'required'; 
	        allowVide[ formFieldId ] = false;
	    } else {
	        tabChamps[ formFieldId ] = false; 
	        allowVide[ formFieldId ] = true;
	    }
	    
	    addImages( formFieldId, permetVide );
	    
	    if( validationTypes[ validationType ] != null ) {
	        var regex = validationTypes[ validationType ]; 
	        if( $F( formFieldId ) == "" && permetVide == true )  {
	           tabChamps[ formFieldId ] = true; 
	         } else {
	           tabChamps[ formFieldId ] = regex.test( $F( formFieldId ) );   
	         }  
	         
	        if( $F( formFieldId ).length > 0 ) {
	            changeFieldState( formFieldId, tabChamps[ formFieldId ] );
	        }
	        
	        new Form.Element.Observer( formFieldId, timeout, function( field, value ) {
	        	var regex = validationTypes[ validationType ];
	        	
	    		if( formFieldId == 'account_email' ) {
	    			if ( regex.test( value ) ) {
	    				new Ajax.Request('../ajax/verifierCourriel.php?courriel='+value+'&uid=' + $F( 'account_noUsagerEmail' ) , {
	    				
		    				onSuccess: function(response) {
		    					if( parseInt( response.responseText ) == 1 ) {
		    						changeFieldState( field.id, false );
		    					} else {
		    						changeFieldState( field.id, true );
		    					}
		    				}
		    			} );
	    			} else {
	    				changeFieldState( field.id, false );
	    			}
	    		} else {
	    			if( allowVide[ field.id ] && value == '' ) {
	    				changeFieldState( field.id, true );
	    			} else {
    					changeFieldState( field.id, regex.test( value ) );
	    			}
	    		}
	        } );
	    }
	}
}

function Comparison( formId, formFieldId, compareToId ) {
    addImages( formFieldId );
    //tabChamps[ formFieldId ] = false;
    new Form.Observer( formId, timeout, function( field, value ) {
        if( $F( formFieldId ).length > 0 ) {
            if( $F( formFieldId ) == $F( compareToId ) ) {
                changeFieldState( formFieldId, true );
            } else {
                changeFieldState( formFieldId, false );
            }
        }
    } );
}      

function getImagePath() {
    return document.location.toString().substring( 0, document.location.toString().indexOf( '/', 8 ) );
}

function addImages( field, permetVide ) {
    getImagePath();
    Insertion.After( field, '<img id="' + field + '_' + failClass + '" src="' + getImagePath() + '/images/icon_check_unavailable.gif" alt="Invalid entry" class="right" style="display:none;" />' );
    Insertion.After( field, '<img id="' + field + '_' + passClass + '" src="' + getImagePath() + '/images/icon_check_available.gif" alt="Valid entry" class="right" style="display:none;" />' );
    
    if( permetVide ) {
        Insertion.After( field, '<span id="' + field + '_' + reqClass + '" style="display:none;"></span>' );
    } else {
        Insertion.After( field, '<img id="' + field + '_' + reqClass + '" src="' + getImagePath() + '/images/icon_mandatory.gif" alt="Required entry" class="right" />' );
    }
}

function changeFieldState( field, valid ) {
    $( field + '_' + reqClass ).hide();
    if( valid ) {
        $( field + '_' + failClass ).hide();  
        $( field + '_' + passClass ).show();   
        tabChamps[ field ] = true;   
    } else {
        $( field + '_' + failClass ).show();
        $( field + '_' + passClass ).hide();
        tabChamps[ field ] = false;
    }
}

function checkForm() { 
    var formValid = true;
    for( champs in tabChamps ) {
        if( tabChamps[ champs ] == false ) {
            formValid = false;
            changeFieldState( champs, false ); 
        }
    }
    
    var check = chechNewspaper();
    if( !check ) {
        formValid = false;
    }
    return formValid;
}

function chechNewspaper() {
    var retour = true;
    if( typeof( formats ) != 'undefined' ) {
        if( formats.length == 0 ) {
            retour = false;
        }
    }
    return retour;
}

function changeVisible( divId, visible ) {
    if( visible ) {
        $( divId ).show();
    } else {
        $( divId ).hide();
    }
}

function call_changementProvinceNew( input, idPays, idProvince, pageLang ) {
	provinceListing = new Ajax.Updater( input, '../ajax/afficherProvinceNew.php', {method: 'get', parameters: {idPays: idPays, idProvince: idProvince, pageLang: pageLang } } );  
}

function call_changementProvinceSearch( input, idPays, idProvince, pageLang ) {
	provinceListing = new Ajax.Updater( input, '../ajax/afficherProvinceSearch.php', {method: 'get', parameters: {idPays: idPays, idProvince: idProvince, pageLang: pageLang } } );  
}


//**********************************************************************
// @Function: only_numbers();
// @Pages: payment.php
// @Desc: Make sure only numbers are typed in a text input (should be triggered by onkeypress();)

function only_numbers( e ) {
    var code = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;    
    if ( ( code >= 48 && code <= 57 ) || code == 8 || code == 37 || code == 39 || code == 46 || code == 9 ) {
        return true;
    } else {
        return false;
    }
}

//**********************************************************************
// @Function: changeClientType();
// @Pages: admin/billing.php
// @Desc: Change the form inputs wether the client is a funeral home or a person

function changeClientType( divisionId, totalDivID, pageLang, noParution ) {
	$( divisionId ).show();
	if( divisionId == 'individual' ) {
		$( 'funeral_home' ).hide();
		
		swapTaxes( totalDivID, $F( 'client_province' ), $F( 'client_country' ), pageLang, noParution );
		
	} else if( divisionId == 'funeral_home' ) {
		$( 'individual' ).hide();
		
		updateTaxesFromFuneralHome( 'funeral_homes_country', $F( 'existing_funeral_homes' ), pageLang, totalDivID, 'funeral_home_province', 'funeral_home_country', noParution );
	}
}

//**********************************************************************
// @Function: updateFunrealHomesList();
// @Pages: admin/billing.php
// @Desc: Updates the list of funeral homes

function updateFunrealHomesList( divisionId, provinceId, countryDivisionId, pageLang ) {
	countryId = $( countryDivisionId ).value;
	returnValue = new Ajax.Updater( divisionId, '../ajax/funeralHomesList.php', {method: 'get', parameters: { provinceId: provinceId, countryId: countryId, pageLang: pageLang } } );
}

//**********************************************************************
// @Function: removeOrganisationAccess();
// @Pages: admin/admin_organisation_usagers.php
// @Desc: Removes a user from the administrators for a selected organisation

function removeOrganisationAccess( noUsager, noOrganisation, pageLang ) {
	returnValue = new Ajax.Updater( 'usager-'+noUsager, '../ajax/removeOrganisationAccess.php', {method: 'get', parameters: {noUsager: noUsager, noOrganisation: noOrganisation, pageLang: pageLang } } );  
}


//**********************************************************************
// @Function: updateTaxesFromFuneralHome();
// @Pages: admin/billing.php
// @Desc: Same as swapTaxes() but retrieves the province from organisationInfos. If organisationInfos is blank, update according to the new province entered.

function updateTaxesFromFuneralHome( countrySelectId, organisationInfos, pageLang, totalDivID, newProvinceField, newCountryField, noParution ) {
	organisationArray = organisationInfos.split(';');
	if( organisationArray.length == 2 ) {
		swapTaxes( totalDivID, organisationArray[1], countrySelectId, pageLang, noParution );
	} else if( organisationInfos == '--' ) {
		swapTaxes( totalDivID, $F( newProvinceField ), $F( newCountryField ), pageLang, noParution )
	}
}

//**********************************************************************
// @Function: swapTaxes_FuneralHomes();
// @Pages: admin/billing.php
// @Desc: Verify if the funeralHomesSelectId input is empty before executing swapTaxes(); 
function swapTaxes_FuneralHomes( totalDivID, idProvince, idPays, pageLang, funeralHomesSelectId, noParution ) {
	if( $F( funeralHomesSelectId ) == '' || $F( funeralHomesSelectId ) == '--' ) {
		swapTaxes( totalDivID, idProvince, idPays, pageLang, noParution );
	}
}

//**********************************************************************
// @Function: changementCountryTaxes_FuneralHomes();
// @Pages: admin/billing.php
// @Desc: Verify if the funeralHomesSelectId input is empty before executing call_changementProvinceTaxes(); 

function changementCountryTaxes_FuneralHomes( input, idPays, idProvince, pageLang, totalDivID, funeralHomesSelectId, noParution ) {
	if( $F( funeralHomesSelectId ) == '' || $F( funeralHomesSelectId ) == '--' ) {
		call_changementProvinceTaxes( input, idPays, idProvince, pageLang, totalDivID, noParution );
	}
}

//**********************************************************************
// @Function: swapTaxes();
// @Pages: admin/billing.php
// @Desc: Updates the taxes and total section at the bottom of every billing/payment pages according to the seller's province, client's province and client's country.

function swapTaxes( totalDivID, idProvince, idPays, pageLang, noParution ) {
	if( idProvince.length > 2 ) {
		clientProvince = ( document.getElementById( idProvince ) ) ? $F( idProvince ) : '';
	} else {
		clientProvince = idProvince;
	}
	
	clientCountry = ( idPays.length > 2 ) ? $F( idPays ) : idPays;
	
	taxesListing = new Ajax.Updater(
		totalDivID,
		'../ajax/generateTaxes.php',
		{
				method: 'post',
				parameters: {
						clientProvince: clientProvince, 
						pageLang: pageLang,
						clientCountry: clientCountry,
						noParution: noParution
				}
		}
	);  
}

function updateRegionsList( inputId, idProvince ) {
	returnValue = new Ajax.Updater(
		inputId,
		'../ajax/getRegions.php',
		{
			method: 'get',
			parameters: {
				province: idProvince,
				online: 0
			}
		}
	);
}

function call_changementProvinceTaxes( totalDivID, provincesSelectInput, idPays, pageLang, noParution ) {
    provinceListing = new Ajax.Updater(
    	provincesSelectInput,
    	'../ajax/afficherProvinceTaxes.php',
    	{
    		method: 'post',
    		parameters: {
    			idPays: idPays,
    			pageLang: pageLang
    		}
    	}
    );
    
    swapTaxes( totalDivID, '--', idPays, pageLang, noParution );
}

function call_changementProvinceBilling( input, idPays, idProvince, pageLang ) {
    provinceListing = new Ajax.Updater( input, '../ajax/afficherProvinceTaxes.php', {method: 'get', parameters: {idPays: idPays, idProvince: idProvince, pageLang: pageLang } } );
    
    if( idPays == 'CA' ) $('province_change').value='1';
}