// JScript File: requires validate.js
// Used for default registrations
var MWGAd_defaultAdGroup = new AdvertisementGroup(null);
var MWGAd_defaultAdTokenGroup = new AdvertisementTokenGroup(null);

//var MWGAd_searchAdTokenValue = ""; // doubleclick has reserved keyword for search terms
var MWGAd_reservedSearchKeywordsTokenName = "kw";
var MWGAd_defaultAdTokenDelimeter = ";";
var MWGAd_defaultAdTokenValueDelimeter = "=";
var MWGAd_sourceSplitAgent = '$mwg$';

var MWGAd_largeRandomInt = MWGAd_GenerateRandomUniqueInteger()

//////// AdvertisementToken HELPERS ////////////

function OverrideTokenDelimeter(newDelimeter)
{
	MWGAd_defaultAdTokenDelimeter = newDelimeter;
}

function OverrideTokenValueDelimeter(newDelimeter)
{
	MWGAd_defaultAdTokenValueDelimeter = newDelimeter;
}

//////// AdvertisementToken ////////////

function AdvertisementToken(name,value)
{
	this.name = "";
	this.value = "";
	
	if( name != null )
	{
		this.name = name;
		this.value = value;
	}
}

AdvertisementToken.prototype.Serialize = function ( tokenDelimeter , valueDelimeter )
{
	return tokenDelimeter + this.name + valueDelimeter + this.value;
}

//////// AdvertisementTokenGroup ////////////




function AdvertisementTokenGroup(size /* null permitted */ )
{
	this.Tokens = null;
	
	if( size != null )
	{
		this.Tokens = new Array( size );
	}
	else
	{
		this.Tokens = new Array();
	}
}

AdvertisementTokenGroup.prototype.Serialize = function ( tokenDelimeter , valueDelimeter  )
{
	var returnVal = "";
	var hasSearchKeywords = false;
	
	if( this.Length() > 0 )
	{	
		// if contains search keywords, then we want to serialize string with that key-value first
		for( var i = 0; i < this.Tokens.length; i++ )
		{
			if( this.Tokens[ i ] )
			{
				if( this.Tokens[i].name == MWGAd_reservedSearchKeywordsTokenName )
				{
					hasSearchKeywords = true;
					// search terms go first
					returnVal += this.Tokens[ i ].Serialize(tokenDelimeter,valueDelimeter);
				}
			}
		}		
	
		for( var i = 0; i < this.Tokens.length; i++ )
		{
			if( this.Tokens[ i ] )
			{
				if(   (hasSearchKeywords && this.Tokens[ i ].name != MWGAd_reservedSearchKeywordsTokenName)
				    || !hasSearchKeywords )
				{
					returnVal += this.Tokens[ i ].Serialize(tokenDelimeter,valueDelimeter);
				}
			}
		}
	}
		
	return returnVal;
}

// specialized/specific version of serialize
AdvertisementTokenGroup.prototype.SerializeURL = function ( )
{
	return this.Serialize("&","=");
}

AdvertisementTokenGroup.prototype.RemoveAll = function ( )
{
	this.Tokens = new Array();
}


AdvertisementTokenGroup.prototype.RemoveByName = function ( name )
{
	if( this.Tokens == null )
	{
		return;
	}
	else
	{	
		for( var i = 0; i < this.Tokens.length; i++ )
		{
			if(	  this.Tokens[ i ] != null
			    &&  this.Tokens[ i ].name == name )
			{
				this.Tokens.splice ( i , 1 );
				return;
			}
		}
	}
}

AdvertisementTokenGroup.prototype.Merge = function ( rhs )
{
	// if current contains token and RHS contains token, copy RHS token value to current
	// if current doesn't contain token and RHS contains token, copy RHS token to current
	// if current contains token and RHS doesn't, leave token untouched
	
	if( this.Tokens == null )
	{
		this.Tokens = rhs;
	}
	else
	{			
		for( var i = 0; i < rhs.Length(); i++ )
		{
			//alert(rhs.Tokens[ i ].name + " : : " + rhs.Tokens[ i ].value );
			var currentToken = this.FindByName( rhs.Tokens[ i ].name );
		
			// merge where both sides contain token	
			if ( currentToken != null )
			{
				currentToken.value = rhs.Tokens[ i ].value;
			}
			else
			{
				// merge where rhs has the token and current doesn't
				this.Add( new AdvertisementToken( rhs.Tokens[ i ].name , rhs.Tokens[ i ].value ));
			}				
		}
	
	}
}

