function AdsLoader(placeHolderId, data, brownInterval)
{
	this.error = '';

	if (document.getElementById(placeHolderId))
	{
		var boxControl = document.getElementById("box_" + placeHolderId);
		if (boxControl) {
			boxControl.style.display = "";
		}

		this.placeHolderControl = document.getElementById(placeHolderId);
		this.blocks = data;
		this.adCount = this.blocks.length;
		this.randPrefix = Math.floor(Math.random()*100000) + 100000;
		this.mode = this.placeHolderControl.getAttribute("adMode");
		this.direction = this.placeHolderControl.getAttribute("adDirection");
		this.width = this.placeHolderControl.getAttribute("adWidth");
		this.height = this.placeHolderControl.getAttribute("adHeight");
		this.brownTimmer = 0;
		this.downloadCompleted = false;

		if (brownInterval) this.brownInterval = brownInterval;
		else this.brownInterval = 10000;
	}
	else	this.error = 'PLACE_HOLDER_NOT_FOUND';

	// methodes
	this.brownRunningZone = brownRunningZone;
	this.brownZone = brownZone;	
	this.doLoad = doLoad;
	this.fadeBlock = fadeBlock;
	this.swapBlocks = swapBlocks;
	this.genSquelette = genSquelette;
	this.rotateBlock = rotateBlock;
	this.onRotateBlock = onRotateBlock;
	this.onRotateZone = onRotateZone;
	this.fillAdPlace = fillAdPlace;
	this.downloadImage = downloadImage;
	this.swapfade = swapfade;
	this.brownBlock = brownBlock;
	this.stopBlocksSwapping = stopBlocksSwapping;
	this.genObjectCode = genObjectCode;

	// Dat gia tri vao block de su dung trong cac timmer
	for (var i=0; i<this.blocks.length; i++)
	{
		this.blocks[i].width = this.width;
		this.blocks[i].height = this.height;
		this.blocks[i].direction = this.direction;
	}
}

function doLoad()
{
	if (this.error)	return;

	var self = this;

	//this.brownZone();

	this.placeHolderControl.innerHTML = this.genSquelette();

	this.downloadImage();

	// RANDOM FIRST IMAGE WHEN REFRESH PAGE
	if (self.mode == 'brown') this.brownRunningZone();
	if (self.mode == 'brown' && this.brownInterval > 1)
	{
		window.clearInterval(self.brownTimmer);
		self.brownTimmer = window.setInterval(function() { self.brownRunningZone(); }, this.brownInterval);
	}

	this.onRotateZone();
	
}

function onRotateZone()
{
	for (var i=0; i<this.blocks.length; i++)
	{
		this.onRotateBlock(this.blocks[i], i);
	}
}

function onRotateBlock(block, block_index)
{
	if ((block.rotateInterval > 0) && (block.ads.length > 1))
	{
		block.img_control_id = '' + this.randPrefix + '_' + block_index;

		window.clearInterval(block.timmer);

		block.timmer = window.setInterval(function() { this.fadeBlock(block, block.img_control_id); },block.rotateInterval);
	}
}

function stopBlocksSwapping()
{
	for (var i=0; i<this.blocks.length; i++)
		window.clearInterval(this.blocks[i].timmer);
}

// brown blocks when they are running
function brownRunningZone()
{
	this.stopBlocksSwapping();

	for (var i=0; i<this.blocks.length-1; i++)
	{
			if (!this.blocks[i].dock || this.blocks[i].dock == false)
			{
				var rand = Math.floor(Math.random()*1000) % (this.blocks.length - i - 1) + i + 1;

				if (!this.blocks[rand].dock || this.blocks[rand].dock == false)
					this.swapBlocks(i, rand);
			}
	}
	this.onRotateZone();
}

// swap two blocks when they are running
function swapBlocks(index1, index2)
{	
	if (this.downloadCompleted == false) return;

	var temp = this.blocks[index1];
	this.blocks[index1] = this.blocks[index2];
	this.blocks[index2] = temp;
	this.fadeBlock(this.blocks[index1], this.randPrefix + '_' + index1);
	this.fadeBlock(this.blocks[index2], this.randPrefix + '_' + index2);
}

function brownZone()
{
	for (var i=0; i<this.blocks.length; i++)
	{
		this.brownBlock(this.blocks[i]);
	}
}

function brownBlock(block)
{
	if (block.ads.length < 2) return;
	var rand = Math.floor((block.ads.length-1)*Math.random()) + 1;
	var temp = block.ads[0];
	block.ads[0] = block.ads[rand];
	block.ads[rand] = temp;
}

