/****************************************************************/
/* BEGIN of VnnAdsLoader Class by Thanh Bon, 01.2007, VASC                    */
/* http://javascriptcompressor.com/														   */
/****************************************************************/
function VnnAdsLoader(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.classe = this.placeHolderControl.getAttribute("adClass");
		this.showTitle = this.placeHolderControl.getAttribute("adShowTitle");

		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;

	// animation methods
	this.JSFX_KeepInView = JSFX_KeepInView;
	// 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].classe = this.classe;
		this.blocks[i].direction = this.direction;
	}
}

/*****************************************************************************
 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 doLoad()
{
	if (this.error)	return;

	var self = this;

	this.placeHolderControl.innerHTML = this.genSquelette();

	this.downloadImage();

	// RANDOM FIRST IMAGE WHEN REFRESH PAGE
	if (self.mode == 'brown') {
		this.brownRunningZone(); // ramdom zone
	}
	//this.brownZone(); // random block's ads

	if (self.mode == 'brown' && this.brownInterval > 1)
	{
		window.clearInterval(self.brownTimmer);
		self.brownTimmer = window.setInterval(function() { self.brownRunningZone(); }, this.brownInterval);
	}

	this.onRotateZone();

}
/* Keep In View (c) JavaScript-FX. (www.javascript-fx.com)          */
function JSFX_KeepInView(id){
	var getPageY=function(el){return(el==null)?0:el.offsetTop+getPageY(el.offsetParent);};
	var getScrollTop=function(){return document.body.scrollTop||document.documentElement.scrollTop};
	var el=document.getElementById(id);if(el==null)return;
	if(el.style.position=="absolute"){el.startPageTop=-el.offsetTop;el.currentX=el.offsetLeft;el.currentY=el.offsetTop;}
	else{el.style.position="relative";el.startPageTop=getPageY(el);el.currentX=el.currentY=0;};
	el.floatInView=function(){
		var targetY=(getScrollTop()>this.startPageTop)?getScrollTop()-this.startPageTop:0;
		this.currentY+=(targetY-this.currentY)/4;this.style.top=this.currentY+"px";};
		setInterval('document.getElementById("'+id+'").floatInView()',40);
};

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;
				var rand = Math.floor(Math.random()*this.blocks.length);

				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()
{
	// this.stopBlocksSwapping(); khong can goi ham nay

	for (var i=0; i<this.blocks.length; i++)
	{
		//this.brownBlock(this.blocks[i]);
		this.brownBlock(i);
	}
	//this.onRotateZone(); Neu bat dong thu nhat thi phai bat dong nay
}


function brownBlock(i)
{
	if (this.blocks[i].ads.length < 2) return;
	var rand = Math.floor(Math.random()*(this.blocks[i].ads.length-1)) + 1;
	var temp = this.blocks[i].ads[0];

	swapBlocks(0, rand);
}

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;
}

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}" style="background-color: #dedede; border: 3px solid #eee;" cellspacing="0" cellpadding="0" width="{width}px" height="{height}px"><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==null)?this.blocks[i].ads[0].width:this.width);
		placeHolder = placeHolder.replace("{height}", (this.height==null)?this.blocks[i].ads[0].height:this.height);
		placeHolder = placeHolder.replace("{ad_url}", this.blocks[i].ads[0].link);

		var adLink = '<tr><td align="center" valign="middle" id="{ad_link_id}">{ad_place_holder}</td></tr>';
		adLink = adLink.replace("{ad_link_id}", linkId);
		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" wmode="transparent" type="application/x-shockwave-flash" {ad_width} {ad_height}><BR />';
	}
	else if (typeof  type != 'undefined'  && (type=='script' || type=='html'))
	{
		adHtml = block.ads[0].content;
	}
	else
		adHtml = '<a  href="javascript:void(1);" onclick="javascript:adClick(\'{ad_stats_url}\', \'{ad_url}\');"><img class="{ad_class}" alt="{ad_alt}" {ad_title} {ad_width} {ad_height} src="{ad_src}" /></a>';

	adHtml = adHtml.replace(/{ad_src}/g, block.ads[0].logo);
	adHtml = adHtml.replace(/{ad_class}/g, block.classe);
	adHtml = adHtml.replace("{ad_url}", block.ads[0].link);
	adHtml = adHtml.replace("{ad_stats_url}", block.ads[0].stats);
	adHtml = adHtml.replace("{ad_alt}", block.ads[0].title);

	if (this.showTitle && this.showTitle == 'on')
	{
		adHtml = adHtml.replace("{ad_title}", 'title="' + block.ads[0].title + '"');
	}
	else
	{
		adHtml = adHtml.replace("{ad_title}", "");
	}

	if (block.direction == 'horizontal')
	{
		adHtml = adHtml.replace(/{ad_height}/g, 'height="'+((block.height==null)?block.ads[0].height:block.height)+'"');
		adHtml = adHtml.replace(/{ad_width}/g, 'width="'+((block.width==null)?block.ads[0].width:block.width)+'"');
	}
	else
	{
		adHtml = adHtml.replace(/{ad_width}/g, 'width="'+((block.width==null)?block.ads[0].width:block.width)+'"');
		if (typeof  type != 'undefined'  && type=='swf')
			adHtml = adHtml.replace(/{ad_height}/g, 'height="'+((block.height==null)?block.ads[0].height:block.height)+'"');
		else
			adHtml = adHtml.replace(/{ad_height}/g, '');
	}

	return adHtml;
}