// returns token object
AdvertisementTokenGroup.prototype.FindByName = function ( name )
{
		for( var i = 0; i < this.Tokens.length; i++ )
		{
			if(	  this.Tokens[ i ] != null
			    &&  this.Tokens[ i ].name == name )
			{
				return this.Tokens[ i ];
			}
		}
}

AdvertisementTokenGroup.prototype.Add = function (newToken)
{
	if( this.Tokens == null )
	{
		this.Tokens = new Array();
	}
		
	this.Tokens[ this.Tokens.length ] = newToken;
}


AdvertisementTokenGroup.prototype.Length = function ()
{
	if( this.Tokens == null )
	{
		return -1;
	}
	else
	{
		return this.Tokens.length;
	}
}


//////// AdvertisementGroup ////////////



function AdvertisementGroup( size /* null permitted */ )
{
	this.Ads = null;

	if( size != null )
	{
		this.Ads = new Array( size );
	}
	else
	{
		this.Ads = new Array();
	}
}

AdvertisementGroup.prototype.RemoveAll = function ( )
{
	this.Ads = new Array();
}


AdvertisementGroup.prototype.RemoveByLocation = function ( location )
{
	if( this.Ads == null )
	{
		return;
	}
	else
	{	
		for( var i = 0; i < this.Ads.length; i++ )
		{
			if(	  this.Ads[ i ] != null
			    &&  this.Ads[ i ].adLocation == location )
			{
				this.Ads.splice ( i , 1 );
				return;
			}
		}
	}
}

AdvertisementGroup.prototype.Add = function (newAdvertisement)
{
	if( this.Ads == null )
	{
		this.Ads = new Array();
	}
		
	this.Ads[ this.Ads.length ] = newAdvertisement;
}


AdvertisementGroup.prototype.RefreshAll = function ( newOrdValue , adTokenGroup /* null permitted */ )
{	
	// set new ord value
	MWGAd_SetOrdValue( newOrdValue );
	
	//alert("RefreshAll Called::" + this.Length());
	// Set tokens first, just in case no ads exist so that every frame which includes this JS file will have a copy of tokens used (real target is top frame)
	if( adTokenGroup != null )
	{		
		// if adTokenGroup not null, we FULLY replace the tokens on the current window with those given
		try
		{
			MWGAd_defaultAdTokenGroup.Merge( adTokenGroup );
		}
		catch( e )
		{}
	}
		
	if( this.Ads != null )
	{
		for( var i = 0; i < this.Ads.length; i++ )
		{
			this.Ads[i].RefreshAd( );
		}
	}
}

AdvertisementGroup.prototype.Length = function ()
{
	if( this.Ads == null )
	{
		return -1;
	}
	else
	{
		return this.Ads.length;
	}
}




//////// Advertisement ////////////




// "page" removed. currently unnecessary
function Advertisement( frame , /*page ,*/ adLocation , adContents )
{
	this.frame = frame;
	//this.page = page;
	this.adLocation = adLocation;
	this.adContents = "";

	if(	adContents != null
		&& adContents.length > 0 )
	{
		this.adContents = adContents;
	}
}

Advertisement.prototype.RefreshAd = function ()
{
	MWGAd_RefreshAdContent( this.frame , this.adLocation , this.adContents);
}

Advertisement.prototype.Exists = function ()
{
	return MWGAd_ElementExists( this.frame , this.adLocation );
}





//////// Advertisement Helpers ////////////


// operates on all frames
function MWGAd_RefreshSite( newOrdValue , adTokenGroup /* null permitted */ )
{
	var top = window.top;
		
	MWGAd_RefreshAllInFrameTree( top , newOrdValue,  adTokenGroup );
}

// operates on a given frame and child frames
function MWGAd_RefreshAllInFrameTree( theFrame , newOrdValue , adTokenGroup /* null permitted */ )
{
	if( theFrame.frames )
	{
		for( var i = 0; i < theFrame.frames.length; i++ )
		{
			MWGAd_RefreshAllInFrameTree( theFrame.frames[i] , newOrdValue , adTokenGroup );
		}
	}
	
	try
	{
		// refresh current frame
		if( theFrame.MWGAd_RefreshRegisteredAds )
		{	
			theFrame.MWGAd_RefreshRegisteredAds( newOrdValue , adTokenGroup );
		}
	}
	catch( e ){}	
}

// operates within the current window (Frame) only
function MWGAd_RefreshRegisteredAds( newOrdValue , adTokenGroup /* null permitted */ )
{
	MWGAd_defaultAdGroup.RefreshAll( newOrdValue , adTokenGroup );
}