function fadeBlock(adArray, img_control_id)
{
	if (this.downloadCompleted == false) return;

	adArray.clock = null;
	adArray.fade = true;
	adArray.count = 1;

	var imgControl = document.getElementById(img_control_id);
	this.rotateBlock(adArray);
	this.swapfade(img_control_id, adArray, '1', '');
}

function rotateBlock(adArray)
{
	if (adArray.rotateInterval <=0) return;

	var len = adArray.ads.length;

	if (len<=1) return;
	
	var item0 = adArray.ads[0];

	for (var i=0; i<len-1; i++ )
	{
		adArray.ads[i] = adArray.ads[i+1];
	}

	adArray.ads[len-1] = item0;
}

/*****************************************************************************
 List the images that need to be cached
*****************************************************************************/
function downloadImage()
{
	//cache the images
	this.blocks.cache = [];
	var imageIndex = 0;
	for(var i=0; i<this.adCount; i++)
	{
		this.blocks.cache[imageIndex] = new Image;
		this.blocks.cache[imageIndex].src = this.blocks[i].ads[0].logo;
		imageIndex++;

		// write img tag
		var control_id = this.randPrefix + '_' + i;
		this.fillAdPlace(control_id, this.blocks[i]);
	}

	for(var i=0; i<this.adCount; i++)
	{
		for (var j=1; j<this.blocks[i].ads.length; j++)
		{
			this.blocks.cache[imageIndex] = new Image;
			this.blocks.cache[imageIndex].src = this.blocks[i].ads[j].logo;
			imageIndex++;
		}
	}
	this.downloadCompleted = true;
}

function genSquelette()
{
	var squelette = '<table border="0" cellspacing="0" cellpadding="0">';

	for (var i=0; i<this.adCount; i++)
	{
		var linkId = this.randPrefix + '_' + i;

		// preview
		var placeHolder = '<table id="tbl_{temp_table_id}" cellspacing="0" cellpadding="0" border="0" width="{width}" height="{height}"><tr><td align="center"><a href="{ad_url}" id="{ad_link_id}">{ad_title}</a></td></tr></table>';
		placeHolder = placeHolder.replace("{ad_title}", this.blocks[i].ads[0].title);
		placeHolder = placeHolder.replace("{temp_table_id}", linkId);
		placeHolder = placeHolder.replace("{width}", this.width);
		placeHolder = placeHolder.replace("{height}", this.height);
		placeHolder = placeHolder.replace("{ad_url}", this.blocks[i].ads[0].link);

		// squelette
		var adLink = '<tr><td align="center" valign="middle" style="padding-bottom:2px;"><a href="{ad_url}" target="_blank" id="{ad_link_id}">{ad_place_holder}</a></td></tr>';
		adLink = adLink.replace("{ad_link_id}", linkId);
		adLink = adLink.replace("{ad_url}", this.blocks[i].ads[0].link);
		adLink = adLink.replace("{ad_place_holder}", placeHolder);
		squelette += adLink;
	}
	squelette +=	'</table>';

	return squelette;
}


function genObjectCode(control_id, block)
{
	var adHtml = '';

	var type = block.ads[0].type;

	if (typeof  type != 'undefined'  && type=='swf')
	{
		adHtml = '<embed src="{ad_src}" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" {ad_width} {ad_height}><BR />';
	}
	else
		adHtml = '<img {ad_width} {ad_height} src="{ad_src}" title="{ad_title}" />';

	adHtml = adHtml.replace(/{ad_title}/g, block.ads[0].title);	
	adHtml = adHtml.replace(/{ad_src}/g, block.ads[0].logo);
	adHtml = adHtml.replace(/{control_id}/g, control_id);

	if (block.direction == 'horizontal')
	{
		adHtml = adHtml.replace(/{ad_height}/g, 'height="'+block.height+'"');
		adHtml = adHtml.replace(/{ad_width}/g, 'width="'+block.width+'"');
	}
	else
	{
		adHtml = adHtml.replace(/{ad_height}/g, '');
		adHtml = adHtml.replace(/{ad_width}/g, 'width="'+block.width+'"');
	}
	return adHtml;
}

function fillAdPlace(control_id, block)
{
	var tempTable = document.getElementById('tbl_' + control_id);
	tempTable.parentNode.removeChild(tempTable);

	document.getElementById(control_id).innerHTML = this.genObjectCode(control_id, block);
}

function swapfade(img_control_id, adArray, resolution, alt)
{
	if(typeof alt != 'undefined' && alt != '')
	{
		adArray.obj.alt = alt;
	}
	var control = document.getElementById(img_control_id);
	control.innerHTML = this.genObjectCode(img_control_id, adArray);
	control.href = adArray.ads[0].link;
};
