var wsl_ready = false;
var wsl_campaign_id, wsl_line_id, duration_in_ms;
var wsl_ad_display_timer = 0;
var wsl_ad_display_timer_duration = 0;
var wsl_clickURLFlash = "";
var wsl_clickURLStatic = "";
var wslClickTargetFrame = "_blank";
var wsl_resume_time_from_cookie = 0;
var wsl_v_scroll = null;
var wsl_h_scroll = null;
var wsl_did_load_flash = 0;
var wsl_did_click_recently = 0;

var wsl_real_zone_id = wsl_zone_id;
var wsll_add_spacer = wsl_add_spacer;
var wsll_force_wmode;
if (typeof(wsl_force_wmode) != "undefined") {
  wsll_force_wmode = wsl_force_wmode;
}
var wsll_fix_youtube_wmode;
if (typeof(wsl_fix_youtube_wmode) != "undefined") {
  wsll_fix_youtube_wmode = wsl_fix_youtube_wmode;
}
var wsl_placement = "bottom";

var wsl_showXAfterSeconds = 0;

if (wsl_real_zone_id.length > 5) {
  wsl_real_zone_id = wsl_real_zone_id.substring(6);
  wsl_real_zone_id = wsl_real_zone_id.split("").reverse().join("");
}

// Production location for ad requests:
var wsl_ads_url = 'http://ads.advinea.com';
//var wsl_ads_url = 'http://adserver-1832466727.ap-southeast-1.elb.amazonaws.com';
//var wsl_ads_url = 'http://ads.adnetworks.co.jp';
// Dev locations for ad requests:
//var wsl_ads_url = 'http://localhost:9292';
//var wsl_ads_url = 'http://192.168.1.111:9292';
// Test location for ad requests:
//var wsl_ads_url = 'http://ec2-50-18-56-30.us-west-1.compute.amazonaws.com:9292';
//var wsl_ads_url = 'http://ec2-175-41-170-112.ap-southeast-1.compute.amazonaws.com:9292';

// Production location for impression events:
var wsl_event_url = 'http://event.advinea.com/event';
//var wsl_event_url = 'http://event.adnetworks.co.jp/event';
// Test location for impression events:
//var wsl_event_url = 'http://ec2-50-18-56-30.us-west-1.compute.amazonaws.com/event';


//Create the 'event tracking' image placeholders
function wsl_createEventElements() {
  // Create the image element for sending impression events.
  var eventImg = document.getElementById('wsl_event');
  if (!eventImg) {
    eventImg = document.createElement('img');
    eventImg.style.position = 'absolute';
    eventImg.id = 'wsl_event';
    eventImg.setAttribute("src", wsl_event_url);
    document.body.appendChild(eventImg);
  }
  //Create the final impression event
  var eventImgFin = document.getElementById('wsl_event_fin');
  if (!eventImgFin) {
    eventImgFin = document.createElement('img');
    eventImgFin.style.position = 'absolute';
    eventImgFin.id = 'wsl_event_fin';
    eventImgFin.setAttribute("src", wsl_event_url);
    document.body.appendChild(eventImgFin);
  }

}

function wsl_reset_did_click_recently() {
  wsl_did_click_recently = 0;
}

function wsl_ad_clicked() {
  if (wsl_did_click_recently == 0) {
    wsl_did_click_recently = 1; //Prevent us from clicking twice back-to-back
    setTimeout('wsl_reset_did_click_recently()', 5000); //Set a timer to clear the did_click_recently flag

    //There's no need to record the ad click here anymore since we record a click inside the wsl_clickURLStatic
    //(That's the URL of the ad server that redirects to the desired click URL)
    //wsl_recordAdClick();
    if (wslClickTargetFrame == '_top') top.location.href = wsl_clickURLStatic;
    else if (wslClickTargetFrame == '_self') self.location.href = wsl_clickURLStatic;
    else if (wslClickTargetFrame == '_new') window.open(wsl_clickURLStatic, "advinea_opener")
    else window.open(wsl_clickURLStatic);
  } else {
    //alert('Click is being ignored; happened too close to a previous click');
  }
}

