/*
MWG Advertisement Manager for DART v2.7.0 Commercial Edition - Copyright (c) 2000-2008 MyWebGrocer, LLC

Last Modified: 3/16/2009

WARNING: Do NOT make any modification to this file without proper permit.
*/

var MWGAd_defaultAdGroup = new AdvertisementGroup(null);
var MWGAd_defaultAdTokenGroup = new AdvertisementTokenGroup(null);

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++ )
                {
                        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)
{
        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 );
        
        // 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++ )
                {
                         return 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 ()
{
        return 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;
                
        return MWGAd_RefreshAllInFrameTree( window , newOrdValue,  adTokenGroup );
}

// operates on a given frame and child frames
function MWGAd_RefreshAllInFrameTree( theFrame , newOrdValue , adTokenGroup /* null permitted */ )
{
        var content = "";
        if( theFrame.frames )
        {
                for( var i = 0; i < theFrame.frames.length; i++ )
                {
                        return MWGAd_RefreshAllInFrameTree( theFrame.frames[i] , newOrdValue , adTokenGroup );
                }
        }
        
        try
        {
                // refresh current frame
                if( theFrame.MWGAd_RefreshRegisteredAds )
                {        
                         return theFrame.MWGAd_RefreshRegisteredAds( newOrdValue , adTokenGroup );
                }
        }
        catch( e ){}        
}

// operates within the current window (Frame) only
function MWGAd_RefreshRegisteredAds( newOrdValue , adTokenGroup /* null permitted */ )
{
        return 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 */)
{
        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);
                        }
                    }
                   }
            }
            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 )
        {
                return;
        }
        
        if( ! eval( frame ) )
        {
                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 );
        }
        
        if(cssText!='')
        {
                frame_theAdNode.style.cssText = cssText;
        }

        // 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;
        }

        // Tokens
        while( curValue.indexOf( "<mwg_adtokens_mwg/>" ) >= 0 )
        {
                try
                {
                        curValue = curValue.replace("<mwg_adtokens_mwg/>", MWGAd_defaultAdTokenGroup.Serialize(MWGAd_defaultAdTokenDelimeter,MWGAd_defaultAdTokenValueDelimeter));
                }
                catch( 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 )
                {
                        break;
                }
        }        

        return curValue;
}

function MWGAd_SetupJavaScriptAd(src) {
    var oScript = document.createElement('script');
    oScript.setAttribute('language', 'javascript');
    oScript.setAttribute('src', src);
    return oScript;
}

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 MWGAd_StripCharsInBag(searchKeywords,"#\",*.()=+<>[];")
}

function MWGAd_StripCharsInBag (s, bag){
        var i;
        var returnString = "";

        for (i = 0; i < s.length; i++){                   
                var c = s.charAt(i);
                if (bag.indexOf(c) == -1) returnString += c;
        }

        return returnString;
}

function MWGAd_BuildOrdNameValuePair()
{
        return ";ord=" + MWGAd_largeRandomInt + "?";
}
function MWGAd_SetOrdValue( newOrdValue )
{
        MWGAd_largeRandomInt = newOrdValue;
}
function MWGAd_GetOrdValue( )
{
        var frames = parent.document.getElementsByTagName('frame');
        var ordInitialized = false;
        if(frames && frames.length>0)
        {
                for( var i = 0; i < frames.length; i++ )
                {
                        var hUniqueOrder = frames[i].contentWindow.document.getElementById('hUniqueORD');
                        if(hUniqueOrder && hUniqueOrder.value!='')
                        {
                                MWGAd_largeRandomInt = hUniqueOrder.value;
                                ordInitialized = true;
                                break;
                        }
                }
        }
        
        if(ordInitialized == false)
        {
                var hUniqueOrder = document.getElementById('hUniqueORD');
                if(hUniqueOrder)
                {
                        hUniqueOrder.value = MWGAd_largeRandomInt; //only the frame that loads first will set this value
                }
        }
        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_SetupJavaScriptAd(adURL));        

        containerElement.appendChild(containerDiv);
      }        
   }
   catch(e)
   {
   }
}

