/* addUrlToFavorites.js */

function addFav(url, title){
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

/* makeHomePage.js */

function makeHomePage(domain) {
    if (!domain)
    	domain = "http://www.bowenwang.com.cn";

    if(navigator.appName == "Microsoft Internet Explorer" && (parseInt(navigator.appVersion) >= 4)) { // IE 4+
        document.body.style.behavior="url(#default#homepage)";
        document.body.setHomePage(domain);
    }
    else {
    	// anything else
        //sethp = window.open("/sethomepage.php", "sethp", "toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,width=500,height=300,alwaysRaised=yes,screenX=250,screenY=250,top=250,left=250,alwaysRaised=yes");
        window.location.href = 'http://money.bowenwang.com.cn/make-homepage.htm';
    }
}

/* action_thread.js */
//(c) 2007 HSW
// Author: michael squires

//Define class.
function Action_Thread (action, iterations, waitTime, runStart)
{
	this._threadId      = null;
	this._waitValue     = 10;
	this._thread        = null;
	this._action        = '';
	this._iterations    = 1;
	this._incIterations = 0;


	//Constructor
	this.__construct(action, iterations, waitTime, runStart);
}

//Static members
Action_Thread._threads   = new Array();
Action_Thread._threadInc = 0;


//Define instantiated members
Action_Thread.prototype.__construct = function (action, iterations, waitTime, runStart)
{
	//Create thread id for this object
	this._threadId = ++Action_Thread._threadInc;
	
	//Assign self reference to threads pool
	Action_Thread._threads[this._threadId] = this;
	
	this._action = action;
	
	if (typeof iterations != 'undefined')
	{
		this._iterations = iterations;
	}
	
	if (typeof waitTime != 'undefined')
	{
		this._waitValue = waitTime;
	}
	
	if (runStart == true)
	{
		this.run();	
	}
	
}

Action_Thread.prototype.setWait = function (waitValue)
{
	this._waitValue = (waitValue > 0 ? waitValue : this._waitValue);
}

Action_Thread.prototype.setIterations = function (iterations)
{
	this._iterations = (iterations > 0 ? iterations : this.iterations);	
}

Action_Thread.prototype.run = function ()
{
	if (this._thread == null)
	{
		this._incIterations = 0;
		this._thread = setInterval(this._buildAction(), this._waitValue);
		
		return true;
	}
	
	return false;
}

Action_Thread.prototype._buildAction = function ()
{
	var actionPrefix = '';
	var actionSuffix = '';
	if (this._iterations > 0)
	{
		actionPrefix = 'if(Action_Thread._threads[' + this._threadId + ']._incIteration()){ ';
		actionSuffix = ' }';
	}
	
	return actionPrefix + this._action + actionSuffix;
}

Action_Thread.prototype._incIteration = function ()
{
	if (this._iterations == 0)
	{
		return true;
	}
	
	++this._incIterations;
	
	if (this._incIterations > this._iterations)
	{
		this.kill();
		return false;
	}
	
	return true;
}

Action_Thread.prototype.kill = function ()
{
	clearInterval(this._thread);
	this._thread = null;
}


/* main.js */

// Start cookie handling functions

function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+"="+escape( value ) +
    ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// This function checks to see if the HSW cookie is set.  If so, it returns
// true. If not, false.
function getHSWCookie() {
  var results = document.cookie.match ( 'HSWCookie' + '=(.*?)(;|$)' );

  if (results) {
    return true;
  } else {
    return null;
  }
}

// If the HSWCookie is not set, then display the log in/register link.  If it
// is, then display the logout link.  This is used in the Opinion block of the
// left navbar.
function checkHSWCookie() {
  if (!getHSWCookie()) {
  	document.write('<li id="rccStatus">&nbsp;&nbsp;<a href="/login.php">Log In/Register</a></li>')
  }
  else {
    document.write('<li id="rccStatus">&nbsp;&nbsp;<a href="/logout.php">Log Out</a></li>');
  }
}

// End cookie handling


// A little Web 2.0 for ya...
function createRequestObject() {
	var ro;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		ro = new XMLHttpRequest();
	}
	return ro;
}

