function zeroPad(num,count)
{
    var numZeropad = num + '';
    while(numZeropad.length < count) {
	numZeropad = "0" + numZeropad;
    }
    return numZeropad;
}

function updateRedtubeThumb(node) {
    m = node.src.match(/\_([0-9]{3})\./);
    if(m!=null) {
	frame = parseInt( m[1], 10) +1;

	//alert('m[1] '+m[1]+' frame '+frame);

	tries = 0;

	do {
	    if(frame>16) {
		frame = 1;
	    }
	    if(document.getElementById(node.id+'_'+frame).naturalWidth==160) {
		break;
	    } else {
		frame++;
	    }

	} while(tries++<16);
	//alert('new frame '+frame);

	node.src = node.src.replace(/\_([0-9]{3})\./,'_'+zeroPad(frame, 3)+'.');
    }
}

function playRedtubeThumb() {
    //    all
    //    nodes = document.getElementsByTagName('img');
    //
    //    $each(nodes, function(node){
    //	if(node.className=='redtubeThumb') {
    //	    updateRedtubeThumb(node);
    //	}
    //    })

    if(playedThumb!=null) {
	updateRedtubeThumb(playedThumb);
    }

    setTimeout('playRedtubeThumb();', 1500);
}

function stopRedtubeThumb() {
    if(playedThumb!=null) {
	playedThumb.src=orginalFrame;
	playedThumb = null;
    }
}

function startRedtubeThumb(node) {
    stopRedtubeThumb();
    orginalFrame = node.src;
    playedThumb = node;

    if(document.getElementById(node.id+'_1')==null) {
	thumb_parent=document.getElementById('p_'+node.id);

	out = '';
	m = node.src.match(/\_([0-9]{3})\./);
	if(m!=null) {
	    for( i=0; i<16; i++) {
		frame = parseInt( m[1], 10) +i;

		//alert('m[1] '+m[1]+' frame '+frame);

		if(frame>16) {
		    frame = frame%16;
		}

		out+='<img src='+ node.src.replace(/\_([0-9]{3})\./,'_'+zeroPad(frame, 3)+'.') + ' alt="" class="redtubeThumb" id="'+node.id+'_'+frame+'" />';

	    }
	}
	thumb_parent.innerHTML=out;
    }
}

playedThumb = null;
orginalFrame = null;

window.addEvent('domready',function () {
    playRedtubeThumb();
})