function wsl_get_resume_time() {
  var resume_time = 0;
  if (wsl_resume_time_from_cookie > 0) {
    resume_time = wsl_resume_time_from_cookie;
  }
  return resume_time;
}
function wsl_flash_creative_loaded() { 
  //The flash creative should alert us when it starts.
  //Start the timer from here so we can fire a final impression
  //If it's a static ad, we'll need to make a JS call to this function.
//alert("Creative loaded, duration = " + duration_in_ms);

  if (wsl_resume_time_from_cookie > 0) {
    //If we're resuming from a cookie, that's our start time
    wsl_ad_display_timer_duration = wsl_resume_time_from_cookie;
  } else {
    //Record our impression event here so we don't also count "ad resumes"
    wsl_trackEvent("imp");
    wsl_ad_display_timer_duration = 0;
  }
  
  clearInterval(wsl_ad_display_timer); //Clear the interval here again, just in case there's already one active
//alert("Here, duration = " + duration_in_ms);
  if (duration_in_ms > 0) {
    wsl_ad_display_timer = setInterval("wsl_ad_timer_tick()", 1000);
  }
}

function wsl_ad_timer_tick() {
  wsl_ad_display_timer_duration++;
  if (duration_in_ms > 0) {
    if ((1000 * wsl_ad_display_timer_duration) >= duration_in_ms) {
      wsl_ad_display_timer_duration = 0;
      //Stop the timer
      clearInterval(wsl_ad_display_timer);

      //Clear our timer cookie
      wsl_setCookie("ad_timer_" + wsl_real_zone_id, 0);
      wsl_setCookie("ad_url", '');
      //Call the function when the creative duration has been reached
      wsl_creativeDurationReached();
    } else {
      //Update our timer cookie
      wsl_setCookie("ad_timer_" + wsl_real_zone_id, wsl_ad_display_timer_duration);
    }
  }

  //Do we need to show the X?
  if (wsl_showXAfterSeconds > 0 && wsl_ad_display_timer_duration >= wsl_showXAfterSeconds) {
    wsl_showCloseButton();
  }
}
function wsl_closeAdFrame(stay_closed_for_session) {
  if (typeof(stay_closed_for_session) != "undefined" && stay_closed_for_session == 1) {
    //alert("Banner will stay closed for the duration of this session");
    wsl_setCookie("ad_close_clicked", 1, 'session');
  }

  var ad_container = document.getElementById('wsl_zone_container_' + wsl_real_zone_id);
  var spacer_container = document.getElementById('wsl_zone_spacer_' + wsl_real_zone_id);

  if (ad_container) {
    ad_container.style.display="none";
    wsl_reset_timer();
    if (wsll_add_spacer == 1 && spacer_container) { //If we're using a spacer div
      spacer_container.style.display = ad_container.style.display;
    }
  }

  //alert('Closed zone ' + wsl_real_zone_id);
}

function wsl_reset_timer() {
  clearInterval(wsl_ad_display_timer);
  duration_in_ms = 0;
}

function wsl_showCloseButton() {
  var closeDiv = document.getElementById('wsl_close_div');
  if (closeDiv) {
  } else {
    var ad_container = document.getElementById('wsl_zone_container_' + wsl_real_zone_id);

    newDiv = document.createElement('div');
    newDiv.id = 'wsl_close_div';
    newDiv.style.zIndex = 9999;
    newDiv.style.width = '20px';
    newDiv.style.height = '20px';
    newDiv.style.textAlign = 'center';
    newDiv.style.backgroundColor = '#dddddd';
    newDiv.style.position = 'absolute';
    newDiv.style.top = '5px';
    newDiv.style.right = '15px';

    closeX = document.createElement('a');
    closeX.href = 'javascript:wsl_closeAdFrame(1)';
    closeX.innerHTML = '<img src="http://advinea.s3.amazonaws.com/x_small.png" style="border: 0px;">';
    closeX.style.width = '20px';
    closeX.style.height = '20px';
    closeX.style.display = 'block';
    closeX.style.color = '#444';

    newDiv.appendChild(closeX);
    ad_container.appendChild(newDiv);
    closeDiv = document.getElementById('wsl_close_div');
  }

}

