var player = {};
var domPlayer = [];
var timerObj = [];
var timerTimes = [];
var timerMode = [];
var completed = [];
function playerReady(thePlayer) {
	if ( thePlayer.id == 'undefined' ) return;
	player[thePlayer.id] = document.getElementById(thePlayer.id);
	domPlayer[domPlayer.length] = document.getElementById(thePlayer.id);
	addListeners(thePlayer.id);
}

function addListeners(id) {
	if (player[id]) {
		player[id].addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners('"+id+"')",100);
	}
}

function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate;
	previousState = obj.oldstate;
	if ( previousState == "BUFFERING" && currentState == "PLAYING" ) {
		startTimer(obj.id);
	} else if ( currentState == "PLAYING" ) {
		if ( timerMode == false )
			playTimer(obj.id);
	}
	if ( currentState == 'PAUSED' )
		pauseTimer(obj.id);
	if ( currentState == 'IDLE' )
		stopTimer(obj.id);
	if ( currentState == 'COMPLETED' )
		if ( completed == false )
			updateCounter(obj.id);
	//alert ( obj.id );
	/*
	if ((currentState == "COMPLETED")&&(previousState == "PLAYING")) {
		var curentFile = player[obj.id].getPlaylist()[0].file;
		var scr = document.createElement ( 'script' );
		scr.setAttribute ( 'src', '/flashv.php?file='+curentFile+'&tmp='+Math.random() );
		document.getElementById('main').appendChild ( scr );
	}
	*/
}


function startTimer ( id ) {
	timerTimes[id] = 0;
	timerMode[id] = true;
	completed[id] = false;
	timerObj[id] = setTimeout ( 'incTimes("'+id+'")', 1000 );
}

function pauseTimer ( id ) {
	timerMode[id] = false;
}

function playTimer ( id ) {
	timerMode[id] = true;
}

function stopTimer ( id ) {
	timerTimes[id] = 0;
	timerMode[id] = false;
	if ( timerObj[id] != null ) {
		clearTimeout(timerObj[id]);
		timerObj[id] = null;
	}
}

function incTimes ( id ) {
	if ( timerMode[id] == true ) {
		timerTimes[id]++;
	}
	timerObj[id] = setTimeout ( 'incTimes("'+id+'")', 1000 );
	checkTimer(id);
}

function checkTimer ( id ) {
	if ( timerTimes[id] >= 10 ) {
		stopTimer(id);
		updateCounter(id);
	}
}

function updateCounter ( id ) {
	var curentFile = player[id].getPlaylist()[0].file;
	var scr = document.createElement ( 'script' );
	scr.setAttribute ( 'src', '/flashv.php?file='+curentFile+'&tmp='+Math.random() );
	document.getElementById('main').appendChild ( scr );
}


function startPlayer(num) {
	if ( domPlayer[num] )
		domPlayer[num].sendEvent("PLAY","true");
	return false;
}