/**** globals  ****/
var PEOPLE=window.PEOPLE||{};

var adConfig = new TiiAdConfig("3475.cbb");
adConfig.setCmSitename("cm.cbb");

/**** functions  ****/
function popup(url) {
	newwindow=window.open(url,'name','height=450,width=474');
	if (window.focus) {newwindow.focus()}
	return false;
}

function popEmailWin(pageURL,pageTitle,path,w,h){
    if(!pageURL){
        pageURL=document.URL;
    }
    if(pageURL.substring(pageURL.length-1)=="#"){
        pageURL=pageURL.substring(0,pageURL.length-1);
    }
    if(pageURL.match('/quizzes/')){
        pageURL=transformURL(pageURL);
    }
    if(!pageTitle){
        pageTitle=self.document.title;
    }
    if(pageTitle.indexOf('|')>0){
        pageTitle=pageTitle.substring(0,pageTitle.indexOf('|'));
    }
    if(!path){
        path='/people/emailfriend';
    }
    if(!w){
        w=460;
    }
    if(!h){
        h=450;
    }
    var formURL="http://cgi.pathfinder.com/cgi-bin/mail/mailurl2friend.cgi?path="+path+"&url="+pageURL+"&group=people&title="+escape(pageTitle);
    showCenteredPopup('emailpop',formURL,'scrollbars=1',w,h);
    return false;
}

var __eventListeners = [];//eventlistener functions, http://ajaxcookbook.org/

function addListener(instance, eventName, listener) {
    var listenerFn = listener;
    if (instance.addEventListener) {
        instance.addEventListener(eventName, listenerFn, false);
    } else if (instance.attachEvent) {
        listenerFn = function() {
            listener(window.event);
        };
        instance.attachEvent("on" + eventName, listenerFn);
    } else {
        //throw new Error("Event registration not supported");
    }
    var event = {
        instance: instance,
        name: eventName,
        listener: listenerFn
    };
    __eventListeners.push(event);
    return event;
}

function removeEventListener(event) {
    var instance = event.instance;
    if (instance.removeEventListener) {
        instance.removeEventListener(event.name, event.listener, false);
    } else if (instance.detachEvent) {
        instance.detachEvent("on" + event.name, event.listener);
    }
    for (var i = 0; i < __eventListeners.length; i++) {
        if (__eventListeners[i] == event) {
            __eventListeners.splice(i, 1);
            break;
        }
    }
}

function unregisterAllEvents() {
    while (__eventListeners.length > 0) {
        removeEventListener(__eventListeners[0]);
    }
}

function makeRequest(url,e) {
	var httpRequest;
	
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/html');
			// See note below about this line
		}
	} 
	else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
	}
	
	if (!httpRequest) {
		throw new Error("Giving up. Cannot create an XMLHTTP instance");
		return false;
	}
	httpRequest.onreadystatechange = function() { writeContent(httpRequest,e); };
	httpRequest.open('GET', url, true);
	httpRequest.send('');
}

function writeContent(httpRequest,e) {
	if (httpRequest.readyState == 4) {
		if (httpRequest.status == 200) {
			document.getElementById(e).innerHTML = httpRequest.responseText;
		} else {
			throw new Error("There was a problem with the httpRequest.");
		}
	}
}

function tii_callFunctionOnWindowLoad (functionToCall)
{
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener ('load', functionToCall, false);
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener ('load', functionToCall, false);
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent ('onload', functionToCall);
  }
  else
  {
    var oldFunctionToCall = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = functionToCall;
    }
    else
    {
      window.onload = function ()
      {
        oldFunctionToCall ();
        functionToCall ();
      };
    }
  }
}

