if (typeof(WWE) == 'undefined')  WWE = {}

if (typeof(WWE.DoubleClick) == 'undefined') {
 WWE.DoubleClick = function() {
        var VERSION = '200803260008';
        // Private Variables
        var random = 0;
        var protocol = window.location.protocol;
        var server = 'ad.doubleclick.net';
        var networkID = 'N4675';
        var siteName = '';
        var zoneName = '';
        var keyValues = {};
        var tile = 1;
        var ads = [];
        var render = [];

        // Private Methods
        function reset() {
              tile = 1;
              generateRandomNumber();
        }

        function generateRandomNumber() {
               var rn = new String(Math.random());
               random = rn.substring(2, rn.length);
               return random;
        }

        function buildTag(size, type, dcopt ) {
                var tag = protocol + '//' + server + '/';
                if (type === 'adj' || type === 'adf') { tag += networkID + '/'; }
                tag += type + '/';
                tag += siteName + '/' + zoneName + ';';

                for (keyValue in keyValues) {
                        if (typeof(keyValues[keyValue]) != 'string') {
                                for (var i = 0; i < keyValues[keyValue].length; i++ ) {
                                        tag += keyValue + '=' + keyValues[keyValue][i] + ';';
                                }
                        } else {
                                tag += keyValue + '=' + keyValues[keyValue] + ';';
                        }
                }
                var excludeHostName = "ss10.wwe.com";
                if (window.location.hostname != excludeHostName) {
                     if (dcopt) { tag += 'dcopt=ist;'; }
                }

                if (WWESiteWide.wwe_testad_enabled == 1) tag += 'path=test;';

                tag += 'sz=' + size + ';';
                if (size == '728x90,1000x90') {
                        tag += 'pos=top;';
                } else if (size == '300x600,300x251') {
                        tag += 'pos=right;';
                } else if (size == '300x250') {
                        tag += 'pos=bottom;';
                }
                tag += 'tile=' + tile + ';';
                tile++;
                tag += 'dcove=d;';
                tag += 'ord=' + random+'?';
                return tag;
        }

        // call first dc call for iframe
        function writeDCCall (divID, size, tag, width, height){
              var newscript = '<iframe marginheight="0" marginwidth="0" allowtransparency="true"  id="galAd' + size + '" src="/sites/all/modules/custom/features/wwe_sitewide/FiFIE.html?id=galAd'+size+ '&dcsrc='+tag+'" border="0" frameborder="0" width="' + width + '" height="' + height + '" scrolling="no"></iframe>';
              document.getElementById(divID).innerHTML = newscript;
        }
        // call first dc call for iframe
        function writeDirectDCCall (divID, size, tag, width, height){
              var newscript = '<iframe marginheight="0" marginwidth="0" allowtransparency="true"  id="galAd' + size + '" src="'+tag+'" border="0" frameborder="0" width="' + width + '" height="' + height + '" scrolling="no"></iframe>';
              document.getElementById(divID).innerHTML = newscript;
        }
        // Initialization
        generateRandomNumber();

        // Public Methods
        return {
          getRandomNumber : function() {
          return random;
        },

        setValues: function(values) {
                if (typeof(values.siteName) !== 'undefined') { siteName = values.siteName; }
                if (typeof(values.zoneName) !== 'undefined') { zoneName = values.zoneName; }
                if (typeof(values.keyValues) !== 'undefined') { keyValues = values.keyValues; }
        },

        addKeyValue: function(key,value) {
                if(typeof(keyValues[key]) === 'undefined') {
                        keyValues[key] = value;
                } else if (typeof(keyValues[key]) === 'string') {
                        keyValues[key] = [keyValues[key]];
                        keyValues[key].push(value);
                } else {
                        keyValues[key].push(value);
                }
        },
        renderAd: function(size, dcopt, type, delta) {
              // Only render the ad if it's the first time being rendered
              if (!render[delta]) {
                  type = type ? type : 'adj';
                  var tag = buildTag(size,type,dcopt);
                  switch (type) {
                          case 'adi':
                                  document.write('<script type="text/javascript">');
                                  document.write('var adTag = "' + tag + ';dc_seed=";');
                                  document.write('</scr' + 'ipt>');
                                  break;
                          case 'pfadx':
                                  document.write('<script type="text/javascript">');
                                  document.write('var introclip = "' + tag + '";');
                                  document.write('</scr' + 'ipt>');
                                  break;
                          case 'adf':
                                  var origtile = tile -1;
                                  var sizeOfId = size.replace(',','_');
                                  var divID = "divgalAd" + sizeOfId ;

                                  document.write('<div id="' + divID + '"></div>');

                                  // set iframe default width and height
                                  if (size == '728x90,1000x90' ) {
                                          width = '1000';
                                          height = '90';
                                          tag = tag.replace('adf/','adj/');
                                          writeDCCall(divID,size,tag,width,height);
                                  } else 	if (size == '300x600,300x251' ) {
                                          width = '300';
                                          height = '600';
                                          window.setTimeout(function() {
                                              tag = tag.replace('adf/','adj/');
                                              writeDCCall(divID,size,tag,width,height);
                                          }, 200*origtile);
                                  } else {
                                          var dims = size.split('x');
                                          var width = dims[0];
                                          var height = dims[1];
                                          window.setTimeout(function() {
                                               writeDirectDCCall(divID,size,tag,width,height);
                                          }, 500*origtile);
                                  }
                                  ads.push({id:'ifrgalAd'+sizeOfId, type:type, size:size, dcopt:dcopt,tile:origtile,divID :divID,width:width,height:height });
                                  break;
                          default:
                                  document.write('<script type="text/javascript" src="' + tag + '"></scr' + 'ipt>');
                                  break;
                  }
              }
              render[delta] = delta;
        },

        resizeIframe: function(id){
        },
        getZoneName: function() {
                return zoneName;
        },
        reloadAds: function() {
              document.getElementsByTagName('body')[0].style.backgroundImage  = '';
              tile = 1;
              var rn = new String(Math.random());
              random = rn.substring(2, rn.length);

              $.each(ads, function(key, ad) {
                     var tag = buildTag(ad.size,ad.type,ad.dcopt);
                     //console.log('refresh ad sz'+ ad.size+'   tile= '+ ad.tile+ ad.divID+',w='+ad.width+',ht='+ad.height);
                     if (ad.size == '728x90,1000x90' ) {
                            tag = tag.replace('adf/','adj/');
                            writeDCCall(ad.divID,ad.size,tag,ad.width,ad.height);
                    } else 	if (ad.size == '300x600,300x251' ) {
                            window.setTimeout(function() {
                             tag = tag.replace('adf/','adj/');
                             writeDCCall(ad.divID,ad.size,tag,ad.width,ad.height);
                            }, 200*ad.tile);
                    } else {
                            window.setTimeout(function() {
                              writeDirectDCCall(ad.divID,ad.size,tag,ad.width,ad.height);
                            }, 500*ad.tile);
                    }
             });
        },
      //   Gets a new ad url
      getAdUrl: function(adInfo) {
        reset();
        return buildTag(adInfo.adSize, adInfo.adType, adInfo.dCopt);
      }
       };
 }();
}

