var cdnIndex = 0;
var cdnpixel_timeout  = null;

function replaceCDN(fileURL) {
	if (cdnIndex>0 && CDN_LIST.length>0) {
		var linkList = document.getElementsByTagName("a");
		var currentURL = CDN_LIST[cdnIndex-1].fileURL
		var doTrack = true;
		for (var i=0, c = linkList.length; i < c; i++) {
			if (linkList[i].getAttribute("href")==currentURL) {
			    if(doTrack){
			        trackChangURL();
			        doTrack = false;
			    }
				linkList[i].setAttribute("href", fileURL);
			}
		}
	}
}

function nextCDN() {
	cdnIndex++;
	if (cdnIndex<CDN_LIST.length) {
		replaceCDN(CDN_LIST[cdnIndex].fileURL);
		checkCDN();
	}			
}
function checkCDN() {
    
	var pixel_img = new Image();
	pixel_img.onload = function(e) {
		if (pixel_img.failed==null) {
		clearTimeout(cdnpixel_timeout);
		}
		
	}

	pixel_img.onerror = function(e) {		
		clearTimeout(cdnpixel_timeout);
		nextCDN();
	}
    if (CDN_LIST.length>0)
    {
	pixel_img.src = CDN_LIST[cdnIndex].pixel;	
	}
	cdnpixel_timeout = setTimeout(function() {
		pixel_img.failed = true;
		nextCDN();
	}, CDN_RESPONSE_TIME_OUT);
}

function _onLoad() {
	checkCDN();
}

if (window.attachEvent) {
  window.attachEvent( "onload", _onLoad );
} else {
  window.addEventListener( "load", _onLoad, false );
}