function MWGAd_ElementExists( frame , id )
{
	if( eval( frame.document.getElementById( id ) ) )
	{
		return true;
	}
	else
	{
		return false;
	}
}

function MWGAd_RefreshAdContent( frame , id , optionalContent1 /* null permitted */)
{
	//alert("called MWGAd_RefreshAdContent with " + id + "::" + optionalContent.length);
	var optionalContent = "";
	var width = 120;
	var height = 60;
	var cssText = "";
	
	
	if(optionalContent1 != null && optionalContent1.length > 0)
	{ 
	
	    var strTemp = new String(optionalContent1);
	    
	    var strTemp1;
	    
	    if(strTemp.indexOf(MWGAd_sourceSplitAgent) != -1 )
	    {	        
	        strTemp1 = strTemp.split(MWGAd_sourceSplitAgent);

	        if ( strTemp1!= null && strTemp1.length > 0 )
	        {	            
	            optionalContent = strTemp1[0];
	            
	            for(var count = 1; count<strTemp1.length; ++count)
	            {
	                if(strTemp1[count].indexOf('c=')!=-1)
	                {
	                    cssText = strTemp1[count].substring(2);
	                }
	                if(strTemp1[count].indexOf('w=')!=-1)
	                {
	                    width = strTemp1[count].substring(2);
	                }
	                if(strTemp1[count].indexOf('h=')!=-1)
	                {
	                    height = strTemp1[count].substring(2);
	                }
	            }
	            
                
                
    	       /* if( strTemp1.length >1 )
    	        {
	                cssText = strTemp1[1];
                }
	            
	            if( strTemp1.length > 2 )
	            { 
    	            width = strTemp1[2];                    
                }
                
                if( strTemp1.length > 3 )
                {
                    height = strTemp1[3];
                }*/
	        }
	    }
	    else
	    {
	        optionalContent = strTemp;
	    }
	   
	    
    	
	}
	var curValue = "";
	
	var containerID = id + "_Container";
	var sourceID = id + "_Source";
	
	var frame_container = null;
	var frame_theAdNode = null;
	var frame_theAdSource = null;

	if( frame == null )
	{//alert(id + "::frame is null");
		return;
	}
	
	if( ! eval( frame ) )
	{//alert(id + "::frame does not eval");
		return;
	}
	  
	if( ! MWGAd_ElementExists( frame , containerID ) )
	{
		return; // cannot proceed without container. Improperly setup.
	}
	else
	{
		frame_container = frame.document.getElementById( containerID );
	}
	
	if( ! MWGAd_ElementExists( frame , id ) )
	{
		return; // cannot proceed without container. Improperly setup.
	}
	else
	{
		frame_theAdNode = frame.document.getElementById( id );
	}

	// ad exists, continue
		
	if(	optionalContent != null
		&& optionalContent.length > 0 )
	{
		curValue = optionalContent;
	}	

	if( curValue.length == 0 )
	{	
		if( ! MWGAd_ElementExists( frame , sourceID ) )
		{
			return; // cannot proceed without container. Improperly setup.
		}
		else
		{
			frame_theAdSource = frame.document.getElementById( sourceID );
		}
		// get current content, re-use it since no optional content was given
		curValue = frame_theAdSource.value;
	}

	// Remove Ad and children
	frame_container.innerHTML = "";
	//frame_container.blur();
	
	//frame_container.childNodes.length = 0;
	//for( var i = 0; i < frame_container.childNodes.length; i++ )
	//{
	//	var oChild=frame_container.childNodes[i];	
	//	frame_container.removeChild(oChild);
	//}

	// Add it back in
	var frame_newAdNode = frame.document.createElement("div");
	frame_newAdNode.id = id;
	
	// Tokens
	
	
	while( curValue.indexOf( "<mwg_adtokens_mwg/>" ) >= 0 )
	{
		try
		{
			curValue = curValue.replace("<mwg_adtokens_mwg/>", MWGAd_defaultAdTokenGroup.Serialize(MWGAd_defaultAdTokenDelimeter,MWGAd_defaultAdTokenValueDelimeter));
		}
		catch( e )
		{
			//alert(e);
			break;
		}
	}
	
	// append our cache buster (and tile glue)
	newOrdValue = MWGAd_BuildOrdNameValuePair();
	while( curValue.indexOf( "<mwg_adord_mwg/>" ) >= 0 )
	{
		try
		{
			curValue = curValue.replace("<mwg_adord_mwg/>", newOrdValue);
		}
		catch( e )
		{
			//alert(e);
			break;
		}
	}	

	// MPB: 2007-04-02: IE 6.0 (only 6 has been tested) will only fire javascript if the <BR> tag is included in the innerHTML value, very strange, trying
	// to find a workaround.
	// WORKAROUND DISCOVERED: use span tag with non-breaking-space, position absolute so that it doesn't interfere with surrounding document
	//								  http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/fb360f782ef616ad/1c3280e489db3841?lnk=st&q=IE+appendchild+javascript+doesn%27t+execute&rnum=10&hl=en#1c3280e489db3841	
//	if( document.all )
//	{
//		// IE runs javascript immediately after setting innerHTML, so append child first to ensure ID exists prior to code execution (which may refer to the ID)
//		frame_container.appendChild( frame_newAdNode );
//		frame_newAdNode.innerHTML = "<span style=\"position:absolute;left:-1000;\">&nbsp;</span>" + curValue;
//	}
//	else
//	{
//		// All else (FF2.0 so far) runs javascript immediately after appendingChild()
//		// All else (FF2.0 so far) doesn't need the span hack
//		frame_newAdNode.innerHTML = curValue;
//		frame_container.appendChild( frame_newAdNode );		
//	}
    
    // Function to Prepare and Show the Ad on the Page 
    showAD(id,curValue,width,height,cssText);   
	
//	alert("PreAppendChild");		
	// add element back in, fires code if exists
		
	//container.blur();
	
//alert("CurValue=" + curValue);

//alert("AfterRemove: innerHTML:" + container.innerHTML);

}