function wsl_recordFinalImpression() {
  wsl_trackEvent("fin");
}

function wsl_recordImpression() {
  wsl_trackEvent("imp");
}

function wsl_recordAdClick() {
  wsl_trackEvent("clk");
}

function wsl_saveadstate (value) {
  wsl_setCookie("ad_state", value);
}

function wsl_getadstate () {
  return wsl_getCookie("ad_state");
}

function wsl_setCookie(c_name,value, expiration_secs) {
  if (!value) {
    value = '';
  }
  if (!expiration_secs) {
    expiration_secs = 10;
  }

  c_name += "_" + wsl_real_zone_id;
  now=new Date();
  expiration = new Date(now.valueOf() + expiration_secs * 1000);

  if (expiration_secs == "session") {
    document.cookie = c_name+ "=" + escape(value) + "; path=/";
  } else {
    document.cookie = c_name+ "=" + escape(value) + "; expires=" + expiration.toUTCString() + "; path=/";
  }
}

function wsl_getCookie(c_name) {
  c_name += "_" + wsl_real_zone_id;
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}

function wsl_loadAd() {
  /*
  var url = 'http://localhost:9292?zoneid=' + wsl_zone_id + '&callback=adCallback&cachebust=' + (new Date).valueOf();

  var JSONPscript = document.createElement("script");
  JSONPscript.id = 'adLoaderScript';
  JSONPscript.setAttribute("src", url + "&callback=adCallback');
  JSONPscript.setAttribute("type","text/javascript");
  document.body.appendChild(JSONPscript);
  */

  fcap_impressions = wsl_getCookie('fcap_impressions');
  fcap_impressions = fcap_impressions.replace(/#/g, '%23');
  wsl_JSONP.get(wsl_ads_url, {zoneid:wsl_real_zone_id, cachebust:(new Date).valueOf(), fcap_impressions: fcap_impressions}, function(data){
    if (data) {
      wsl_resume_time_from_cookie = 0; //We're showing a new ad; reset the cookie timer whether or not this one has a duration of its own
      wsl_receivedAdData(data);
    } else {
      /*alert('No ad on zone ' + wsl_real_zone_id + ' closing ad frame');*/
      wsl_closeAdFrame();
    }
  });
}

function wsl_receivedAdData(data) {
  json_data = JSON.stringify(data);
  wsl_setCookie("ad_data_" + wsl_real_zone_id, json_data, 120);
  wsl_setCookie("fcap_impressions", data.fcap_impressions, 86400);

  format_group = data.adunit_format_group_id;
  wsl_campaign_id = data.campaign_id;
  wsl_line_id = data.campaign_line_id;
 
  wsl_showBrandlineAd(wsl_real_zone_id, data, wsl_event_url, wsl_swfLoadCallback);
}

function wsl_swfLoadCallback(e) {
  if (e.success == true) {
    //If we were successful in loading the flash creative..
    wsl_did_load_flash = 1;
  } else {
    //The flash creative was NOT loaded (i.e. no flash support).
    // If there's a static ad present, directly call the 'creative_loaded' function to start our countdown timer.
    // Otherwise, just close the ad frame.
    if (document.getElementById('wsl_static_creative')) wsl_flash_creative_loaded();
    else wsl_closeAdFrame();
  }
}
function wsl_creativeDurationReached() {
  //Record a final impression for this ad
  wsl_recordFinalImpression();
  
  //Stop the ad from playing

  //Load up a new ad
  wsl_loadAd();
}

function wsl_trackEvent(type) {
  if (!type || (type != "imp" && type != "fin" && type != "clk")) return;
  params = {}
  params['t'] = type;
  params['c'] = wsl_campaign_id;
  params['l'] = wsl_line_id;
  params['z'] = wsl_real_zone_id;
  params['cachebust'] = (new Date).valueOf();

  var trackUrl = "";
  for (p in params) {
    trackUrl = trackUrl + escape(p) + "=" + escape(params[p]) + "&";
  }
  trackUrl = trackUrl.substr(0,trackUrl.length-1);
  trackUrl = wsl_event_url + "/track.gif?" + trackUrl;
  // Temporary image element to request the tracking image
  var eventImg;
  if (type == "fin") {
    eventImg = document.getElementById('wsl_event_fin');
  } else {
    eventImg = document.getElementById('wsl_event');
  }
  eventImg.setAttribute("src", trackUrl);
}

function wsl_windowIsTooNarrowForAd() {
  var width = wsl_getWindowSize().width;
  //alert("Width is: " + width);
  if (width <= 600) {
    return true;
  } else {
    return false;
  }
}

function wsl_closeWindowIfTooNarrow() {
  if (wsl_windowIsTooNarrowForAd()) {
    wsl_closeAdFrame();
  }
}

//Cross browser dimension getter
//usage: var width = wsl_getWindowSize().width;
//source: http://jibbering.com/faq/#getWindowSize

var wsl_getWindowSize = (function() {
  var docEl = document.documentElement,
      IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;

  // Used to feature test Opera returning wrong values 
  // for documentElement.clientHeight. 
  function isDocumentElementHeightOff () { 
      var d = document,
          div = d.createElement('div');
      div.style.height = "2500px";
      d.body.insertBefore(div, d.body.firstChild);
      var r = d.documentElement.clientHeight > 2400;
      d.body.removeChild(div);
      return r;
  }

  if (typeof document.clientWidth == "number") {
     return function () {
       return { width: document.clientWidth, height: document.clientHeight };
     };
  } else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
      var b = document.body;
      return function () {
        return { width: b.clientWidth, height: b.clientHeight };
      };
  } else {
      return function () {
        return { width: docEl.clientWidth, height: docEl.clientHeight };
      };
  }
})();


