/**
 * Displays advertisements that streams live from the Server
 * 
 * @author Elie Zedeck RANDRIAMIANDRIRAY <rez@eliezedeck.com>
 */

var adPending = false;
var adSwitchable = true;

function displayAdvertisement(pageLocation)
{
	if(adPending == false && adSwitchable == true)
	{
		// Craft the request URL
		var url = "http://" + window.location.host + "/cgi-bin/ajax_ads_server/" + pageLocation;

    // declare that an Advert fetch is pending
    adPending = true;

		new Ajax.Request(url,
		{
			method: 'get', asynchronous: true,
			onSuccess: function(transport)
			{
				adPending = false;

				// get the JSON data
				var jsonData = transport.responseText.evalJSON();

        // check for valid Advert data
        if(transport.responseText.length < 1 || typeof(jsonData.d) == 'undefined' || typeof(jsonData.ad) == 'undefined')
        {
          $('adWrapper').update('&nbsp;');
        }
        else
        {
        	// update the Advertisement box
        	$('adWrapper').update(jsonData.ad);

        	// display effect
	        new Effect.Opacity('adWrapper', { from: 1.0, to: 0.5, duration: 0.5, fps: 15 });
	        setTimeout(function() { new Effect.Opacity('adWrapper', { from: 0.5, to: 1.0, duration: 0.5, fps: 15 }); }, 500);

	        // schedule for the next update
	        adSwitchable = false;
	        setTimeout(function() { adSwitchable = true; }, jsonData.d * 1000);
        }
			},
			onFailure: function()
			{
				// reset to allow incoming Advertisement
				adPending = false;
				adSwitchable = true;
			}
		}
		);
	}
}
