// Contact form script

jQuery( function() {
    // Validation on submit od the form.
    $( '#form-contact' ).live( 'submit', function() {
        var all_valid = true;

        // Validation of required field.
        $( '#form-contact input.required, #form-contact textarea.required' ).each( function( arg ) {
            if( $( this ).attr( 'value' ) === '' ) {
                $( this ).addClass( 'notvalid' );
                all_valid = false;
            }
        } );
 
        if( all_valid ) {
            $( '#form-contact input:disabled' ).each( function( arg ) {
                $( this ).attr( 'disabled', false );
            } );
            return true;
        } else {
            return false;
        }
    } );

    // Removed notvalid class on focus of field.
    $( '#form-contact input.required, #form-contact textarea.required' ).bind( 'focus', function() {
        $( this ).removeClass( 'notvalid' );
    } );

    // On reset also reset notvalid status.
    $( '#form-contact' ).bind( 'reset', function() {
        $( '#form-contact input.required, #form-contact textarea.required' ).each( function() {
            $( this ).removeClass( 'notvalid' );            
        } );
    } );

    // We populate field base on the postal code.
    $( '#form-contact #contact_postal_code' ).live( 'keyup', function() {
        if( $( '#form-contact #contact_postal_code' ).attr( 'value' ).length >= 5 ) {
            $.getJSON( '/postalCode.php', { postal_code: $( '#form-contact #contact_postal_code' ).attr( 'value' ) }, function( data ) {
                if( data.error === false ) {
                    $( '#form-contact #contact_city' ).attr( 'value', data.item.city );
                    $( '#form-contact #contact_province' ).attr( 'value', data.item.province );
                    $( '#form-contact #contact_country' ).attr( 'value', data.item.country );
                    $( '#form-contact #contact_postal_code' ).attr( 'value', data.item.postal_code );
                    if( $( '#form-contact #contact_phone' ).attr( 'value' ).length === 0 ) {
                        $( '#form-contact #contact_phone' ).attr( 'value', '(' + data.item.area_code + ') ' );
                        $( '#form-contact #contact_phone' ).focus();
                    }
                }
            } );
        }
    } );
} );
