function getSiteDomain(){
	var domain = document.location.hostname;
	var port;
	
	if(document.location.port !== ""){
		port = ":" + document.location.port;
		}
	else{
		port = "";
		}
	return "http://" + domain + port; 
}

function fixProxyUrl(proxyurl, prefix){
    if (!prefix) prefix = "www";
    var spliturl = proxyurl.split("\/")
    try{
        var splitdomain = spliturl[2].split("\.");

        if (splitdomain.length == 2)
            spliturl[2] = prefix + "." + splitdomain.join("\.");
    }
    catch(err){
        return null;
    }

    return spliturl.join("\/");
}

AdManager = function(adserver_url) {
	this.ad_url = fixProxyUrl(adserver_url);
        //this.ad_url = getSiteDomain() + "/adproxy/?";
	this.ad_tags = {};
	this.ad_table = { 
		'preroll'  : "empty",
		'overlay'  : "empty",
		'postroll' : "empty"
	}; 
};

AdManager.prototype = {
	queueAdTag: function(adtag) {
		var ad_type = parseQueryString(adtag).adtype.toLowerCase();
		this.ad_tags[ad_type] = adtag;
	},
	
	// Deprecated:  using queueAdTag in newer versions
	setAdTag: function(adtag) {
		var ad_type = parseQueryString(adtag).adtype.toLowerCase();
		this.ad_tags[ad_type] = adtag;
		this.loadAds(ad_type);
	},
	
	setSite: function(site){
		this.site = site;
		//alert(this.site);
	},
	
	getAdTags: function (needle){
	  var  my_array = document.getElementsByTagName("*");
	  var  retvalue = [];
	  var  i;
	  var  j;
	  for (i = 0, j = 0; i < my_array.length; i++){
			var c = " " + my_array[i].id + " ";
			if (c.indexOf(" " + needle + " ") !== -1){
			  retvalue[j++] = my_array[i];
			  }
	  	}
	  return retvalue;
	},
	
	fetch_url: function(url) {
		var page_request = false;
		if (window.XMLHttpRequest){ // if Mozilla, Safari etc
			//netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead");
			page_request = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{ // if IE
			try {
				page_request = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e){
				try{
					page_request = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (err){}
			 }
		}
		else{
			return false;
		}
		page_request.open("GET", url, false); //get page synchronously
		page_request.send(null);
		if (window.location.href.indexOf("http")==-1 || page_request.status==200){
		    return( page_request.responseText) ;
		}
		return( "NO PAGE at " + url  ) ;
	},
	
	loadSyncAd: function(targets) {
		var divnid = this.site + "_BIGBOX_1";
		var proxyurl = this.ad_url + targets;
		try{
			thead = this.fetch_url( proxyurl );
			document.getElementById( divnid ).innerHTML = thead;
		}catch(eror){
			//alert("Admanager error: "+eror);
		}
	},
	
	//	Deprecated:  We are loading ad tag data now through ActionScript only
	//	right before we need it.
	
	loadAds: function (type) {
		var self = this;
		var req = loadJSONDoc( self.ad_url + self.ad_tags[type] );
		var parseAdResponse = function(response) {
    		if(response)
			{
    		    self.ad_table[type] = response;
				var sync_ad = self.ad_table[type].sync_ad;
				self.myad = sync_ad; 
				ad_targets = sync_ad; //sync_ad.split('/js.ng/')[1];
				
				//ad_targets = ad_targets.replace('site=ECP','site=TEST');
				
				//alert(ad_targets);
				ad_url = self.ad_url + ad_targets ;
				//alert(ad_url);
				if( sync_ad )
				{
					var divnid = self.site + "_BIGBOX_1";					
					try{		
						thead = self.fetch_url( ad_url );
						document.getElementById( divnid ).innerHTML = thead ;
						
					}catch(eror){
						//alert("Admanager error: "+eror);
					}
				}
			}
    		else{
    		    self.ad_table[type] = null;
			}
		};
		req.addCallback( parseAdResponse );
		req.addErrback( function (err) {
			return;
		});
	},
	
	getAdTag: function (type) {
		var ad_info = this.ad_url + this.ad_tags[type];
		//this.ad_tags[type] = null;
		return ad_info;
	},
	
	//  Deprecated:  using getAdTag instead, since we aren't storing the actual
	//	ad data in javascript anymore.
	getAd: function (type) {
		var ad_info = this.ad_table[type];
		this.ad_table[type] = null;
		return ad_info;
	},
	
	getElementsByClass: function (needle){
	  var  my_array = document.getElementsByTagName("*");
	  var  retvalue = [];
	  var  i;
	  var  j;
	  for (i = 0, j = 0; i < my_array.length; i++){
			var c = " " + my_array[i].className + " ";
			if (c.indexOf(" " + needle + " ") !== -1){
			  retvalue[j++] = my_array[i];
			  }
	  	}
	  return retvalue;
	},

	
	
	cycle_ads: function (path){
		//alert("still getting called");
		//alert(path);
		targets = path.split( '/' ) ;
		new_ad_targets = "&target=" + targets.join( "&target=" ) ;
		ad_nodes = this.getElementsByClass( 'adtag' ) ;
		var idx = 0 ;
		for( idx = 0; idx < ad_nodes.length; idx ++ )
			{
			ad_node = ad_nodes[ idx ] ;
			site = ad_node.id.split( '_' ) [0] ;
			ad_type = ad_node.id.split( '_' ) [1] ;
			ad_pos = ad_node.id.split( '_' ) [2] ;
			//this.ad_url = "http://" + this.domain + this.port + "/adproxy/?";
			new_ad_url = getSiteDomain() + "/adproxy/" + "?site=" + site + "&adtype=" + ad_type + "&PagePos=" + ad_pos + new_ad_targets;
			new_ad = this.fetch_url( new_ad_url ) ;
			ad_node.innerHTML = new_ad ;
			}
		}
	
	
};// end AdManager.prototype

// sync_ads code
// end sync ads


function getPreroll() {
    return ad_manager.getAd('preroll');
}

function getOverlay() {
    return ad_manager.getAd('overlay');
}

function getPostroll() {
   return ad_manager.getAd('postroll');
}

if(typeof(embeddedProxy) != "undefined"){
    ad_manager = new AdManager(embeddedProxy);
}