//Lightweight JSONP fetcher - www.nonobtrusive.com
var wsl_JSONP = (function(){
	var counter = 0, head, query, key, window = this;
	function load(url) {
		var script = document.createElement('script'),
			done = false;
		script.src = url;
		script.async = true;

		script.onload = script.onreadystatechange = function() {
			if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
				done = true;
				script.onload = script.onreadystatechange = null;
				if ( script && script.parentNode ) {
					script.parentNode.removeChild( script );
				}
			}
		};
		if ( !head ) {
			head = document.getElementsByTagName('head')[0];
		}
		head.appendChild( script );
	}
	function jsonp(url, params, callback) {
		query = "?";
		params = params || {};
		for ( key in params ) {
			if ( params.hasOwnProperty(key) ) {
				query += key + "=" + params[key] + "&";
			}
		}
		var jsonp = "json" + (++counter);
		window[ jsonp ] = function(data){
			callback(data);
			window[ jsonp ] = null;
			try {
				delete window[ jsonp ];
			} catch (e) {}
		};
 
		load(url + query + "callback=" + jsonp);
		return jsonp;
	}
	return {
		get:jsonp
	};
}());

function wsl_loadScript(url, callback) {
    // adding the script tag to the head as suggested before
   var head= document.getElementsByTagName('head')[0];
   var script= document.createElement('script');
   script.type= 'text/javascript';
   script.src= url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = function() {
    if (this.readyState == 'complete' || this.readyState == 'loaded') {
        callback();
      }
    }
   script.onload = callback

   // fire the loading
   head.appendChild(script);
}