// Support Script Item:: BEGIN
function appendChild(node, text) {
  if (null == node.canHaveChildren || node.canHaveChildren) {
    node.appendChild(document.createTextNode(text));
  } else {
    node.text = text;
  }
}

function showScript(code) {
  document.writeln(code);
}
// Support Script Item:: END

function fillAdPlace(control_id, block)
{
	var tempTable = document.getElementById('tbl_' + control_id);
	tempTable.parentNode.removeChild(tempTable);

    // Support Script Item:: BEGIN
	var type = block.ads[0].type;
	var code = block.ads[0].content;
    if (typeof  type != 'undefined'  && type=='script') {
        var script = document.createElement("script");
        script.setAttribute('type','text/javascript');
        appendChild(script, "showScript('"+code+"');");
        document.getElementById(control_id).appendChild(script);
    }
    // Support Script Item:: END
    else {
        document.getElementById(control_id).innerHTML = this.genObjectCode(control_id, block);
    }
}

// DOM scripting by brothercake -- http://www.brothercake.com/
function swapfade(img_control_id, adArray, resolution, alt)
{
	if(typeof alt != 'undefined' && alt != '')
	{
		adArray.obj.alt = alt;
	}
	var control = document.getElementById(img_control_id);
    // Support Script Item:: BEGIN
	var type = adArray.ads[0].type;
	var code = adArray.ads[0].content;
    if (typeof  type != 'undefined'  && type=='script') {
        var script = document.createElement("script");
        script.setAttribute('type','text/javascript');
        appendChild(script, "showScript('"+code+"');");
        control.appendChild(script);
    }
    // Support Script Item:: END
    else {
        control.innerHTML = this.genObjectCode(img_control_id, adArray);
    }
};


function adClick(stats_url, ad_url)
{
	var r = "http://sime.vn";

	if (document.referrer) r = escape(document.referrer);
	try {
		if (ad_url != '#') {
			newwin = window.open(ad_url, '_blank');
		}
		element = document.createElement('div');
		element.innerHTML = '<img id="stat_img" style="display: none;" alt="" src="' +stats_url.replace("{REFERRER}", r) + '" width="0" height="0"/>';
		document.body.appendChild(element);
	}
	catch (e) {}

    return false;
}

//////////////////////////////////////////////////////////////////////////////