//	builds the embeddable Brightcove player
var buildEmbeddedBrightcovePlayer = function(videoID,chann,peoplechann,packageid) {
	var config = new Array();
	config["videoId"] = videoID;
	if(!chann){ var chann = ""; }
	if(!peoplechann){ var peoplechann = ""; }
	if(!packageid){ var packageid = ""; }
	config["additionalAdTargetingParams"] = ';chan='+chann+';pchan='+peoplechann+';pckge='+packageid;
	config["videoRef"] = null;
	config["lineupId"] = null;
	config["playerTag"] = null;
	config["autoStart"] = false;
	config["preloadBackColor"] = "#FFFFFF";
	config["width"] = 466;
	config["height"] = 402;
	config["playerId"] = 1803212252;
	createExperience(config, 8);
}

function buildBrightcovePlayer (videoID) {
	var config = new Array();
	config["videoId"] = videoID;
	config["videoRef"] = null;
	config["lineupId"] = null;
	config["playerTag"] = null;
	config["autoStart"] = false;
	config["preloadBackColor"] = "#FFFFFF";
	config["width"] = 300;
	config["height"] = 320;
	if(brightcovePlayerID == ""){
		config["playerId"] = 416421276;
	}else{
		config["playerId"] = brightcovePlayerID;
	}
	createExperience(config, 8);
	
}

var qVal;
function windowOnload(){ //use cross browser onload call to resolve cross-browser conflict, http://cross-browser.com/talk/onload_conflict.html

	//search input box listener: empty default value on click, reload if unchanged on blur, else leave as what user input
	qVal = window.document.getElementById('q').value;
	PEOPLE.listener = addListener(window.document.getElementById('q'), "click", function() {
		if(window.document.getElementById('q').value == qVal){ window.document.getElementById('q').value = ''; }
	});
	PEOPLE.listener = addListener(window.document.getElementById('q'), "blur", function() {
		if(window.document.getElementById('q').value === ''){ window.document.getElementById('q').value = qVal; }
	});
	
	//Partner Recirc function
	startRecircFeeds2();
	
	//add the top news content to #topNews
	//makeRequest('/topnews.inc','topNews');
	
}

/****  quigo  ****/
function tiiQuigoIsEnabled() {
	if (typeof(_tiiQuigoEnabled) == "boolean") {
		return _tiiQuigoEnabled;
	}
	return true;
}

function tiiQuigoWriteAd(pid, placementId, zw, zh, ps) {
	if (tiiQuigoIsEnabled()) {
		qas_writeAd(placementId, pid, ps, zw, zh, 'ads.adsonar.com');
	}
}

var MasterArray2 = new Array();
/* 	global Partner Recirc function */
	var PartnerRecirc2 = function(initialArray) {
		var arr = MasterArray2;
		var nextFeed;
		var lastFeed;
		var recircCallback = function(pos) {
			if (!document.getElementById) return;
			if (!document.getElementById(pos.id)) return;
			divID = pos.name.replace(/\./,'').replace(/ /,'');
			divHTML = '<div class="toutSectionWrapper">\n';
			divHTML += '<div class="toutSection">\n';
			divHTML += '<div id="' +divID+ '" class="tout recirc'+nextFeed+'">\n';
			divHTML += '	<h3><a href="'+pos.site+'" target="_blank"><img src="'+pos.image+'" alt="'+pos.name+'" /></a></h3>\n';
			divHTML += '	<div class="txtcont">\n';
			divHTML += '		<ul>\n';
			for (li = 0; li < pos.display; li++) {
				divHTML += '			<li><a href="'+pos.response[0][li].url+'" target="_blank">'+pos.response[0][li].title+'</a></li>\n';
			}
			divHTML += '		</ul>\n';
			divHTML += '	</div>\n';
			divHTML += '	<div class="tout seeAll">\n';
			divHTML += '	    <p class="more"><a href="'+pos.site+'" target="_blank">'+pos.cta+'</a></p>\n';
			divHTML += '	</div>\n';
			divHTML += '</div>\n';
			divHTML += '</div>\n';
			divHTML += '</div>\n';
			divHTML += '<hr />\n';
			divHTML = document.getElementById(pos.id).innerHTML + divHTML + '\n';
			document.getElementById(pos.id).innerHTML = divHTML;
		};
		var checkScript = function(pos) {
			var recircInt = setInterval(function() {
				var name = pos.name.replace(/\./,'').replace(/ /,'');
				if (feed) {
					pos.response = new Array(feed);
					feed = null; detachScript(name); recircCallback(pos);
					nextFeed++;
					if(nextFeed < lastFeed) { getStarted(nextFeed); };
					clearInterval(recircInt);
				}
			},500);
		};
		var detachScript = function(name) {
			elem = document.getElementById('recirc-'+name);
			elem.parentNode.removeChild(elem);
		};
		var attachScript = function(pos) {
			var name = pos.name.replace(/\./,'').replace(/ /,'');
			var script = document.createElement('script');
				script.setAttribute('type','text/javascript');
				script.setAttribute('language','javascript');
				script.setAttribute('id','recirc-'+name);
				script.setAttribute('src',pos.json);
			document.body.appendChild(script);
			checkScript(pos);
		};
		var getStarted = function(nextFeed) {
			var a = nextFeed;
			if (document.getElementById(arr[a].id)) {
				arr[a].callback = (arr[a].callback) ? arr[a].callback : recircCallback;
				arr[a].display = (arr[a].display) ? arr[a].display : 3;
				arr[a].cta = (arr[a].cta) ? arr[a].cta : 'More news at '+arr[a].name;
				attachScript(arr[a]);
			}
		};
		var init = function() {
			if (arr.length > 0) {
				nextFeed = 0;
				lastFeed = arr.length;
				getStarted(nextFeed);
			}
		};
		init();
	}


		
			