function MWGAd_SetupIFrameAd(idprefix,src,width,height)
{
	var container = document.createElement("DIV");
	
	var oIF = document.createElement("IFRAME");
	
	var uniqueID = MWGAd_GenerateRandomUniqueInteger();
	
	oIF.setAttribute("id","id_" + idprefix + uniqueID);
	oIF.setAttribute("name","name_" + idprefix + uniqueID);
	oIF.style.width = width+"px";
	oIF.style.height = height+"px"; 
	oIF.setAttribute("width","" + width);
	oIF.setAttribute("height","" + height);
	oIF.setAttribute("src", src );

	oIF.setAttribute("marginwidth","0");
	oIF.setAttribute("marginheight","0");
	oIF.setAttribute("hspace","0");
	oIF.setAttribute("vspace","0"); 
	oIF.setAttribute("frameBorder","0"); // mozilla doesn't care but IE wants camel case
	oIF.setAttribute("scrolling","no");
	oIF.setAttribute("borderCOLOR","#000000");
	oIF.setAttribute("visibility","visible");
	oIF.setAttribute("margin","0");
	oIF.setAttribute("padding","0");
	oIF.setAttribute("style","margin:0px;padding:0px;");

	//document.body.appendChild(oIF);
	return oIF;	
	//document.getElementByID(idprefix).appendChild(oIF);
}

function MWGAd_GenerateRandomUniqueInteger()
{
	var a = Math.random()+"";
	var b = a * 1000000000000000000;
	var c = Date.parse( new Date() ) + "" + b;
	return c;
}
function MWGAd_SterilizeSearchKeywords(searchKeywords)
{
	return stripCharsInBag(searchKeywords,"#\",*.()=+<>[];")
}
function MWGAd_BuildOrdNameValuePair()
{
	return ";ord=" + MWGAd_largeRandomInt + "?";
}
function MWGAd_SetOrdValue( newOrdValue )
{
	MWGAd_largeRandomInt = newOrdValue;
}
function MWGAd_GetOrdValue( )
{
	return MWGAd_largeRandomInt;
}
function MWGAd_RandomizeOrdValue()
{
	MWGAd_SetOrdValue( MWGAd_GenerateRandomUniqueInteger() );
}
// original purpose was to keep snapshot of latest tokens at "top" frame for use by lower level frames
function MWGAd_GetDefaultTokenGroup()
{
	return MWGAd_defaultAdTokenGroup;
}




// function to show the AD
function showAD(container,adURL,w,h,cssText)
{
   try
   {  
      if (adURL != "" && adURL.substring(0,5) != MWGAd_sourceSplitAgent)
      {
        var containerElement = document.getElementById( container + "_Container");
        containerElement.innerHTML = "";
        var containerDiv = document.createElement('DIV');
        containerDiv.setAttribute('id',container);
        
        if (cssText != '')
        {
            containerElement.setAttribute('style',cssText);
            containerElement.style.cssText = cssText;
        }
        
        containerDiv.appendChild(MWGAd_SetupIFrameAd(container,adURL,w,h));
        
        containerElement.appendChild(containerDiv);
      }         
   }
   catch(e)
   {//alert(e);
   }
}