function VsAdBlockHandler(block_id)
{
    this.block_id = block_id;
    this.blockObject = document.getElementById(this.block_id);

    this.interval = this.blockObject.getAttribute('adInterval')?
                    this.blockObject.getAttribute('adInterval'):0;

    this.displayOrder = this.blockObject.getAttribute('adDisplayOrder')?
                        this.blockObject.getAttribute('adDisplayOrder'):'random';

    // functions prototype
    this.showNextItem = showNextItem;
    this.createTimer = createTimer;
    this.removeEmptyItem = removeEmptyItem;
	this.randomOrderItems = randomOrderItems;
	this.adItemCpm = adItemCpm;

    // remove empty item
    this.removeEmptyItem();

    this.itemList = getElementsByClassName(this.block_id + 'i');

    // find first item displayed
	this.randomOrderItems(); // init with random order
    this.displayedItemIndex = -1;    // ordered
    this.showNextItem(); // show first time

    if (this.itemList.length>1 && this.interval>=1000)
        this.createTimer();

    // Get the first random item
	// Call this function after the page loaded
    function randomOrderItems() {
        for (var i=0; i<this.itemList.length; i++) {
            var randomItem = Math.floor(Math.random()*(this.itemList.length-i))+i;
            var handler = this.itemList[i].handler;
            var html = this.itemList[i].innerHTML;
            this.itemList[i].handler = this.itemList[randomItem].handler;
            this.itemList[i].innerHTML = this.itemList[randomItem].innerHTML;
            this.itemList[randomItem].handler = handler;
            this.itemList[randomItem].innerHTML = html;
        }
    }

    // Get the next item to show on the top of block
	// random mode: next item is random
	// ordered mode: next item is the next item of current top item. the top item may be random at the begining
    function showNextItem() {
        var nextItemIndex = Math.floor(Math.random()*this.itemList.length);
        if (this.displayOrder == 'random') {
            while (nextItemIndex == this.displayedItemIndex) {
                nextItemIndex = Math.floor(Math.random()*this.itemList.length);
            }
        }
        else {
            nextItemIndex = (this.displayedItemIndex >= this.itemList.length-1)?
                            0:this.displayedItemIndex+1;
        }


		if (this.displayedItemIndex > -1 && this.itemList[this.displayedItemIndex] != 'undefined' && this.itemList[this.displayedItemIndex]) 
			document.getElementById(this.itemList[this.displayedItemIndex].id).style.display = 'none';

        if (this.itemList[nextItemIndex]) {
			document.getElementById(this.itemList[nextItemIndex].id).style.display = 'block';
			this.adItemCpm(this.itemList[nextItemIndex]);
		};
        this.displayedItemIndex = nextItemIndex;
    };

	function adItemCpm(item)
	{
		var r = "http://truelife.vn";
		if (document.referrer) r = escape(document.referrer);

		var cpmObject = document.getElementById("cpm_" + item.id);
		if (cpmObject != 'undefined' && cpmObject) {
			document.body.removeChild(cpmObject);
		}

		try {
			element = document.createElement('div');
			element.id = "cpm_" +item.id;
			var img_url =  item.getAttribute("cpm_url") + '&'+ Math.random(); 
			element.innerHTML = '<img style="display: none;" alt="Generated by CPM stats" src="' +img_url.replace("{REFERRER}", r) + '" width="0" height="0"/>';
			document.body.appendChild(element);
		}
		catch (e) {}

		return false;
	}

    // init timer
    function createTimer() {
        var self = this;
        window.clearInterval(self.timer);
        this.timer = window.setInterval(
            function() {
                self.showNextItem();
            },
            self.interval
        );
    };

    function removeEmptyItem() {
        var itemList = getElementsByClassName(this.block_id + 'i');
		
        for (var i=0; i<itemList.length; i++) {
          if   (itemList[i].getElementsByTagName('img').length +
                itemList[i].getElementsByTagName('embed').length +
                itemList[i].getElementsByTagName('iframe').length +
                itemList[i].getElementsByTagName('object').length == 0) {
               this.blockObject.removeChild(itemList[i]);
            }
        }
    }
};
//////////////////////////////////////////////////////////////////////////////

var VsAdZoneHandler = function(zone_id) {
    this.zone_id = zone_id;
    this.zoneObject = document.getElementById(this.zone_id);

	// has no data
	if (!vsAdData[this.zoneObject.getAttribute("name")]) {
		return;
	}

	// Functions prototype
    this.showBlocksRandom = showBlocksRandom;
    this.createTimer = createTimer;
	this.JSFX_KeepInView = JSFX_KeepInView;	// animation method
	
    this.interval = this.zoneObject.getAttribute('adInterval')?
                    this.zoneObject.getAttribute('adInterval'):0;

	this.displayOrder = this.zoneObject.getAttribute('adDisplayOrder')?
                        this.zoneObject.getAttribute('adDisplayOrder'):'random';

	this.blockList = getElementsByClassName(this.zone_id + 'b');

    for (var i=0; i<this.blockList.length; i++) {
        this.blockList[i].handler = new VsAdBlockHandler(this.blockList[i].id);
    }

    // show blocks at the first time
    if (this.displayOrder == 'random')
        this.showBlocksRandom();

    // set visible ad zone border
    var i = 0;
    var borderObject = this.zoneObject.parentNode;
	while (i < 10 && (borderObject.getAttribute("name") !== null || borderObject.getAttribute("name") !== undefined) && borderObject.getAttribute("name") != 'vsad_border') {
		borderObject = borderObject.parentNode;
		i=i+1;
	}

	// set border object id
	if (borderObject) {
		borderObject.setAttribute("id", "border_of_" + this.zone_id);
	}


	this.JSFX_KeepInView(this.zoneObject.getAttribute('name'));


    if (borderObject && borderObject != this.zoneObject)
		borderObject.style.display = 'block';

    // start ad show
    this.createTimer();

    // Functions Body.
    function showBlocksRandom() {
        for (var i=0; i<this.blockList.length; i++) {
            var randomBlock = Math.floor(Math.random()*(this.blockList.length-i))+i;
            var handler = this.blockList[i].handler;
            var html = this.blockList[i].innerHTML;
            this.blockList[i].handler = this.blockList[randomBlock].handler;
            this.blockList[i].innerHTML = this.blockList[randomBlock].innerHTML;
            this.blockList[randomBlock].handler = handler;
            this.blockList[randomBlock].innerHTML = html;
        }
    }

    function createTimer() {
        var self = this;
        window.clearInterval(self.timer);
        if (self.blockList.length>1 && self.interval>=1000)
        this.timer = window.setInterval(
            function() {
                self.showBlocksRandom();
            },
            self.interval
        );
    };
}

