// =============================== ADS        =================================//
var stack=[];
var iterator=0;

jQuery(window).load(function(){
    //Loading after everything is loaded
    if (typeof images != "undefined") {
        jQuery.each(images,function(n,obj){
            loadFromObj(jQuery('.blocPublicitaire'),obj);
        });
    }
});
function addToStack(ob){
    stack.push(ob);
    if(stack.length==images.length){
        stack.sort(function(a, b) {
            var compA = $(a).data('obj').order;
            var compB = $(b).data('obj').order;
            return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
        });
        fullyLoaded();
    }
}
function fullyLoaded(){
    if (typeof startId != "undefined") {
        $(stack).each(function(n,obj){
            var idObj=obj.data('obj').id;
            if(idObj==startId){
                iterator=n;
                nextIter();
            }
        })
    }
    var ob=stack[iterator];
    ob.addClass('active')
    .fadeIn('slow').delay((ob.data('obj').time * 1000)).removeClass('active').fadeOut('Fast',function(){
        skipToNext();
    });
}
function skipToNext(){
    var ob=stack[iterator];
    var rnd = Math.random();
    $.get('showed.php?id=' + (ob.data('obj').id) + '&ran=' + rnd);
    nextIter();
    var ob=stack[iterator];
    ob.addClass('active')
    .fadeIn('slow').delay(ob.data('obj').time * 1000).removeClass('active').fadeOut('Fast',function(){
        skipToNext();
    });
//.removeClass('active')
}
function nextIter(){
    iterator++;
    if(iterator>=stack.length){
        iterator=0;
    }
}
function loadFromObj(dest,obj){
    var img = new Image();
    $(img)
    .data('obj',obj)
    .addClass('imgNo'+obj.id)
    .load(function () {
        // set the image hidden by default
        $(this).hide();
        // with the holding div #loader, apply:
        $(dest)
        // remove the loading class (so no background spinner),
        .removeClass('loading')
        // then insert our image
        .append(this);
        addToStack($(img));
    })
    .error(function (e) {
        alert(e);
        return false;
    // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', obj.url);
}
// =============================== JCAROUSEL================================//