function wsl_addInnerContainer(zone_id) {
  var ad_container = document.getElementById('wsl_zone_container_' + zone_id);
  var inner_container = document.getElementById('wsl_zone_container_inner_' + zone_id);
  if (!inner_container) {
    ad_container.innerHTML = '<div id="wsl_zone_container_inner_' + zone_id + '"></div>';
  }
}

function wsl_setIE6Positions() {
  var ad_container = document.getElementById('wsl_zone_container_' + wsl_real_zone_id);
  var spacer_container = document.getElementById('wsl_zone_spacer_' + wsl_real_zone_id);

  if (wsl_placement == "top") {
    ad_container.style.top = 0;
  } else {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    //On pages where the <body> is shorter than the <html> tag, we need to use the lesser of (scrollTop + clientHeight) and document.body.offsetHeight
    if (document.body.offsetHeight > 0 && document.body.offsetHeight < (scrollTop + clientHeight)) {
      ad_container.style.top = document.body.offsetHeight - ad_container.clientHeight + 'px';
    } else {
      ad_container.style.top = scrollTop + (clientHeight - ad_container.clientHeight);
//alert('normal layout at ' + scrollTop + ' + ' + clientHeight + ' - ' + ad_container.clientHeight + ' = ' + ad_container.style.top);
    }
  }
  
}

function wsl_showBrandlineAd(zone_id, data, wsl_event_url, wsl_swfLoadCallback) {
  var ad_container = document.getElementById('wsl_zone_container_' + zone_id);
  var spacer_container = document.getElementById('wsl_zone_spacer_' + zone_id);

  ad_container.style.zIndex = "999";
  ad_container.style.display = '';

  var ad_url = data.p1;
  var ad_static_url = data.p2;
  var ad_min_height = data.p3;
  if (ad_min_height == 0 || !ad_min_height) { //Make sure there's a min height so at least something shows up if they forgot to enter one
    ad_min_height = 100;
  }
  var flashvars = {};
  var params = {};
  var attributes = {};

  wsl_clickURLFlash = wsl_event_url + "?type%3Dclk%26r=" + escape(data.adunit_target_url);
  //wsl_clickURLStatic = wsl_event_url + "?type=clk&r=" + escape(data.adunit_target_url);
  wsl_clickURLStatic = wsl_event_url + "?t=clk&c=" + data.campaign_id + "&l=" + data.campaign_line_id + "&z=" + zone_id + "&r=" + escape(data.adunit_target_url);
  if (data.adunit_target_frame) wslClickTargetFrame = data.adunit_target_frame;
  params.allowscriptaccess = "always";
  params.loop = "false";
  params.wmode = "opaque";

  if (ad_static_url && ad_static_url.length > 0) {
    static_ad_code = '<a id="wsl_static_creative_link" href="' + wsl_clickURLStatic + '"><img id="wsl_static_creative" style="border:0px;" /></a>';
    ad_container.innerHTML = '<div style="text-align:center;">' + static_ad_code + '</div>';

    var static_creative = document.getElementById('wsl_static_creative');
    static_creative.style.height = ad_min_height + 'px';
    document.getElementById("wsl_static_creative_link").onclick = function() {wsl_ad_clicked(); return false;};
    if (!ad_url || ad_url.length == 0) {
      // If no flash creative, then just go with the static ad impressions.  Otherwise, swfobject callback will take care of it.
      // Do this in separate run loop for IE timer continuation to work.
      static_creative.onload = function() {setTimeout(wsl_flash_creative_loaded, 0);};
    }
    // Set image src after setting onload so it'll fire for cached images.
    static_creative.src = ad_static_url;
  }

  //Set the duration value that we want to time...
  if (data.adunit_duration && data.adunit_duration > 0) {
    duration_in_ms = data.adunit_duration * 1000;
  }
  if (data.zone_p2 && data.zone_p2 > 0) {
    wsl_showXAfterSeconds = data.zone_p2;
  }
  if (data.zone_p1 && data.zone_p1 == "top") {
    wsl_placement = "top";
  }

  /* Place the spacer in the appropriate spot (either top or bottom) */
  var spacer_element = spacer_container.parentNode.removeChild(spacer_container);
  if (wsl_placement == "top") {
    document.body.insertBefore(spacer_element, document.body.childNodes[0]);
  } else {
    document.body.insertBefore(spacer_element, null);
  }

  /* Now load in the flash creative */
  var swf_width = '100%';
  var swf_height = '100%';

  var ie_version = wsl_getInternetExplorerVersion();

  if(ie_version >= 6.0 && ie_version < 7.0) {
    ad_container.style.width = '100%';
    ad_container.style.height = ad_min_height + 'px';
    ad_container.style.position = 'absolute';
    if (wsl_placement == "top") {
      ad_container.style.top = '0px';
    } else {
      ad_container.style.bottom = '0px';
    }
    ad_container.style.left = '0px';

    window.onscroll = wsl_setIE6Positions;
    window.onresize = wsl_setIE6Positions;

    /**Because the ad div isn't properly positioned in IE6, we also need to rip it out and put it right before/after the body.
    Otherwise it could be constrained by elements that contain it.
    */
    var ad_element = ad_container.parentNode.removeChild(ad_container);
    if (wsl_placement == "top") {
      document.body.insertBefore(ad_element, document.body.childNodes[0]);
    } else {
      document.body.insertBefore(ad_element, null);
    }

  } else {
    ad_container.style.width = '100%';
    ad_container.style.height = ad_min_height + 'px';
    ad_container.style.position = 'fixed';
    if (wsl_placement == "top") {
      ad_container.style.top = '0px';
    } else {
      ad_container.style.bottom = '0px';
    }
    ad_container.style.left = '0px';
  }

  if (ad_url && ad_url.length > 0) {
    swfobject.removeSWF('wsl_zone_container_inner_' + zone_id);
    wsl_addInnerContainer(zone_id);
    swfobject.embedSWF(ad_url, 'wsl_zone_container_inner_' + zone_id, swf_width, swf_height, '6.0.0', "expressInstall.swf", flashvars, params, attributes, wsl_swfLoadCallback);
  }

  if (wsll_add_spacer == 1) {
    spacer_container.style.position = 'static';
    if (wsl_placement == "top") {
      spacer_container.style.top = '0px';
    } else {
      spacer_container.style.bottom = '0px';
    }
    spacer_container.style.display = ad_container.style.display;
    spacer_container.style.width = ad_container.style.width;
    spacer_container.style.height = ad_container.style.height;
    spacer_container.style.clear = "both";
  }
}