// Function used by PG
function reloadWWEAds() {
  WWE.DoubleClick.reloadAds();
  var galleryCookie = new WWE.Cookie(document, ".gallery" + 'nid', null, '/', (window.location.host.toString() != 'localhost') ? '.wwe.com' : null);
  if (!galleryCookie.load()) galleryCookie.store();
  galleryCookie.no = (galleryCookie.no == undefined) ? 1 : parseFloat(galleryCookie.no) + 1;
  galleryCookie.store();
  s.prop33 = parseFloat(galleryCookie.no) + 1;
  s.t();
}

// Function to call omniture and reload ads
function addPageViewAndReloadAds() {
	s.t();
	WWE.DoubleClick.reloadAds();
}

// Function to call omniture alone
function addPageView() {
	s.t();
}

/**
 *  Flash calls this method when it does not have an ad to show for a specific target element
 * <param name="adWidth">Width of targetted ad</param>
 */
function showNullCompanionAd(adWidth, adHeight) {
	var adInfo = {adSize : adWidth+'x'+adHeight, adType : 'adf', dCopt : false};
  	var adUrl = WWE.DoubleClick.getAdUrl(adInfo);
    syncRoadBlock(adUrl);
}

function syncRoadBlock(adTag) {
	//alert('videoGallery::syncRoadBlock,'+adTag);
	var a = adTag.split(';');
	if (a.length>0) {
      for (x=0; x<=a.length-1; x++)	{
	    if (a[x].indexOf('sz=') == 0) {
			    size = a[x].substring(3);
    			dims = size.split('x');
    			height = dims[1];
     			width = dims[0];
         	adId = '';

         	if (width == 300) {
                //removed to avoid DC using this ad slot for companionAd
         		//loadRBs('adDiv_300x600_300x251',width, height, adTag);
         	}
         	if (width == 728 || width == 930 || width == 1000) {
         		loadNewRBs('vidAdDiv_728x90_1000x90',width, height, adTag);
         	}
         	if (width == 0) {
         		loadBGs(adTag + ';dcopt=ist;');
         	}
        }
       }
	}
}

