$( function() {
    
    window.OK = function(val) { return val !== undefined && val !== null && val !== false; }
    window.PR = function() { if ( OK( window.console ) ) window.console.debug( arguments ); }
    
    $.fn.extend( {
        bindRemove: function() {
            PR( "BIND", $( this ).find( 'a.remove' ) );
            $( this ).find( 'a.remove' ).live( 'click', function() {
                var rel = $( this ).attr( 'rel' ),
                    url = $( this ).attr( 'href' )
                ;
                if ( !OK( url ) ) return false;
                if ( OK( rel ) ) $( rel ).remove();
                $.get( url );
                return false;
            } );
        }
    } );
    
    
    var countdown = [];
    $( '.countdown-timer' ).each( function( idx ) {
        var secs = parseInt( $( this ).attr( 'rel' ) );
        var end = new Date( ( new Date() ).getTime() + secs * 1000 );
        countdown.push( [ end, this ] );
    } );
    if ( countdown.length > 0 ) {
        setInterval( function() {
            var now = new Date().getTime() / 1000;
            $( countdown ).each( function() {
                var end = this[0].getTime() / 1000, el = this[1];
                $( el ).text( formatCountdown( end - now ) );
            } );
        }, 1000 );
    }
    
    if ( $( '#AccountPhone' ).length > 0 ) {
        $( '#x_allow_phone_check' )[ $( '#AccountPhone' ).keyup( function() {
            $( '#x_allow_phone_check' )[$( this ).val().length > 0 ? 'show' : 'hide' ]();
        } ).val().length > 0 ? 'show' : 'hide' ]();
    }
    
} );


function formatCountdown( secs ) {
    if ( secs < 0 ) secs = 0;
    var days    = Math.floor( secs / 86400 ); secs -= days * 86400; if ( days < 10 ) days = "0"+ days;
    var hours   = Math.floor( secs / 3600 ); secs -= hours * 3600; if ( hours < 10 ) hours = "0"+ hours;
    var minutes = Math.floor( secs / 60 ); secs -= minutes * 60; if ( minutes < 10 ) minutes = "0"+ minutes;
    secs = Math.floor( secs );
    if ( secs < 10 ) secs = "0"+ secs;
    return [ days, hours, minutes, secs ].join( ':' );
}