// Functions to handle pulling in cobranded headers if applicable
var cobrand = createRequestObject();
var cobrand_firstpageonly = false;

function sendCobrandRequest() {
	var ref = document.referrer;
	if(cobrand_firstpageonly != true) {
		var refcookie = getCookie('HSWPartner');
		if(refcookie != "" && refcookie != null && refcookie != undefined) {
			ref = refcookie;
		}
	}
	// Be sure we have a valid partner so we don't make unnecessary HTTP calls
	var partner = getPartner(ref);
	if(partner == "" || partner == undefined || partner == null) {
		return;
	}
	if(cobrand_firstpageonly != true) {
		if(refcookie == "" || refcookie == null || refcookie == undefined) {
			setCookie('HSWPartner', ref, '', '/', '.howstuffworks.com');
		}
	}
	var cobrand_url = 'cobrand.htm?partner='+partner;
	cobrand.open('get', cobrand_url);
	cobrand.onreadystatechange = handleResponse;
	cobrand.send(null);
}

function getPartner(ref) {
	if(ref.indexOf('www.forbestraveler.com') >= 0) {
		return 'forbestravel';
	} else {
		return '';
	}
}

function handleResponse() {
	switch(cobrand.readyState) {
		case 1:
		case 2:
		case 3:
			break;
		case 4:
			if(cobrand.responseText != '' && cobrand.responseText != null) {
				document.getElementById('coBrand').style.display='';
				document.getElementById('coBrandContents').innerHTML=cobrand.responseText;
			}
			break;
		default:
			break;
	}
}

// End cobrand code

// Function for in-page video player
function embedVideo(videofile) {
        var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage.php?pageID='+videofile+'" name="vidFrame" frameborder=0 width=420 hscroll=no vscroll=no height=410>Your Browser Does Not Support iFrames</iframe>';
        document.write(msg);
}
function embedVideoSmall(videofile) {
        var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage_s.php?pageID='+videofile+'" name="vidFrame" frameborder=0 width=225 hscroll=no vscroll=no height=195>Your Browser Does Not Support iFrames</iframe>';
        document.write(msg);
}
function embedVideoPlain(videofile) {
        var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage_plain.php?pageID='+videofile+'" name="vidFrame" frameborder="0" width="420" hscroll="no" vscroll="no" height="410">Your Browser Does Not Support iFrames</iframe>';
        document.write(msg);
}
function embedVideo280(videofile) {
        var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage_280.php?pageID='+videofile+'" name="vidFrame" frameborder=0 width=290 hscroll=no vscroll=no height=300>Your Browser Does Not Support iFrames</iframe>';
        document.write(msg);
}

// New video 2.0 javascript calls
function inPagePlayer (videoId, args)
{
	args = args ? args : {};
	
	var url       = 'http://videos.msquires5.howstuffworks.com/inline-player.htm';
	var winWidth  = 460;
	var winHeight = 520;
	var noSkin    = 0;

	options = new Array;
	options.push('videoId=' + videoId);

	if (args.noSkin)
	{
		options.push('noSkin=' + (args.noSkin ? noSkin = 1 : 0));
	}

	if (args.width != null)
	{
		options.push('width=' + args.width);
		
		if (noSkin)
		{
			winWidth = args.width;
		}
	}

	if (args.height)
	{
		options.push('height=' + args.height);
		
		if (noSkin)
		{
			winHeight = args.height;
		}
	}

	if (args.autostart)
	{
		options.push('autostart=' + (args.autostart ? 1 : 0));
	}

	var msg = '<iframe src="' +  url + '?' + options.join('&') + '" name="vidFrame" frameborder="0" width="' + winWidth + '" hscroll="no" vscroll="no" scrolling="no" height="' +  winHeight + '">'
	        + 'Your Browser Does Not Support iFrames'
	        + '</iframe>';

	document.write(msg);
}

