
//var xmlHttp = $.get(serverUrl, data, callback, type);
//type: "xml", "html", "script", "json", "jsonp", or "text".

var adIndex = 0;
var adArray = [];

$(document).ready(function(){
    showAds(-1, -1);
});

function showAds(index, count){

    index = ( index == null ) ? 0  : index;
    count = ( count == null ) ? 10 : count;

    var bannerAd = $("#Ads #Ad");
    bannerAd.html("");

    var seqId = Math.floor(Math.random()*1000);

    var serverUrl = "./ajax.php";

    var data      = "page=get_ads"
                  + "&index="+index
                  + "&count="+count
                  + "&seqId="+seqId;

    var xmlHttp = $.get(serverUrl, data, onLoadAds, "json");

    $( "#ads_loading" ).show();
}

function onLoadAds( outputArray ){


    var ads         = outputArray.ads;
    var resultCount = outputArray.resultCount;
    var index       = outputArray.index;

    var count      = 10;
    var groupCount = 100;

    //alert( ads.length );

    $( "#ads_loading" ).hide();

    var output = '';

    displayAds(ads);

}

function displayAds(ads){

    adIndex = 0;
    adArray = ads;

    showNextImage();

    setInterval(changeAdImage, 10000);
}

function changeAdImage(){

    hideCurrentImage();

    //alert('change ok');
}

function hideCurrentImage(){

    $("#Ads #Ad").fadeTo("slow", 0.1, showNextImage);

}

function showNextImage(){

    var ad = adArray[adIndex];

    var adDiv  = $("#Ads #Ad");

    $("#ad_loading").fadeTo("slow", 1).show();

    var htmlText = '<a href="'+ad.link+'">'
                    + '<img id="imgAd" src="uploads/ads/'+ad.image+'" width="315" height="315" border="0" />'
                 + '</a>';

    adDiv.html( htmlText );

    $("#Ads #Ad").fadeTo("slow", 1);
    $("#ad_loading").fadeTo("slow", 0.1).hide();

    adDiv.load(function () {
        $("#Ads #Ad").show();
        $("#ad_loading").fadeTo("slow", 0.1).hide();
    });

    adIndex++;

    if( adIndex >= adArray.length ){
        adIndex = 0;
    }
}
