var _DEBUG = false;
var WNG_BRIDGEFILEPATH = '/global/interface/linksplus/linksplusbridge.html';
var WNG_COOKIEMANAGERURL = 'http://content.worldnow.com/global/interface/cookiemanager.js';
var WNG_COOKIEMANAGERID = 'wncookiemanager';
var WNG_REFERRERNAME = 'referrerDomain';
var WNG_RESIZE_HEIGHTPADDING = 25;
var wng_resizeFrameId = 'Frame1';

/* Import js files *********************************************************************/
/***************************************************************************************/
//wnCreateElement ( 'SCRIPT' , {id:WNG_COOKIEMANAGERID,src:WNG_COOKIEMANAGERURL,type:'text/javascript'} );
document.writeln ( '<SCR' + 'IPT id="' + WNG_COOKIEMANAGERID + '" src="' + WNG_COOKIEMANAGERURL + '" type="text/javascript"></SCR' + 'IPT>' );

/* Create Page Element *****************************************************************/
/***************************************************************************************/
function wnCreateElement ( tagname, atts, attachToObj ) {
	var e = document.createElement ( tagname.toUpperCase() );

	if ( typeof (atts) == 'object' ) {
		for (var name in atts) {
			e.setAttribute ( name, atts[name] );
		}		
	}
	
	if ( typeof (attachToObj) != 'object' ) {
		var bodies = document.getElementsByTagName('BODY');
		if ( bodies.length ) {
			attachToObj = bodies[0];
		}
		else {
			attachToObj = document.documentElement;
		}
	}
	
	attachToObj.appendChild ( e );
	return ( e );
}
/* Get Query String Value **************************************************************/
/***************************************************************************************/
function wnGetQueryValue(name) {	
	var nameValue;
	var queryString = location.search.substr(1);
	var vals = queryString.split('&');
	
	for (var i=0; i<vals.length; i++) {
		nameValue = vals[i].split('=');
		if (name == nameValue[0]) {
			return unescape(nameValue[1]);
		}
	}	
	return null;
}
/* Go To URL (top window) **************************************************************/
/***************************************************************************************/
function wnParentLocation (url) {
	window.parent.location.href = url;
}
/* Convert keywords array to delimited format ******************************************/
/***************************************************************************************/
function wnKeywordsToParams ( eq, sep, keywords ) {
	if ( keywords ) {
		var params = '';
		for (var name in keywords) {
			params += sep + name + eq + keywords[name];
		}
		return params.substr(1);
	}
	return null;
}
/* Return the offset height of a page element ******************************************/
/***************************************************************************************/
function wnGetDocumentHeight(obj) {
	var height = 0;
	var padding = wnGetQueryValue ( 'padding' );
	padding = ( padding ) ? parseInt( padding ): WNG_RESIZE_HEIGHTPADDING;
	
	if (obj.offsetParent) {
		height = obj.offsetTop;
		while (obj = obj.offsetParent) {
			height += obj.offsetTop;
		}
	}
	return height + padding;
}
/* Main routine.  We wrap these instructions within a function so we can delay their 
execution until any other js includes are loaded ***************************************/
/***************************************************************************************/
function wnMainRoutine() {

	// Check if WN_Update Links is enabled
	/************************************************************************************/

	try {
		if ( wng_updateLinksDynamicLinksPlusID ) {
	
			try { if(wng_updateLinksMode){} }
			catch(err) { var wng_updateLinksMode =  'IFRAME'; }
			
			try { if (wng_updateLinksParentElementArray){} }
			catch(err) { var wng_updateLinksParentElementArray = []; }
		
			WNUpdateLinks.setMode(wng_updateLinksMode);
			WNUpdateLinks.setLinkPlusId(wng_updateLinksDynamicLinksPlusID);
			WNUpdateLinks.load(wng_updateLinksParentElementArray);
			
		}
	}
	catch (err) {
		// Could not update links
		//if ( _DEBUG ) alert ( 'could not update links: ' + err );
	}	
			
	/************************************************************************************/
	/************************************************************************************/


	// Build bridge file url
	var topDomain = wnGetQueryValue ( WNG_REFERRERNAME );
	var queryString = "?rnd=" + Math.floor(Math.random() * 9999);

	// Check if this is the inital Frame load, in which case pull the referrer value from the query
	/************************************************************************************/
	if ( topDomain ) { // this is the inital linksplus call
		// set a cookie for subsequent clicks
		WNCookieManager.setCookie( WNG_REFERRERNAME, topDomain, false, '/' );
		// disable ad keywords transfer
		wng_pageKeywords = false;
		// disable refresh ads on click
		wng_refreshAdsOnClick = false;
	}
	else { // this is a subsequent click
		// try to retreive a the top domain via a cookie
		topDomain = WNCookieManager.getCookie ( WNG_REFERRERNAME );
		// If the topDomain could not have been defined by now, exit the function.
		if ( !topDomain ) { 
			return false;
		}
	}
	/************************************************************************************/
	/************************************************************************************/
	
	// Check if resize functionality has been enabled.  Build query string for resizing the frame
	/************************************************************************************/
	try {
		if ( wng_resizeFrame ) {
			// The document scroll height of the 3rd party page
			endOfContent = wnCreateElement ( 'DIV' );
			var documentHeight = wnGetDocumentHeight ( endOfContent );
		
			// Is the target resize frame being passed through the queryString?
			wng_resizeFrameId = ( wnGetQueryValue( 'resizeFrameId' ) ) ? wnGetQueryValue( 'resizeFrameId' ) : wng_resizeFrameId;
			
			queryString += '&height=' + documentHeight + '&resizeframeid=' + wng_resizeFrameId + '&visibility=visible';
		}
	}
	catch (err) {
		// Could not build resize params
		//if ( _DEBUG ) alert ( 'could not build resize params: ' + err );
	}
	/************************************************************************************/
	/************************************************************************************/
		
	// Check if page keywords has been enabled. Build query string for page keywords
	/************************************************************************************/
	try {
		if ( wng_pageKeywords ) {
			queryString += '&adkeywords=' + wnKeywordsToParams ( ":", ";", wng_pageKeywords );
		}
	}
	catch ( err ) {
		// Could not build page keywords params
		//if ( _DEBUG ) alert ( 'could not build page keyword params: ' + err );
	}
	/************************************************************************************/
	/************************************************************************************/
	
	// Check if refresh ad on click has been enabled.  Build query string.
	/************************************************************************************/
	try {
		if ( wng_refreshAdsOnClick ) {
			queryString += '&refreshadsonclick=1';
		}
	}
	catch ( err ) {
		// Could not build refresh Ads string
		//if ( _DEBUG ) alert ( 'could not build refresh on click params: ' + err );
	}
	/************************************************************************************/
	/************************************************************************************/
		
	// Create the domain bridge iframe	
	/************************************************************************************/
	if ( queryString.indexOf ( '&' ) > -1 ) {
		var url = 'http://' + topDomain + WNG_BRIDGEFILEPATH + queryString;
		wnCreateElement ( 'IFRAME', {src:url,width:'0',height:'0',frameborder:'0',style:'display:none'} );
	}
	/************************************************************************************/
	/************************************************************************************/
	
} // End of main routine

