// 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.howstuffworks.com/inline-player.htm';
	var winWidth  = 460;
	var winHeight = 496;
	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 = '<br><iframe  style="clear: both;"  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;
				}
			}
		}
	}
}