function inject_code(str) {
	document.write(str);
}

function browserAcceptsCookies() {
	var HSW_acceptsCookies = false;
	if (document.cookie == '') {
		document.cookie = 'HSW_acceptsCookies=yes';
		if (document.cookie.indexOf('HSW_acceptsCookies=yes') != -1) {
			HSW_acceptsCookies = true;
		}
	}
	else {
		HSW_acceptsCookies = true;
	}
	return (HSW_acceptsCookies);
}

function recordStats(webpage,referer) {
}

function tsStats(parms) {
  var _bs = '<img height=1 width=1 border=0 src="http://www.howstuffworks.com/tsform.php?'+parms+'">';
  document.write(_bs);
}

function OpenWindow(url) {
	newwindow = window.open ("/" + url, 'HowStuffWorks', 'status=no,toolbar=no,location=no,menubar=no,scrollbars=yes,resizable=yes,width=485,height=675');
}

function OpenWindow2(url,h,w) {
	newwindow = window.open ("/" + url, 'HowStuffWorks', 'status=no,toolbar=no,location=no,menubar=no,scrollbars=no,resizable=no,width=' + w + ',height=' + h);
}

var RN = new String (Math.random());
var RNS = RN.substring(2,11);
//var RNS = "1290781908475";

function DisplayAds (sitepage, position, width, height)
{
	var oas = 'http://ad.howstuffworks.com/RealMedia/ads/';
	var oaspage = sitepage + '/1' + RNS + '@' + position;

	if (_version < 11) {
		document.write ('<A HREF="' + oas + 'click_nx.ads/' + oaspage + '" TARGET="_top"><IMG SRC="' + oas + 'adstream_nx.ads/' + oaspage + '" BORDER="0" WIDTH="' + width + '" HEIGHT="' + height + '"></a>');
	} else {
		document.write ('<SCRIPT LANGUAGE="JavaScript1.1" SRC="' + oas + 'adstream_jx.ads/' + oaspage + '">');
		document.write ('\<\!-- --\>');
		document.write ('\<\/SCRIPT\>');
		document.write ('\<\!-- --\>');
	}
}

function showImage(html)
{
  windowOps = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes," +
              "width=500,height=500,left=250,top=50";
  ImageWindow = window.open("","ImageWindow",windowOps);
  windowHTML = '<html><body><base href="http://www.howstuffworks.com/"><center><font face="arial,helvetica">' + html +
               '<p><font face="arial,helvetica">' +
               '<a href="javascript:window.close();">Click here</a> to close this window.</font></center>' +
               '</body></html>';
	self.ImageWindow.document.clear();
  self.ImageWindow.document.write(windowHTML);
	self.ImageWindow.focus();
	self.ImageWindow.document.close();
}

function tryIt(HTML)
{
  windowOps = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes," +
              "width=500,height=500,left=250,top=50";
  ImageWindow = window.open("","ImageWindow",windowOps);
  windowHTML = '<html><body>' + HTML +
               '<p><font face="arial,helvetica">' +
               '<A HREF="javascript:window.close();">Click here</a> to close this window.</font>' +
               '</body></html>';
  self.ImageWindow.document.clear();
  self.ImageWindow.document.write(windowHTML);
  self.ImageWindow.focus();
  self.ImageWindow.document.close();
}

function shopTI(url,lid) {
   if (url.indexOf("LINKIN_ID") == -1) {
      url="http://"+escape(url.substring(7))+"/LINKIN_ID-"+lid;
      }
   return url;
   }

function videoWin(id) {
    window.open('mediacenter/mcPlayerFull.php?vidID='+id,'mcPlayer','width=740,height=440,menubar=no,status=no,location=no,toolbar=no,scrollbars=yes,resizable=yes');
}