function loadBGs(adUrl)	{
	adUrl = encodeURIComponent('/proxy?url=' + adUrl);
}

function loadRBs(s,w,h,adTag)  {
 document.getElementById(s).innerHTML = '<iframe src="' + adTag  +'" id="ifr_companion" width="'+w+'" height="'+h+'" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
}

function loadNewRBs(s,w,h,adTag)  {
   //alert('videoGallery::loadRBs '+adTag);
   w = '1000';
   var adUrl = "http://ad.doubleclick.net/N4675/adj/wwe.video/;sz=728x90,1000x90;dcopt=ist;pos=top;pagetype=videos;tile=1;dcove=d;ord=24928121980535511?";//WWE.DoubleClick.getAdUrl(adInfo);
   var fifieUrl = "/sites/all/modules/custom/features/wwe_sitewide/FiFIE.html?id=ifr_companion&dcsrc="+adUrl;
   document.getElementById(s).innerHTML = '<iframe src="' + fifieUrl  +'" id="ifr_companion" width="'+w+'" height="'+h+'" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
}

///   Called by the flash player when an error is raised in the DC component
/// <param name="adUrl">Url of the ad call that was made to doubleclick</param>
function handleDoubleClickError(adUrl) {
       var url = 'http://gen.wwe.com/trac/gif.php?PIXID=22&Str1=' + encodeURIComponent(adUrl);
       new Ajax.Request(url);
} //end method handleDCError

/**
 * Tremor Media banner ad callbacks
 */
function displayFallbackBanners(banners, x300, x728) {
	if (!x300) { showNullCompanionAd(300, 250); }
    if (location.href.indexOf('/shows/') == -1) {
       if (!x728) { showNullCompanionAd(728, 90); }
    }
}
/* Called by Tremor for Companion Ads.
 * NOTE: Tremor needs our divIDs to drop Ads
 */
function displayCompanionBanners(banners){
	var x300 = false;
	var x728 = false;
	for (var i in banners) {
		if (banners[i].width == '300') {
			try {
                tmDisplayBanner(banners, "adDiv_Companion_300x250", 300, 250, "300x250");
                x300 = true;
			} catch (e) {}
		} else if (banners[i].width == '728') {
              try {
                tmDisplayBanner(banners, "vidAdDiv_728x90_1000x90", 728, 90, "728x90");
                x728 = true;
              } catch (e) {}
		} else if (banners[i].width == '1000') {
              try {
                tmDisplayBanner(banners, "vidAdDiv_728x90_1000x90", 1000, 90, "1000x90");
                x728 = true;
              } catch (e) {}
		}
	}
	displayFallbackBanners(banners, x300, x728);
}
/*
 * function to reload ad, and omniture call for every 30 seconds.
 */
function onTimerReloadWWEAds() {
  WWE.DoubleClick.reloadAds();
  s.t();
  self.setTimeout('onTimerReloadWWEAds()', 30000);
}

