var obj = Array( );

var tt = "url(/template/pzw/img/star1.gif) no-repeat";
var f = "url(/template/pzw/img/star1d.gif) no-repeat";
var i, j, n, t;

function addEvent( o, e, f )
{
    if( o.addEventListener )
	o.addEventListener( e, f, false );
    else
	o['on'+e]=f;
}

function onOver( )
{
    var tmp = this.name.split( '_' );
    j = tmp[ 1 ];
    n = Number( tmp[ 2 ] ) + 1;
    for( i=0; i<5; ++i ){
	obj[ j ][ i ][ 0 ].style.background = i<n ? tt : f;
    }
}

function onOut( )
{
    var tmp = this.name.split( '_' );
    j = tmp[ 1 ];
    for( i=0; i<5; ++i ){
        obj[ j ][ i ][ 0 ].style.background = obj[ j ][ i ][ 1 ];
    }
}

function onClick()
{
    j = this.name.split('_');
    var y = j[ 2 ];
    var x = j[ 1 ];

    $.ajax( 
    {
	url: '/source/ajax/oceny.php?id_prezentacji='+obj[x][y][2]+'&id_wpisu='+obj[x][y][3]+'&prefix_modulu='+obj[x][y][4]+'&ocena='+(Number(y)+1),
	type: 'GET',
	dataType: 'xml',
	success: function( xml )
	{
    	    punkty = $(xml).find('punkty').text();
    	    glosy = $(xml).find('glosy').text();
	    komunikat = $(xml).find('komunikat').text();
	    note = Math.round( punkty/glosy );
	    setNote( obj[x][y][5], note, glosy, komunikat );
	}
    } );
    return false;
}

function setNote( th, note, suma_glosow, komunikat )
{
    var a = th.getElementsByTagName( 'a' );
    j = a[ 0 ].name.split( '_' );
    j = Number( j[ 1 ] );

    for( i=0; i<5; ++i ){
	if( i<note ){
    	    a[ i ].style.background = tt;
	    obj[ j ][ i ][ 1 ] = tt;
	}else{
    	    a[ i ].style.background = f;
	    obj[ j ][ i ][ 1 ] = f;
	}
    }
    
    if ( suma_glosow == 0 )
    {
	th.getElementsByTagName('p')[0].innerHTML = 'głosów: 0';
    } else {
	th.getElementsByTagName('p')[0].innerHTML = 'głosów: '+suma_glosow;
    }
    
    if( komunikat ){
	switch( komunikat ){
	    case 'oceniony':
                th.getElementsByTagName('p')[0].innerHTML = 'Możesz głosować raz na 24h.';
		break;
	    case 'dodano':
		th.getElementsByTagName('p')[0].innerHTML = 'Dziękujemy za oddany głos.';
	}
    }
}

function buildNote( th, j, id_prezentacji, id_wpisu, prefix_modulu,html_dir)
{
    obj[ j ] = Array( );
    http_request_prefix = false;

    $.ajax( 
    {
	url: '/source/ajax/oceny.php?id_prezentacji='+id_prezentacji+'&id_wpisu='+id_wpisu+'&prefix_modulu='+prefix_modulu,
	type: 'GET',
	dataType: 'xml',
	success: function( xml ){
    	    punkty = $(xml).find('punkty').text();
    	    glosy = $(xml).find('glosy').text();
	    note = Math.round( punkty/glosy );
	    element = th.getElementsByTagName( 'a' );
    	    for( i=0; i<5; ++i ){
	        element[i].setAttribute( 'name', 'note_' + j + '_' + i );
	        obj[ j ][ i ] = Array(element[i],'f',id_prezentacji,id_wpisu,prefix_modulu,th,html_dir);
	        addEvent( element[i], 'mouseover', onOver);
	        addEvent( element[i], 'mouseout', onOut);
	        element[i].onclick=onClick;
	    }
	    setNote( th, note, glosy, 0 );
	}
    } );
}