// place the call to this function in the box ad;
function genAdZoneHtml(zone_name) {
	try {
		var html = "";
		var zonePattern =  '<div id="{zone_id}" name="{zone_name}" class="adz" align="center" adDisplayOrder="{display_order}" adInterval="{interval}">{blocks_html}</div>';

		var zone = vsAdData[zone_name];
		if (!zone) {
			return;
		}

		for (var i = 0; i<zone.blocks.length; i++)
		{
			html = html + genAdBlockHtml(zone.blocks[i]);
		}
		html = zonePattern.replace("{blocks_html}", html);

		html =  html.replace(/{interval}/gi, zone.interval)
					.replace(/{display_order}/gi, zone.displayOrder)
					.replace(/{zone_name}/gi, zone_name)
					.replace(/{zone_id}/gi, zone.id);
		document.write(html);
	}
	catch (e) {}
}

function genAdBlockHtml(block, zone_id) {
	var html = "";
	var blockPattern=  '<div id="{zone_id}{block_id}" class="{zone_id}b" align="center" adDisplayOrder="{display_order}" adInterval="{interval}">{items_html}</div>';
	for (var i = 0; i< block.items.length; i++) {
		html = html + genAdItemHtml(block.items[i]);
	}
	html = blockPattern.replace("{items_html}", html);

	html = html.replace(/{interval}/gi, block.interval)
					   .replace(/{display_order}/gi, block.displayOrder)
					   .replace(/{block_id}/gi, block.id);

	return html;
}

function genAdItemHtml(item, block_id, zone_id) {
	var html = "";
	var itemPattern =  '<div id="{zone_id}{block_id}{item_id}" class="{zone_id}{block_id}i"  style="display: none;" cpm_url="{cpm_url}">{item_code}</div>';

	if (item.type == 'image')  html = genAdImageItemHtml(item);
	else if (item.type == 'flash') html = genAdFlashItemHtml(item);
	else if (item.type == 'script') html = genAdScriptItemHtml(item);
	else if (item.type == 'text' ) html = genAdScriptItemHtml(item);
	html = itemPattern.replace("{item_code}", html);

	return html.replace("{item_id}", item.id)
					.replace("{cpm_url}", item.cpm_stats_url);

}

function genAdImageItemHtml(item) {
	var imageItemPattern = '<a href="javascript:void(1);" onclick="javascript:adClick(\'{ad_stats_url}\', \'{ad_url}\');"><img src="{ad_src}" alt="" /></a>';
	imageItemPattern = imageItemPattern.replace(/{ad_src}/g, item.logo);
	imageItemPattern = imageItemPattern.replace("{ad_url}", item.link);
	imageItemPattern = imageItemPattern.replace("{ad_stats_url}", item.cpc_stats_url);
	return imageItemPattern.replace("{ad_alt}", item.title);
}

function genAdFlashItemHtml(item) {
		var flashItemPattern = '<span onmousedown="javascript:adClick(\'{ad_stats_url}\', \'{ad_url}\');"><embed src="{ad_src}" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" type="application/x-shockwave-flash" width="{ad_width}" height="{ad_height}" /></span>';
	flashItemPattern = flashItemPattern.replace(/{ad_src}/g, item.logo);
	flashItemPattern = flashItemPattern.replace("{ad_url}", item.link);
	flashItemPattern = flashItemPattern.replace("{ad_stats_url}", item.cpc_stats_url);
	flashItemPattern = flashItemPattern.replace("{ad_width}", item.width);
	flashItemPattern = flashItemPattern.replace("{ad_height}", item.height);
	return flashItemPattern.replace("{ad_alt}", item.title);
}

function genAdScriptItemHtml(item) {
	return item.code;
}


function load_ads() {
    // get zone list
    // - create Object to handle zone business
    // - start zone's handler
		var zoneList = getElementsByClassName('adz');
		for (var i=0; i<zoneList.length; i++) {
			zoneList[i].handler =  new VsAdZoneHandler(zoneList[i].id);
		}
}


function getElementsByClassName(classname, node)  {
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
		if(re.test(els[i].className))a.push(els[i]);
	return a;
}