//	initialize Partner Recirc feeds; uses Global PartnerRecirc2 function
	var initializeGlobalRecirc = function() {
		if (!document.getElementById) return;
		if (!document.getElementsByTagName) return;
		var recircArray = {
			'recircs' : [
				{
					'id'		: 'leftcolumnrecirc',
					'feed' 		: [
						{
							'name'  	: 'OMG',
							'json' 		: 'http://www.people.com/people/static/json/omggoddess/feed.js',
							'site' 		: 'http://omg.yahoo.com/blogs/goddess',
							'image' 	: 'http://img2.timeinc.net/people/static/i/babies/header_omg.gif',
							'display'	: 3,
							'cta'		: 'More News on Celebrity Moms at Goddess'
						}
					]
				},{
					'id'		: 'leftcolumnrecirc2',
					'feed' 		: [
						{
							'name'  	: 'Momtourage.com',
							'json' 		: 'http://www.people.com/people/static/json/momtourage/feed.js',
							'site' 		: 'http://www.momtourage.com',
							'image' 	: 'http://img2.timeinc.net/people/static/i/babies/header_momtourage.gif',
							'display'	: 3,
							'cta'		: 'More Advice at Momtourage.com'
						}
					]
				}
			]
		};
		for (var a = 0; a < recircArray.recircs.length; a++) {
			var tempArray = new Array(recircArray.recircs[a]);
			var last = tempArray[0].feed.length;
			if (tempArray[0].type && tempArray[0].type == 'random') { 
				tempArray[0].feed.sort(function() {return 0.5 - Math.random();}); 
				last = tempArray[0].display;
			}
			for (var f = 0; f < last; f++) {
				var ids = tempArray[0].id.split(',');
				var thisID = (ids.length > 1) ? ids[f] : tempArray[0].id;
				tempArray[0].feed[f].id = thisID;
				MasterArray2.push(tempArray[0].feed[f]);
			}
		}
	}
	initializeGlobalRecirc();
//	start recirc feed process
	var startRecircFeeds2 = function() {
		var n = new PartnerRecirc2();
	}

//son of suckerfish hover state for IE, http://htmldog.com/articles/suckerfish/dropdowns/
PEOPLE.sfHover = function() {
	var sfEls = window.document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		};
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		};
	}
}; if (window.attachEvent) { window.attachEvent("onload", PEOPLE.sfHover); }

/****  window listeners  ****/
//window.onload = windowOnload;
tii_callFunctionOnWindowLoad(windowOnload);
window.onunload = unregisterAllEvents;