//JSON Parser from json.org
if(!this.JSON){this.JSON={}}(function(){function f(n){return n<10?'0'+n:n}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key)}if(typeof rep==='function'){value=rep.call(holder,key,value)}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null'}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null'}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' '}}else if(typeof space==='string'){indent=space}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify')}return str('',{'':value})}}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j}throw new SyntaxError('JSON.parse')}}}());

function wsl_getInternetExplorerVersion() {
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function wsl_fix_youtube_flash() {
  var iframes = document.getElementsByTagName('iframe');
  for (i = 0; i < iframes.length; i++) {
    iframe = iframes[i];

    if (iframe.src.substr(0, 22) == "http://www.youtube.com" || iframe.src.substr(0, 18) == "http://youtube.com") {
      if (iframe.src.match(/wmode=/)) {
        //An wmode parameter is already specified in the url; don't try to add one
      } else {
        if (iframe.src.match(/\?/)) {
          iframe.src = iframe.src + "&wmode=opaque";
        } else {
          iframe.src = iframe.src + "?wmode=opaque";
        }
      }
    }
  }
}

function wsl_fix_flash() {
    // loop through every embed tag on the site
    var embeds = document.getElementsByTagName('embed');
    for (i = 0; i < embeds.length; i++) {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if (embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
                new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='opaque'");
            // add a new wmode parameter
            else
                new_embed = html.replace(/<embed\s/i, "<embed wmode='opaque' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin', new_embed);
            embed.parentNode.removeChild(embed);
        } else {
            // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
            new_embed = embed.cloneNode(true);
            if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')
                new_embed.setAttribute('wmode', 'opaque');
            embed.parentNode.replaceChild(new_embed, embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementsByTagName('object');
    for (i = 0; i < objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if (object.outerHTML) {
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
                new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='opaque' />");
            // add a new wmode parameter
            else
                new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='opaque' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            for (j = 0; j < children.length; j++) {
                try {
                    if (children[j] != null) {
                        var theName = children[j].getAttribute('name');
                        if (theName != null && theName.match(/flashvars/i)) {
                            new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
                        }
                    }
                }
                catch (err) {
                }
            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin', new_object);
            object.parentNode.removeChild(object);
        }
    }
}


function wsl_ad_main() {
  close_clicked_cookie = wsl_getCookie("ad_close_clicked");
  if (close_clicked_cookie == 1) {
    return;
  }

  if (!wsl_ready) {
    wsl_ready = true;

    if (wsll_fix_youtube_wmode == 1) {
      wsl_fix_youtube_flash();
    }

	if (wsl_windowIsTooNarrowForAd()) {
      return;
    }

    //document.write('<div id="wsl_zone_container_' + wsl_real_zone_id + '" style="display: none;"></div>');
    var zoneContainer = document.getElementById('wsl_zone_container_' + wsl_real_zone_id);
    wsl_createEventElements();
  
    //When we resize the window, call this function to see if we should close the ad:
    window.onresize = function() {
      wsl_closeWindowIfTooNarrow();
    }

    var resume_timer = wsl_getCookie("ad_timer_" + wsl_real_zone_id);
    var resume_creative_data = wsl_getCookie("ad_data_" + wsl_real_zone_id);
    if (resume_timer > 0 && resume_creative_data.length > 0) {
      //We need to resume from an existing creative.
      wsl_resume_time_from_cookie = resume_timer;
      var data = JSON.parse(resume_creative_data);
      wsl_receivedAdData(data);
    
    } else {
      //We need to load up a new creative
      wsl_loadAd();
    }
  }
}

//Print out an ad container for this zone at the spot the tag was included in the html
document.write('<div id="wsl_zone_container_' + wsl_real_zone_id + '" style="display: none;"></div>');
if (wsll_add_spacer == 1) {
  document.write('<div id="wsl_zone_spacer_' + wsl_real_zone_id + '" style="display: none;"></div>');
}

// The DOM ready check for Internet Explorer (approach borrowed from jQuery).
function wsl_doScrollCheck() {
  if (wsl_ready) return;
  try {
    // If IE is used, use the trick by Diego Perini - http://javascript.nwbox.com/IEContentLoaded/
    document.documentElement.doScroll("left");
  } catch(e) {
    setTimeout("wsl_doScrollCheck()", 1);
    return;
  }
  // and execute any waiting functions
  wsl_ad_main();
}


// Wait until the DOM is ready before starting (approach borrowed from jQuery).
if (document.readyState == "complete") {
  // If the document is already ready at this point, call our function straightaway
  wsl_ad_main();
} else if (document.addEventListener) {
  // Use the handy event callback
  document.addEventListener("DOMContentLoaded", wsl_ad_main, false);
  // Fallback to window.onload, that will always work
  window.addEventListener("load", wsl_ad_main, false);
} else if (document.attachEvent) {
  // ensure firing before onload, maybe late but safe for iframes
  document.attachEvent("onreadystatechange", wsl_ad_main);
  // Fallback to window.onload, that will always work
  window.attachEvent("onload", wsl_ad_main);
  // If IE and not a frame, continually check to see if the doument is ready
  var toplevel = false;
  try {
    toplevel = window.frameElement == null;
  } catch(e) {}
  if (document.documentElement.doScroll && toplevel) {
    wsl_doScrollCheck();
  }
}

//wsl_ad_main();