function getRccStatus(){

	var xmlhttp=false;

	try {
		xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
	} catch (e) {
		try {
			xmlhttp = new
			ActiveXObject('Microsoft.XMLHTTP');
    	} catch (E) {
			xmlhttp = false;
    	}
	}

	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}

	var file = '/rccStatus.php';
	xmlhttp.open('GET', file, true);

	xmlhttp.onreadystatechange=function() {

    	if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200 && xmlhttp.responseText){
				document.getElementById ("rccStatus").innerHTML = xmlhttp.responseText;
			}
        }

    }

	xmlhttp.send(null)
	return;
}

function D_findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function D_findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


// Locates a div, moves it to its parent's bottom right and
// displays it
function revealDiv (divID, parentID)
{
	this._timeout = 0;
	this._element = document.getElementById (divID);
	this._parent  = document.getElementById (parentID);
}

revealDiv.prototype.show = function ()
{
	this._clear ();
	var y    = D_findPosY (this._parent) + this._parent.clientHeight;
	var doc  = document.getElementById ('doc');
	var docX = D_findPosX (doc);

	this._element.style.top   = y;
	this._element.style.left  = (docX + doc.clientWidth - this._element.offsetWidth) + 'px';
	this._element.style.visibility = 'visible';
}

revealDiv.prototype.hide = function (divID)
{
	element = this._element;
	this._timeout = setTimeout (function () {
		element.style.visibility = 'hidden';
	}, 500);
}

revealDiv.prototype._clear = function ()
{
	if (this._timeout == 0)
		return;

	window.clearTimeout (this._timeout);
	this._timeout = 0;
}

/**************
RealMedia page manipulator.
This is a static class: no prototyping required
**************/
function realMediaPM () {}
//Static members
realMediaPM.cssRules    = (document.all ? 'rules' : 'cssRules');
realMediaPM.classChange = new Array('.header .nav', '.scrollerFeature', '.scrollerFeature .today');
//Static method changeColor
realMediaPM.changeColor = function (color)
{
	//Change base background
	document.body.style.background = color;
	for (var i = 0; i < realMediaPM.classChange.length; ++i)
	{
		for (var S = 0; S < document.styleSheets.length; S++)
		{
			for (var R = 0; R < document.styleSheets[S][realMediaPM.cssRules].length; R++)
			{
				if (document.styleSheets[S][realMediaPM.cssRules][R].selectorText == realMediaPM.classChange[i])
				{
					document.styleSheets[S][realMediaPM.cssRules][R].style['background'] = color;
				}
			}
		}
	}
}

/* button function */
$(document).ready(
	function(){
		$(".button, .buttonlg, .button_left").hover(
			function(){
				$(this).not(".disabled").addClass("hover");
			}, 
			function(){
				$(this).not(".disabled").removeClass("hover");
			});
	});



//ajax_ads.js

$(document).ready(fetchHSWIads);

function fetchHSWIads(){
	// check if there are any adds to fill...
	if ($('.hswiAd').length > 0)
	{
		//lets build a URL
		adCallLocation = 'http://orion.netwebfarm.com/www/delivery/spc.php';
		adDisplayConf = Math.floor(Math.random()*99999999) + "&amp;amp%3Bblock=1&amp;amp%3Bblockcampaign=1&amp;amp%3Bwithtext=1";
		charset = (document.charset ? '&amp;charset='+document.charset : (document.characterSet ? '&amp;charset='+document.characterSet : ''));
	
		//find all the zones
		adZones = '';
		$('.hswiAd').each(
			function(){
				if (adZones.length > 0) adZones += '|';
				adZones += $(this).attr("zoneid")	
			});
	
		//get the s variables from one on the zones
		adSource = $('.hswiAd:eq(0)').attr("source");
		adSource += 'cid='+ getCampaignId( ".bowenwang.com.cn" ) +';';
		adSource += 'refurl='+document.referrer.toLowerCase()+';';	
		//put all the pieces together
	
		urlToGetAds = adCallLocation + "?zones=" + adZones + "&source=" + adSource + "&" + adSource.replace(/;/g, "&") + "&ref=" + document.location.href + "&charset=" + charset + "&loc=" + document.location.href + "&r=" + adDisplayConf 
	
		//get the ads ans start watching
		$.getScript(urlToGetAds, placeHSWIads)
	}
}