/* WNUpdateLinks   **********************************************************************/
/* This tool is intended to automatically format existing links on a page served by a 3rd party 
content provide do that it redirects to any give DynamicLinksPlus page. */
/***************************************************************************************/

var WNUpdateLinks = {
   
   debug : false,
   mode : 'IFRAME',
   linkPlusId : 0,
   WNDomain : false,
   WNLocation : false,
   CPDomain : false,
   CPLoaction : false,
   WNLinkPlusPath : '/global/link.asp',
   parentElementsArray : [],
   
   setMode : function(modeType) {
      if(modeType=='IFRAME') this.mode = 'IFRAME'; 
      else if(modeType=='SCRIPT') this.mode = 'SCRIPT';
   },
   
   setLinkPlusId : function (id) {
      this.linkPlusId = parseInt(id);
   },
   
   load : function (parentElementIdsArray) {
      this.configModeVars();
      /* Will define an array of elements to search within for links */
      var c = '';
      try {c = new String(parentElementIdsArray.constructor);}catch(e){}
      var parentElementIdsArray = (c.indexOf('Array')>=0) ? parentElementIdsArray : [];
      var currentElement;
      
      if ( parentElementIdsArray.length == 0) {
         this.parentElementsArray[0] = document.getElementsByTagName('BODY')[0];
      }
      else {
         for ( i=0; i<parentElementIdsArray.length; i++ ) {
            try {
               currentElement = document.getElementById(parentElementIdsArray[i]);
               if(currentElement) {
                  this.parentElementsArray[i] = currentElement;
               } else { throw('Element not found: ' + parentElementIdsArray[i]);}
            }
            catch(e) {/*Element not found*/
               this.error('Error in function load: \n' + e);
            }
         }         
      }
      
      this.scanLinks();
   },
   
   configModeVars : function() {
      var domainRegExp = /http\:\/\/[^\/]+/;
      var locationRegExp = /\/[^\/]+(\?.*)*$/
      var windowLocation = new String(window.location.toString());
      var documentReferrer = new String(document.referrer);
      
      if ( this.mode == 'IFRAME' ) {
         this.WNLocation = documentReferrer.replace(locationRegExp,'/');
         this.CPLocation = windowLocation.replace(locationRegExp,'/');
      }
      else if ( this.mode == 'SCRIPT' ) {
         this.WNLocation = windowLocation;
      }
      
      try {
         this.WNDomain = (this.WNLocation) ? domainRegExp.exec(this.WNLocation) : false;
         if(!this.WNDomain) throw('Can not proceed without WNDomain defined');
         this.CPDomain = (this.CPLocation) ? domainRegExp.exec(this.CPLocation) : false;
         if(!this.CPDomain) throw('Can not proceed without CPDomain defined');
      }
      catch(e) { this.error('Error in function configModeVars:\n' + e,1); }
      
   },
   
   scanLinks : function() {
      var anchorArray;
      for(i=0;i<this.parentElementsArray.length;i++) {
         anchorArray = this.parentElementsArray[i].getElementsByTagName('A');
         for(j=0;j<anchorArray.length;j++) {
            this.updateLink(anchorArray[j]);
         }
      }
   },

   updateLink : function(node) {
      var hrefAtt;
      var linkMode;
      var fullUrl;
      var newUrl;
      try {
         hrefAtt = node.getAttribute('HREF');
         if(hrefAtt) {
            if(hrefAtt.indexOf('http:\/\/')==0) linkMode = 'full';
            else if(hrefAtt.indexOf('/')==0) linkMode = 'abs';
            else linkMode = 'rel';
            if(linkMode!='full' && this.mode=='SCRIPT') throw('SCRIPT mode can only update fully qualified URLS (ie. http:\/\/URL):\n' + hrefAtt);
            else {
               if(linkMode=='full') fullUrl = hrefAtt;
               else if(linkMode=='abs') fullUrl = this.CPDomain + hrefAtt;
               else if(linkMode=='rel') fullUrl = this.CPLocation + hrefAtt;
               if(fullUrl){ 
                  newUrl = this.WNDomain + this.WNLinkPlusPath + '?L=' + this.linkPlusId + '&dynamicURL=' + escape(fullUrl); 
                  node.setAttribute( 'href', 'javascript:wnParentLocation("' + newUrl + '")' );
                  node.href= 'javascript:wnParentLocation("' + newUrl + '")';      
               } else {throw('Full URL could not be calculated.');}
            }
         }else {throw('Href not set for link: ' + node.innerHTML);}
      } catch(e) {this.error('Error in function updateLink:\n' + e);}            
   },
   
   error : function (err,terminate) {
      if(this.debug) alert('Error in class WNUpdateLinks:\n' + err);   
      if(terminate==1) return false;
   }

};

/* Delay Execution until js files are loaded *******************************************/
/***************************************************************************************/

function wnStartWhenLoaded ( iteration ) { 

	iteration = ( iteration ) ? iteration : 1;
	pauseMilSec = 500;
	maxWaitSeconds = 5;
	maxIterations = ( 1000 / pauseMilSec ) * maxWaitSeconds;
	allReady = false;
	if ( iteration <= maxIterations ) {
		try {
			// List variables required to load
			if ( WNCookieManager ) { 
				allReady = true;
			}
		}
		catch ( err ) {
			//if ( _DEBUG ) alert ( 'caught exception: ' + err ); 
			iteration++;
			window.setTimeout ( 'wnStartWhenLoaded(' + iteration + ');', pauseMilSec );
			return false;
		}
		if ( allReady ) {	
			wnMainRoutine();
			return true;
		}
	}
	else {
		// failed, max wait seconds reached
	}
}
wnStartWhenLoaded();


