jQuery.fn.popId = function() {
    return this.attr('id').split('-').slice(0,-1).join('-');
}
if (!Function.prototype.bind) {
    Function.prototype.bind = function(x) {
        var called = this;
        return function(a,b,c,d) {
            return called.call(x,a,b,c,d)
        }
    }
}

function musiboxsetup () {
    preLoadImages(['/static/img/square_blank.png', '/static/img/square_yellow.png',
            '/static/img/square_red.png', '/static/img/square_green.png', '/static/img/square_orange.png']);
    setupRatings();
    setupLoadVersion();
    setupDownloadLinks();
    setupMessageCount();
    setupPlayers();
}

function preLoadImages (images) {
    for (var x=0;x<images.length;x++) {
        new Image().src = images[x];
    }
}


/***************** Download ****/
function setupDownloadLinks() {
    $('.download-limitcount').each(setupDownloadLimitCount);
    $('.download-nolink').click(function() {
            alert("Votre abonnement BASIQUE ne vous autorise le téléchargement que d'une version par titre")
        });
}
function setupDownloadLimitCount() {
    var limitedDownLink = $(this).popId()+'-link';
    $('.'+limitedDownLink).click(downloadLinkOnClick(this));
    refreshDownloadLimitCount.call(this);
}
function refreshDownloadLimitCount() {
    var e=$(this);
    var idData = e.attr('id').split('-');
    idData.pop();
    var link=$('.'+idData.join('-')+'-link');
    var nolink=$('.'+idData.join('-')+'-nolink');
    var value = parseInt(e.attr('value'));
    if (value == 0) {
        link.hide();
        nolink.show();
    } else {
        link.show();
        nolink.hide();
    }
}
function downloadLinkOnClick(input) {
    return function() {
        $(input).attr('value',parseInt($(input).attr('value'))-1);
        refreshDownloadLimitCount.call(input);
    }
}

/******* message Count ****/
function setupMessageCount() {
    $('.messagecount').each(function () {
            var prefix= $(this).popId();
            var count = parseInt($('#'+prefix).attr('innerHTML'));
            messageCountUpdate(prefix,count);
        });
    $('#fpremaining-count').each(function() {
            $('div.player').click(messageCountDecrement.bind(this));
        });
    $('#dcver-count').each(function() {
            $('.download-link').click(messageCountDecrement.bind(this));
        });
}
function messageCountDecrement(ev){
    var count = parseInt($(this).attr('innerHTML'));
    if (count == 0) {
        ev && ev.stopImmediatePropagation();
        return false;
    }
    count -- ;
    $(this).attr('innerHTML',count);
    messageCountUpdate($(this).popId(),count);
    return true
}
function messageCountUpdate(prefix,count) {
    if (count == 0) {
        $('#'+prefix+'-0').show();
        $('#'+prefix+'-1').hide();
    } else if (count == 1) {
        $('#'+prefix+'-s').hide();
    } else {
        $('#'+prefix+'-0').hide();
    }
}
/****************************** Players ***************************/
function getUpdate(typ,code,l,swf) {
    //codes map:
    //0 stop/pause
    //1 loading
    //2 play
    //3 end
    if (typ == 'state' && code == 1) {
        $('.player embed, .player object')
        .filter(function() {return $(this).attr('id') != swf})
        .each(function () { this.sendEvent('stop'); });
    }
}

function setupPlayers() {
    $('div.player').each(function () {
	        var img = $('<img />',{'src':'/static/img/player.png'})
            .appendTo(this);
        }).one('click',expandPlayer);
}

function expandPlayer() {
    var div = $(this);
    var pid = div.attr('id');
    $('#'+pid+'-nouveau').hide();
    //div.innerHTML = "";
    var cryptUrl = div.attr('mp3');
    if (cryptUrl == '') { return false; }
    var mp3Url = '';
    for(var a=0;a<cryptUrl.length;a+=2) {
        mp3Url += String.fromCharCode(parseInt('0x'+cryptUrl.substr(a,2)));
    }
    div.empty();

    var width = 480; //div.clientWidth;
    var height = 20; //div.clientHeight;
    var swfid = pid + '-swf';

    var so = new SWFObject('/static/mediaplayer.swf',swfid,width,height,'8');
    so.addParam('allowscriptaccess','always');
    so.addParam('allowfullscreen','false');
    so.addVariable('width',width);
    so.addVariable('height',height);
    so.addVariable('file',mp3Url);
    so.addVariable('javascriptid',swfid);
    so.addVariable('enablejs','true');
    so.addVariable('autostart','true'); // change this for expand behaviour XXX  FIXME
    so.write(pid);

    return false;
}