function placeHSWIads(){
	if (typeof(waitForHSWIads) != 'undefined') clearTimeout(waitForHSWIads);
	if (typeof(OA_output) != "undefined"){
		$(".hswiAd").each(fillAdSpace);
	}else{	
		waitForHSWIads = setTimeout("placeHSWIads()", 500);
	}	
}

function gimmieAdByZone(zoneid){
	return OA_output[zoneid];	
}

function fillAdSpace(){
	//we should probably make this work so no matter what data we get it will function
	if (OA_output[$(this).attr("zoneid")]){	
		
		//setup the j object
		//need to get the values somewhere most likely a comment inside the ad
		j = new Object();
		j.html = OA_output[$(this).attr("zoneid")];
		if (j.html.search(/pegasus.netwebfarm.com/i) > 0){
			j.contenttype = "local";
		}else{
			j.contenttype = "remote";
		}
		
		ad = $(this);
		
		// Clean the ad of any child elements
		ad.empty();
		
		var oac = parseCmds(j.html);
		
		//these should be the sizes from the ad
		if (oac.ad.getValue("positionsize")){
			j.width = oac.ad.getValue("positionsize")['x']
			j.height  = oac.ad.getValue("positionsize")['y']
		}
		else if (oac.zone.getValue("positionsize"))
		{
			j.width = oac.zone.getValue("positionsize")['x'];
			j.height = oac.zone.getValue("positionsize")['y'];
		}
		else
		{
			return;
		}
		
		if (oac.zone.get("positionsize")) { // see if we have a positionsize comment 
			// get our width and height from j.html 
			var pw = Number(oac.zone.getValue("positionsize")['x']);
			var ph = Number(oac.zone.getValue("positionsize")['y']);

			// set initial sizes 
			ad.width(pw)
			  .height(ph)
			  .parent()
			  	.width(pw)
			  	.height(ph); // set the parent div's size 
				
			// the banner height may be different 
			var bh = Number(j.height);
			var bw = Number(j.width);

			// if they are not equal, we need to setup the clip areas 

			if ((pw != bw) || (ph != bh)) {
				ad.attr("bw", bw)
				  .attr("bh", bh)
				  .attr("pw", pw)
				  .attr("ph", ph)
				  .mouseover(function(){
						$(this).css({'clip': 'rect(0px ' + $(this).attr('bw') + 'px ' + $(this).attr('bh') + 'px 0px)'});
						var off = $(this).offset();
						var offset = {'left':off.left, 
									  'top':off.top, 
									  'right':off.left + parseInt($(this).attr('bw')), 
									  'bottom': off.top + parseInt($(this).attr('bh'))};
						var adId = '#' + $(this).attr('id');

						$('#doc').bind('mousemove', function(e){
							if (e.clientX < offset.left || e.clientX > offset.right || e.clientY < offset.top || e.clientY > offset.bottom) {
								$(adId).trigger('mouseout');
								$(this).unbind('mousemove');
							}
						});

				  })
				  .mouseout(function(){
						$(this).css({'clip': 'rect(0px ' + $(this).attr('pw') + 'px ' + $(this).attr('ph') + 'px 0px)'});
				  })
				  .parent()
				  	.css("z-index", "101");
			}

		}else{ 
			// otherwise just use the ad size 
			if (j.width.length && j.height.length){
				ad.width(Number(j.width))
				  .height(Number(j.height))
				  .parent()
				  	.width(Number(j.width))
				  	.height(Number(j.height)); // set the parent div's size 
			}
		}

		// should we hide the ad. 
		if (oac.zone.get("type") == 'float' 
				|| oac.ad.get("trans")
				|| oac.zone.get("trans"))
			ad.hide();

		// do we need a close button 
		if(oac.zone.get("type") == 'float')
			ad.append('<div class="closefloat" style="width:' + j.width + 'px;">FECHAR</div>')
			  .parent()
				.removeClass("hswiAdContainer")
				.addClass("hswiFloatingAdContainer");

		// place the ad 
		if (j.contenttype == "remote")	{ //must be HTML
			//var adframeId = "frame-" + ad.attr("id");
			//ad.append('<iframe id="' + adframeId + '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="javascript:parent.gimmieAdByZone(' + $(this).attr("zoneid") + ')" height="' + j.height + '" width="' + j.width + '"></iframe>');

			var adframeId = "frame-" + ad.attr("id");
			ad.append('<iframe id="' + adframeId + '" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="" height="' + j.height + '" width="' + j.width + '"></iframe>');
			adframe = $("#" + adframeId)[0].contentWindow;
			adframe.document.write('<html><head></head><body style="margin:0px;padding:0px;">');
			adframe.document.write(j.html);
			adframe.document.write('</body></html>');
			setTimeout('$("#' + adframeId + '")[0].contentWindow.document.close();', 10000);
		}else{
			ad.append(j.html);	
		}

			// if the ad isn't visible, we need to do something to make it that way
		if (ad.is(":hidden")){
			// if we have  show time we should automatically trigget the hide action
			var ah = (oac.ad.getValue("show"));

			// calculate how long to show the ad 
			var s = ((oac.ad.getValue("show")) ? oac.ad.getValue("show") * 1000 : 10000);

			// find possible transition
			var t = ((oac.ad.get("trans")) ? oac.ad.get("trans") : oac.zone.get("trans"));
			switch(t){
				case 'slide':
					// assign the right display for the close function 
					ad.children(".closefloat").click(function(){$(this).parent().parent().slideUp();});

					// create the display for the close function 
					tf = function(){if ($(this).is(":hidden")) $(this).slideDown("def", function(){if($(this).is(":visible")) setTimeout("$('#" + $(this).attr('id') + "').parent().slideUp()", s)});};
					break;
				case 'fade':
				default:
					// assign the right display for the close function 
					ad.children(".closefloat").click(function(){$(this).parent().parent().fadeOut();});

					// create the display for the close function 
					tf = function(){if ($(this).is(":hidden"))$(this).fadeIn("def", function(){ if($(this).is(":visible")) setTimeout("$('#" + $(this).attr('id') + "').parent().fadeOut()", s)});};
					break;	
			}

			/* need to make sure the load event for the window hasn't already fired.
		   		if it has, then go ahead a trigger the display */
			(typeof(adLoadComplete) != 'undefined') ? tf.call(ad) : ad.load(tf);
		}		
	}
}