/****************************** Ratings ***************************/
function setupRatings () {
    $('span.rating')
    .each(function() {
            var that=$(this);
	        that
            .data('avgrating',parseFloat(that.attr('avgrating')))
	        .data('usrrating',parseFloat(that.attr('usrrating')))
	        .data('starcolor',that.attr('starcolor'));

	        var eventHandlers = that.attr('clickable') &&
            { 'click' : ratingOnClick,
                'mouseover':ratingOnMouseOver,
                'mouseout' : ratingDefaultRepaint.bind(this)
            } || {} ;
            for (var j=1; j<=5; j++) {
	            $('<img />',{'src':'/static/img/square_blank.png','alt':'pic'+j})
                .bind(eventHandlers)
                .appendTo(that);
            }
	    })
    .each(preferedUpdateRating)
    .each(ratingDefaultRepaint);

    $('img.rating-prefered')
    .click(preferedOnClick)
    .mouseover(preferedOnMouseOver)
    .mouseout(preferedUpdate);
}

function ratingDefaultRepaint() {
    ratingRepaint.call(this,$(this).data('usrrating'),$(this).data('starcolor'), 'blank');
}

function ratingRepaint(stars, withColor, withoutColor) {
    var squareUrl = '/static/img/square_';
	$(this).children('img').slice(0,stars).attr('src',squareUrl + withColor + '.png');
	$(this).children('img').slice(stars).attr('src',squareUrl + withoutColor + '.png');
}

function ratingOnMouseOver() {
	ratingRepaint.call($(this).parent(), $(this).index()+1, 'green','blank');
}

function Blinker(rating) {
    this.rating = $(rating);
    this.count = 0;
    this.blink =  function() {
        if (this.count<6) {
            ratingRepaint.call(this.rating, this.count, 'green', 'blank');
        } else {
            ratingRepaint.call(this.rating, this.count-6, 'blank', 'green');
        }
        this.count++;
        if (this.count<12) {
            setTimeout(this.blink, 100);
        } else {
            ratingDefaultRepaint.call(this.rating);
        }
    };
}

function ratingOnClick() {
    var rating =$(this).parent('.rating');
    var stars = $(this).index() +1;
    var trackdata = rating.attr('id').split('-');
	var ratingtype = trackdata.pop();
    var mp3PK = trackdata.pop();

	new Blinker(this).blink();
	$.get('/filepublishing/rating/'+mp3PK, ratingtype+'='+stars+'&x=',
            function (data) { rating.data('avgrating',data['avg'+ratingtype]) }, 'json');
	rating.data('usrrating',stars);
	if (!rating.data('avgrating')) {
	    rating.data('avgrating',stars);
	}
}
/*********** prefered *********/
function preferedOnMouseOver() {
    var radioIdData = $(this).attr('src').split('.');
    var filetype = radioIdData.pop();
    var color = radioIdData.pop() == 'y' && 'w' || 'y';
    radioIdData.push(color);
    radioIdData.push(filetype);
    $(this).attr('src',radioIdData.join('.'))
}
function preferedOnClick() {
    var radioData = $(this).attr('id').split('-');
    var fmPK = radioData.pop();
    var mp3PK = radioData[radioData.length-1];
    var trackId = radioData.join('-');
	$.get('/filepublishing/rating/'+mp3PK, { 'prefered' : fmPK },
        function(data) {
                if (!data.prefered) {
                    data.prefered = 1 ;
                }
                $('#'+trackId+'-prefered').attr('value',data.prefered);
                for(mp3PK in data.scores) {
                    $('#'+trackId+'-'+fmPK+'-score').attr('value',data.scores[fmPK]);
                }
                preferedUpdateRating.call($('#'+trackId+'-prefered'));
            },
            'json' );
}
function preferedUpdate() {
    var trackId = $(this).attr('id');
    var userPrefered = $('#'+trackId+'-prefered').attr('value');
    var scoreCount = $('.'+trackId+'-score').length;
    ratingUpdateStarFromGroup.call($(this),userPrefered,scoreCount);
}
function preferedUpdateRating() {
    var trackId = $(this).popId();
    var scoreCount = $('.'+trackId+'-score').length;
    var userPrefered = $('#'+trackId+'-prefered').attr('value');
    $('img.'+trackId+'-stars').each(function() {
            ratingUpdateStarFromGroup.call($(this),userPrefered,scoreCount);
        });
}
function ratingUpdateStarFromGroup(userPrefered,scoreCount) {
    var fmId = this.attr('id').split('-').pop();
    var score = parseInt($('#'+this.attr('id')+'-score').attr('value'));
    var filename = '/static/img/star.';
    if (!userPrefered) {
        filename += 'e';
    } else if (scoreCount == 1 || score >= (3/2*100/(scoreCount))) {
        filename += '3';
    } else if (score >= (1/3*100/(scoreCount-1))) {
        filename += '2';
    } else {
        filename += '1';
    }
    filename += '.'
    if (fmId == userPrefered ){
        filename += 'y'
    } else {
        filename += 'w' ;
    }
    filename += '.png' ;
    this.attr('src',filename);
}

/***** reduced version ***/

    function setupLoadVersion() {
        var titresSize = $('#titres-size');
        if (titresSize.attr('value') <= 1 ) {
            return ;
        }
        $('.titre-block').each(function() {
                var id = $(this).attr('id');
                $('#'+id+'-full').hide();
                $('.version-'+id).hide();
            });
    }