/* OpenX Functions */

//Function to create a command set object.  This will parse all the commands found in
//txtToParse and store those commands in a command object set.
function parseCmds(txtToParse){
	var cmds = {zone:new openXCmd, ad:new openXCmd};
	re = /!--\s*(ZONE|AD):([^\-]*)\s*-->/g;
	if (txtToParse.match(re))
		$.each(txtToParse.match(re), function(){
			if (this.match(re)){
			//this is needed to work in ie6
			if (jQuery.browser.safari || jQuery.browser.msie || ( typeof(re) != 'function' && typeof(re) != 'object') )
				re =  /!--\s*(ZONE|AD):([^\-]*)\s*-->/g;
				var res = re.exec(this);
				if (res !== null) {
    				cmdtype = $.trim(res[1].toLowerCase());
    				// Only read a zone command once 
    				if (cmdtype != 'zone' || !cmds.zone.locked){
    					$.each(res[2].toLowerCase().split(":"), function(){
    						// seperate the values and commands 
    						var v = /([^ \(]*)(\(?.*\)?)/.exec($.trim(this));
    						v[2] = $.trim(v[2].replace(/^\((.*)\)$/, "$1"));

    						if (v[2].match(/([0-9]+)x([0-9])/i)){ // check if any of the values are xy coordinates 
    							v[2] = {x:v[2].split(/x/i)[0], y:v[2].split(/x/i)[1]}
    						}else if(v[2].match(/([^ \(]+)(\(.*\))/)){ // see if the have sub parameters 
    							var subi = v[2].match(/([^ \(]+)(\(.*\))/)
    							v[2] = {};
    							v[2][subi[1]]=subi[2].replace(/^\((.*)\)$/, "$1");
    						}

    						if (typeof(v[1]) != "undefined" && v[1].length > 0) cmds[cmdtype][v[1]] = v[2];
    					});

    					if (cmdtype.toLowerCase() == 'zone') cmds.zone.locked = true;
    				}// end zone dup check 
			    }
			}
		});

	return cmds;
}

//Class definition for one individual command
function openXCmd(){
	// get the name of the value 
	this.get = function(r){
		switch(typeof(this[r])){
			case 'string':
				return this[r];
				break;
			case 'object':
				for (var i in this[r])
					return i;
				break;
			default:
				return null;	
		}
	}

	// get the actual value 
	this.getValue = function(r){return ((typeof(this[r]) != 'undefined') ? this[r] : null);}
}

/* * * *
* Function used in Omniture JS to determin aid/cid from URL or cookie and set cookie accordingly
* * * */
/* Handle campaign tracking IDs */
function getCampaignId( cookieDomain )
{
        var campId = "";
        var campCookieName = "hswi_aid_cid";
        var campCookieDomain = cookieDomain;
        var campUrlVarKey = (window.location.search.search("aid") > -1 )? "aid" : (window.location.search.search("cid") > -1 )? "cid" : null;
        if (campUrlVarKey != null) // if 'aid' or 'cid' is found as the key to a URL variable
        {
                // get the value of that url variable
                queryString = window.location.search.substr(1,window.location.search.length).split("&");
                for (var i=0;i<queryString.length; i++)
                {
                        if (escape(unescape(queryString[i].split("=")[0])) == campUrlVarKey)
                        {
                                campId = queryString[i].split("=")[1];
                                // set a session cookie with the found cid/aid
                                document.cookie = campCookieName + "=" + escape(campId) + ";domain=" + cookieDomain + ";";
                        }
                }
        } else {
                // if neither 'aid' nor 'cid' is found as key to a URL variable, check for a cookie and get value from there if available
                if (document.cookie && document.cookie != '')
                {
                        var cookies = document.cookie.split(';');
                        for (var i = 0; i < cookies.length; i++)
                        {
                                var cookie = jQuery.trim(cookies[i]);
                                if (cookie.substring(0, campCookieName.length + 1) == (campCookieName + '='))
                                {
                                        campId = decodeURIComponent(cookie.substring(campCookieName.length + 1));
                                        break;
                                }
                        }
                }
        }
        return campId;
}

/*******
*HSWI rotator plugin
*******/
jQuery.fn.nextWrap = function(sel){
						if (this.next(sel).length > 0){
							return this.next(sel);
						}else{
							return this.siblings(sel).filter(":first");	
						}
					}
					
					jQuery.fn.prevWrap = function(sel){
						if (this.prev(sel).length > 0){
							return this.prev(sel);
						}else{
							return this.siblings(sel).filter(":last");	
						}
					}

					jQuery.HSWI_rotate = {
						items:[], 
						executeGotoNextSlideInScope:function(pos){
							jQuery(this.items[pos].ele).HSWI_rotate('next');
						},
						setRotateInt:function(ele, delay){
							return setInterval("jQuery.HSWI_rotate.executeGotoNextSlideInScope(" + ((typeof(ele) == 'object') ? this.findItemPos(ele) : ele) + ")", delay)	
						},
						clearRotateInt:function(ele){
							return clearInterval(this.items[this.findItemPos(ele)].timer)
						},
						findItemPos:function(ele){
							for(var i = 0; i < this.items.length; i++)
								if (this.items[i].ele = ele)
									return i;
							
							return -1;
						},
						addRestart:function(ele, dur){
							var pos = this.findItemPos(ele);
							if (this.items[pos].restart)
								clearTimeout(this.items[pos].restart);
							this.items[pos].restart = setTimeout("jQuery.HSWI_rotate.setRotateInt(" + pos +  ", 5000)", dur)	
						},
						addItem:function(e){
							pos = this.items.length
							this.items[pos] = {ele:e,timer:'',restart:''};
							this.items[pos].timer = this.setRotateInt(e, 5000);
						}
					};
					
					jQuery.fn.HSWI_rotate = function(pos){
						if (pos != ''){
							switch(pos){
								case 'next':
									jQuery(this)
										.children(".rotatorData:visible")
											.hide()
											.nextWrap(".rotatorData")
												.show();
									break;
								case 'prev':
									jQuery(this)
										.children(".rotatorData:visible")
											.hide()
											.prevWrap(".rotatorData")
												.show();
									break;
								case 'first':
									jQuery(this)
										.children(".rotatorData:visible")
											.hide()
											.filter(":first")
												.show();
									break;
								case 'last':
									jQuery(this)
										.children('.rotatorNav')
											.removeClass("current")
										.children(".rotatorData:visible")
											.hide()
											.filter(":last")
												.show();
									break;	
							}
							
							jQuery(this)
								.children(".rotatorNav")
									.children()
										.removeClass("current")
										.eq(jQuery(this).children(".rotatorData").index(jQuery(this).children(".rotatorData:visible")))
											.addClass("current")
							
						}
						
						this.init = function(){
							if(!jQuery(this).attr("HSWIrotate")){
								jQuery(this)
										.attr("HSWIRotate", "1")
										.children('.rotatorNav')
											.children()
												.click(
													function(){
														//clear the timeout for this function
														var rotate = jQuery(this).parents("[HSWIRotate]");
														jQuery.HSWI_rotate.clearRotateInt(rotate);
														jQuery(this)
															.siblings()
																.removeClass("current")
																.end()
															.addClass("current")
															.parent()
																.siblings(".rotatorData")
																	.hide()
																	.eq(jQuery(this).parent().children().index(this))
																		.show();
														jQuery.HSWI_rotate.addRestart(rotate, 20000);
													});
								jQuery.HSWI_rotate.addItem(this);
							}
						}
						
						
						return this.each(this.init);
					}
                    
/*******
*HSWI random article tool tip
*******/
function delayedOut(){
    if($('#randomToolTip.mouseover').length){
    
    }else{
        $('#randomToolTip').hide()
    }
    
}
function hideToolTip(){ $("#randomToolTip").removeClass('mouseover');setTimeout(delayedOut, 400)}
function showToolTip(){  $('#randomToolTip').show();$("#randomToolTip").addClass('mouseover'); }
function overToolTip(){  $("#randomToolTip").addClass('mouseover'); }
function  outToolTip(){  $("#randomToolTip").removeClass('mouseover');  }


$(document).ready(function(){

$("#random").bind('mouseover.tooltip', showToolTip);
$("#random").bind('mouseout.tooltip', hideToolTip);
$("#randomToolTip").bind('mouseover.tooltip', overToolTip);
$("#randomToolTip").bind('mouseout.tooltip', function(){outToolTip(); hideToolTip();});
});
