var d = document;
var noPop = false;
var gV = new Array();
var linkid;

/* general/utility */

function prosper_popUp(page, name, w, h, scroll) { // used for all pop up windows
	page = page.split(" ").join("%20");
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	//var resizable = false;
	winprop  = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=yes';
	win = window.open(page, name, winprop,'S_PROSPER');
	if(win)win.focus();
}


function prosper_popUpOrig(page, name, w, h, scroll) { // used for all pop up windows - used on a few download pages and trump checkout, needs to be removed with the new code is in place (Aaron)
	prosper_popUp(page, name, w, h, scroll)
}

function prosper_exitPage(newURL,hideFor,ex){ // this function is to be called when leaving a page, but not continuing on our site.  This gives us one place to change from popup to takeover to whatever
	//location.href = newURL;
	
	/* popup version... commented out for test*/
	ex = prosper_optionalVars(ex); // break the extras into a useable array
	if (noPop!=true && !hideFor.inArray(''+linkid)){
		if(ex.f)sm.v.f = parseInt(ex.f);
		var n = ex.winName ? ex.winName : 'consult'; // win name
		var h = ex.h ? ex.h : '790'; // win height
		var w = ex.w ? ex.w : '590'; // win width
		prosper_popUp(newURL, n, h, w, "yes");
	}
	
}


var popupsOk=false;
function prosper_checkPop(){ // check if we can use popups
	var testwin = window.open('/images/spacer.gif','testwin','height=1,width=1,top=8000,left=8000','S_PROSPER');
	if (testwin) {popupsOk=true;testwin.close();}
}

function prosper_printThis() {
	var ua = navigator.userAgent.toLowerCase();
	var is_mac = ua.indexOf('mac') > 0;
	if (is_mac) { alert('To print:\n\nUse Command + P. on your keyboard\n') }
	else { print(); } 
}


/* Layer specific utilities */
function prosper_findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	return curleft;
}

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

// from http://www.quirksmode.org/viewport/compatibility.html
function prosper_getScroll(){ // returns how far down we are scrolled
	if (window.innerHeight){
		  pos = window.pageYOffset
	} else if (document.documentElement && document.documentElement.scrollTop){
		pos = document.documentElement.scrollTop
	} else if (document.body){
		  pos = document.body.scrollTop
	}
	return pos
}

// from http://www.quirksmode.org/viewport/compatibility.html
function prosper_getHeight(){ // returns the height of the viewing area
	var y;
	if (self.innerHeight){ // all except Explorer
		y = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight){	// Explorer 6 Strict Mode
		y = document.documentElement.clientHeight;
	} else if (document.body){ // other Explorers
		y = document.body.clientHeight;
	}
	return y;
}

// find the parent node that has the passed class name
// cn = curNode
function prosper_findParentByClass(cn,theClass){
	while(cn.parentNode){
		curClass = " "+cn.parentNode.className+" "; // add spaces to make sure we don't find "fool" when looking for "foo"
		if (curClass.indexOf(" "+theClass+" ") != -1){
			return cn.parentNode;
		}
		cn = cn.parentNode; // move up a node
	}
	return false;
}

// ln = layerName
function prosper_showHide(ln){ // shows and hides a given layer
	if (d.getElementById){
		if(!ln.nodeName) ln = d.getElementById(ln);
		
		curClass = " "+ln.className + " ";
		if(curClass.indexOf(" seen ") != -1){
			prosper_hideLayer(ln);
		} else {
			prosper_showLayer(ln);
		}
		return;
	}
}

// ln = layerName
function prosper_showLayer(ln){ // shows a given layer
	if(!ln.nodeName) ln = d.getElementById(ln);
	if(ln){
		ln.style.display = ''; // left for legacy hardcoded versions
		prosper_addClass(ln,'seen');
		prosper_delClass(ln,'hidden');
		return;
	}
}

// ln = layerName
function prosper_hideLayer(ln){ // hides a given layer
	if(!ln.nodeName) ln = d.getElementById(ln);
	if(ln){
		prosper_delClass(ln,'seen');
		prosper_addClass(ln,'hidden');
		return;
	}
}

/* Manipulate Classes */
// ln = layerName
// oc = Old Class
// cc = Current Class
function prosper_delClass(ln,oc){
	if(!ln.nodeName) ln = d.getElementById(ln);
	if (ln){
		cc = " "+ln.className + " ";
		if(cc.indexOf(" "+ oc + " ") != -1){
			ln.className = prosper_trim(cc.replace(" "+oc+" "," "));
		}
	}
}

// ln = layerName
// nc = New Class
// cc = Current Class
function prosper_addClass(ln,nc){
	if(!ln.nodeName) ln = d.getElementById(ln);
	if (ln){
		cc = " "+ln.className + " ";
		if(cc.indexOf(" "+ nc + " ") == -1){
			ln.className = prosper_trim(ln.className + " " + nc);
		}
	}
}
// ln = layerName
function prosper_toggleClass(ln,tog1,tog2){
	if(!ln.nodeName) ln = d.getElementById(ln);
	if (ln){
		if(!ln.nodeName) ln = d.getElementById(ln);
		curClass = " "+ln.className + " ";
		if(curClass.indexOf(" "+ tog1 + " ") != -1){
			prosper_delClass(ln,tog1);
			prosper_addClass(ln,tog2);
		} else if(curClass.indexOf(" "+ tog2 + " ") != -1){
			prosper_delClass(ln,tog2);
			prosper_addClass(ln,tog1);
		}
	}
}


/*************************************
	scrollToId 
	zelph_ prefix is just so function names don't interfere with potentially similarly named functions.

	Vars passed to the function
	eid = Element ID -  The ID of the element we are scrolling to
	pi = Place It - Where to place the element on the screen when scrolling.  Can be "top" "bot" or "any"
	pad = PADding - How much extra cushing should it be above or below the viewport edge
	dc = Done Code -  Code to run when we are done scrolling
		
	Other vars used in the script
	vty = Viewport Top Y - How far down we have scrolled, the Y is the top pixel of the current viewable area
	vby = Viewport Bottom Y - The y of the bottom of the viewport.  Is vty plus viewport height
	vh = Viewport Height - How tall is the viewport, used for some math
	ey = Element Y - The Y of where the element currently is
	eh = Element Height - How tall is the Element

*************************************/
lvy = -1;
function prosper_scrollToId(eid,pi,pad,dc){
	var e = d.getElementById(eid);
	if(e){
		//var dc = "Fat.fade_element('"+eid+"', 20, 2000, '#ffcc00', '#ffffff')";
		// here are all the vitals we need 
		var vty = prosper_getScroll();
		var vh = prosper_getHeight();
		var vby = vty + vh;
		var ey = prosper_findPosY(e);
		var eh = e.offsetHeight;

		if(pi == "top") st = ey - pad; // place element at the top of the page (after getting full element on screen)
		if(pi == "bot") st = ey + eh + pad - vh; // place element at the bottom of the page (after getting full element on screen)
		if(pi == "mid") st = ey - vh/2; // place element in the middle of the screen
		
		if(ey < vty){ // the element is above the vty... so we need move up
			if(pi == "any") st = ey - pad;
			prosper_scrollToY(st,"up",dc);
		}else if (ey+eh > vby){ // the element is below the vby... so we need move down
			if(pi == "any") st = ey + eh + pad - vh;
			prosper_scrollToY(st,"down",dc);
		} else {
			// must be on screen so just do the Done Code
			if(dc) eval(dc);
		}
	}
}
/*************************************
	scrollToY 
	zelph_ prefix is just so function names don't interfere with potentially similarly named functions.

	Vars passed to the function
	gty = Go To Y -  the Y pixel we are going to
	dir = direction -  up or down... may move the logic in here to automatically figure it out
	dc = Done Code -  Code to run when we are done scrolling
	
	Other vars used in the script
	vy = Viewport Y - How far down we have scrolled, the Y is the top pixel of the current viewable area
	ltg = Left To Go - How many more pixels do we have to scroll
	lvy = Last Viewport Y - The Viewport Y that we were at last time we cylced through this.
	jb = Jump By - How many pixels we jump down this cycle
	nt = New Top - The new top Y we are going to
*************************************/
function prosper_scrollToY(gty,dir,dc){
	var vy = prosper_getScroll();
	
	var ltg = vy - gty;
	if(dir == "down") ltg = gty - vy;
	if(ltg > 0 && vy != lvy){
		var jb = 50;
		if(ltg < 50) {
			jb = 1;
		} else if(ltg < 200) {
			jb = 5;
		} else if(ltg < 400) {
			jb = 10;
		} else if(ltg < 500) {
			jb = 20;
		}
		nt = vy - jb;
		if(dir == "down") nt = vy + jb;
		scrollTo(0,nt);
		lvy = vy;
		foo = setTimeout("prosper_scrollToY('"+gty+"','"+dir+"','"+prosper_addSlashes(dc)+"')",10);
	} else {
		// we have reached our destination... run some code?
		if(dc) eval(dc);
	}
}

/* time related */
function prosper_setupCountDown(secs,targetID,endCode){
	var now = new Date();
	//secs = 10;
	targetTime = now.getTime()+secs*1000;
	//prosper_doCountDown(targetTime,targetID,endCode);
	prosper_doCountDown(targetTime,targetID,'prosper_extendTime("'+targetID+'")');
}
extendSC = extendEC = "";
function prosper_extendTime(targetID){
	alert("The allotted time has run out. To briefly extend your time and proceed, press OK.");
	prosper_setupCountDown(600,targetID,"");
	sc = "#ffcc00";
	ec = "#E5E5CC";
	if(extendSC != "") sc = extendSC;
	if(extendEC != "") ec = extendEC;
	prosper_scrollToId("solp","any",10,"Fat.fade_element('solp', 20, 2000, '"+sc+"', '"+ec+"')");
}

function prosper_doCountDown(targetTime,targetID,endCode){
	curTime = new Date().getTime();
	targTime = new Date(targetTime).getTime();
	
	timeLeft = Math.ceil((targTime - curTime)/1000);
	minsLeft = Math.floor(timeLeft/60);
	secsLeft = Math.floor(timeLeft - (minsLeft*60));
	
	countdown = prosper_zeroPad(minsLeft,2)+":"+prosper_zeroPad(secsLeft,2);
	
	var foo = document.getElementById(targetID);
	if(foo.getAttribute("type")){ // form fields
		foo.value = countdown;
	} else { // others
		foo.innerHTML = countdown;
	}
	
	if(minsLeft == "00" && secsLeft == "00"){
		eval(endCode);// do end code
	} else {
		var foo = setTimeout("prosper_doCountDown("+targetTime+",'"+targetID+"','"+endCode+"')",999); // do this again in a second
	}
}

monthNames = new Array('','January','February','March','April','May','June','July','August','September','October','November','December');
function prosper_customDate(oneDate) {
        var theMonth = monthNames[oneDate.getMonth() + 1]
        var theYear = oneDate.getFullYear( );
        return theMonth + " " + oneDate.getDate() + ", " + theYear
}

/* Flash Related */
// flash detection
actualVersion = 0;
function prosper_flashDetect(reqVersion){ // detect users version of flash, and if it's high enough
	var maxFlashVersion = 9;
	if(actualVersion == ""){
		var gotIt = got2 = got3 = got4 = got5 = got6 = got7 = got8 = got9 = false;
		if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.toLowerCase().indexOf("win") != -1)) {
			vbCode = '<scr'+'ipt language="VBScript"\> \n';
			vbCode += 'on error resume next \n';
			for(x=2; x<=maxFlashVersion; x++){
				vbCode += 'got'+x+' = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.'+x+'"))) \n';
			}
			vbCode += '</scr'+'ipt\> \n';
			d.write(vbCode);
			for (var i = 2; i <= maxFlashVersion; i++) {  
				if (eval("got" + i) == true) actualVersion = i;
			}
		} else {
			var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
			if (plugin) {
				actualVersion = parseInt(plugin.description.substring(plugin.description.indexOf(".")-1));
			}
		}
	}
	useFlashVer = prosper_getQueryVariable('useFlashVer');
	if(useFlashVer) actualVersion = useFlashVer;
	if(actualVersion >= reqVersion) gotIt = true;
	return gotIt;
}
prosper_flashDetect(6); // go ahead and run now for any future use

function prosper_makeFlash(w,h,vars,fileName){ // generate flash code based on passed vars
	swf  = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+window.location.protocol+'//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+w+'" height="'+h+'" class="flashTitle">\n';
	swf += '	<param name="movie" value="'+fileName+'" />\n';
	swf += '	<param name="wmode" value="transparent" />\n';
	swf += '	<param name="allowScriptAccess" value="sameDomain" />\n';
	swf += '	<param name="flashvars" value="'+vars+'" />\n';
	swf += '	<embed src="'+fileName+'" flashvars="'+vars+'" width="'+w+'" height="'+h+'" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="sameDomain" class="flashTitle" wmode="transparent"><'+'/embed>\n';
	swf += '<'+'/object>\n';
	return swf;
}



/*  */
Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
	var i;
	for (i=0; i < this.length; i++) {
		// Matches identical (===), not just similar (==).
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

/*
Modified version from http://www.fiftyfoureleven.com/sandbox/weblog/2004/jun/javascript-pullquote
Made it more modular to be used with onDOMload
*/
function prosper_makePullQuote(quote) {
	var up = quote.parentNode;	// Needed as a target for insertion.
	var up2 = quote.parentNode.parentNode;	// Needed as a target for insertion.

	if(quote.className.indexOf("pullquote") != '-1') {	// Check if it's a pullquote and generate a pullquote
		// Create the blockquote with a class of pullquote
		var pullquote = document.createElement("div");
		var newClass = 'theQuote';
		if(quote.className.indexOf("pqleft") != '-1') newClass = 'theQuoteLeft';
		pullquote.className = newClass;
		
		// Create the paragraph tag for the blockquote
		var paragraph = document.createElement("p");
		
		// I ran into some trouble when cloning the node, Opera went into an infinite loop,
		// a result of, I suppose, having the 'pullquote' class in the span. 
		// The folliowing two lines solve the problem by removing the class from the span.
		quote.className = ""; // Insert class name here if desired
		
		// Sticks the span into the generated paragraph
		paragraph.appendChild(quote.cloneNode(true));
		
		// Sticks the generated paragraph into the generated blockquote
		pullquote.appendChild(paragraph);
		
		// Inserts the pullquote before the <p> that contains the <span class="pullquote">
		up2.insertBefore(pullquote,up);	
	}
}


/*************************************
	onDOMload
	v1.1
	last revision: 03.31.2005
	aaron@zelph.com
	get more info: http://www.zelph.com/releases/ondomload/
	
	zelph_ prefix is just so function names don't interfere with potentially similarly named functions.

	Vars passed to the function
	dtw = Do To What -  the id/class/tagname that the code should be run on
	ctr = Code To Run -  is the actual code to run on the element/id.  use "theTarget" to reference the element you want to work with in the code you pass
	
	Other vars used in the script
	ndc = Number Done Count - Array that will hold the number that have been done for each request. Uses assoicative array,
	kg = Keep Going - as long as this is true the loop continues. Stops after "onload" event is fired
	es = ElementS (e and s) - tht elements returned by the getElementsBySelector
	nes = Number ElementS - the number of elements returned above
	coc = Copy Of Code - copy of the code we are running, so it can be run one last time when the onload fires to stop the loops
*************************************/
ndc = new Array();
coc = new Array();
kg = true;
function zelph_onDOMload(dtw,ctr){
	es = zelph_getElementsBySelector(dtw); // get all elements that match what we are looking for
	if(ndc[dtw] == null){
		ndc[dtw] = 0; // initialize the number we have done for this tag type
		coc[coc.length] = "zelph_onDOMload('" + dtw + "', '" + ctr + "')"; // copy off the code
	}
	if(es.length > ndc[dtw]){ // if available elments are greater then the number of elements already done, then lets do them
		nes = es.length;
		for(var x=ndc[dtw]; x<nes; x++){ // loop through all elements that have not been done yet
			// do what we need to do
			theTarget = es[x];
			eval(ctr);
		}
		ndc[dtw] = nes;
	}
	
	if(kg == true){
		// play it again sam
		setTimeout("zelph_onDOMload('" + dtw + "', '" + ctr + "')", 100);
	}
	return true;
}

// taken from http://pro.html.it/esempio/nifty/niftyCodice.html
// modified to return false in a few situations since that wasn't an option in the original script
function zelph_getElementsBySelector(selector){
	var i;
	var s=[];
	var selid="";
	var selclass="";
	var tag=selector;
	var objlist=[];
	if(selector.indexOf(" ")>0){  //descendant selector like "tag#id tag"
		s=selector.split(" ");
		var fs=s[0].split("#");
		if(fs.length==1) return(objlist);
		if(d.getElementById(fs[1])){
			return(d.getElementById(fs[1]).getElementsByTagName(s[1]));
		}
		return false;
	}
	if(selector.indexOf("#")>0){ //id selector like "tag#id"
		s=selector.split("#");
		tag=s[0];
		selid=s[1];
	}
	if(selid!=""){
		if(d.getElementById(selid)){
			objlist.push(d.getElementById(selid));
			return(objlist);
		}
		return false;
	}
	if(selector.indexOf(".")>0){  //class selector like "tag.class"
		s=selector.split(".");
		tag=s[0];
		selclass=s[1];
	}
	var v=d.getElementsByTagName(tag);  // tag selector like "tag"
	if(selclass=="")return(v);
	for(i=0;i<v.length;i++){
		curClass = " "+v[i].className+" ";
		if(curClass.indexOf(" "+selclass+" ") != "-1"){
			objlist.push(v[i]);
		}
	}
	return(objlist);
}

function zelph_stopIt(){
	kg = ""; // stop the flash loop
	for(x=0; x<coc.length; x++){ // one last check of each script
		eval(coc[x]);
	}
}

function prosper_onViewable(doTo,doWhat){
	// Find out info about our element
	var elem = d.getElementById(doTo);
	var e = new Array(); // elem info
	e['t'] = prosper_findPosY(elem);
	e['h'] = elem.offsetHeight;
	e['b'] = e['t']  + e['h'];
	
	// find out about our viewport
	var v = new Array(); // viewport info
	v['t'] = prosper_getScroll();
	v['h'] = prosper_getHeight();
	v['b'] = v['t'] + v['h'];
	
	// if above the bottom and below the top
	if(e['b'] < v['b'] && e['t'] > v['t']){
		theTarget = elem;
		eval(doWhat);
	} else {
		// try again
		setTimeout("prosper_onViewable('" + doTo + "', '" + prosper_addSlashes(doWhat) + "')", 100);
	}
}
/* Utility functions */

function prosper_trim(s){
	s=s.replace(/^[\s]+/g,"");
	s=s.replace(/[\s]+$/g,"");
	return s;
}

function prosper_getQueryVariable(variable) { // this function gets us the value of a passed variable name from the query string
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	} 
	return '';
}

function prosper_addLoadEvent(func) { // allows multiple window.onload's Thanks to Simon - http://simon.incutio.com/archive/2004/05/26/addLoadEvent
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function prosper_optionalVars(theString){
	// to use this make one string with a = seperating var/value and a | sepeating different value pairs (just like a query string)
	// can use ^ instead of = within the string and it will be changed back below
	tempArray = new Array();
	if(theString){
		var vars = theString.split(/[\|]/);
		for (var i=0;i<vars.length;i++) {
			var pair = vars[i].split(/[\=]/);
			tempArray[pair[0]] = pair[1].replace(/[\^]/,'='); // regex out ^ and replace it with =
		} 
	}
	return tempArray;
} 

function prosper_addSlashes(n){
	var p = /[']/g;
	c = n.replace(p,"\\'");
	p = /["]/g;
	c = c.replace(p,'\\"');
	return c
}

function prosper_stripSlashes(n){
	var p = /\\'/g;
	c = n.replace(p,"'");
	p = /\\"/g;
	c = c.replace(p,'"');
	return c
}

function prosper_zeroPad(numToPad,numDigits){
	numToPad = numToPad+""; // make into string to count length
	curLen = numToPad.length;
	if(curLen < numDigits){
		zeros = "0";
		for(x=curLen; x<numDigits-1; x++)zeros += "0";
		newNum = zeros+numToPad;
		return newNum;
	}
	return numToPad;
}


function prosper_toggleText(foo,tog1,tog2){ // toggles text that is within a span below the passed element
	if(!foo.nodeName) foo = d.getElementById(foo);
	s = foo.getElementsByTagName('span');
	for (var i=0; i<s.length; i++) {
		if(s[i].innerHTML == tog1){
			s[i].innerHTML = tog2;
		} else if(s[i].innerHTML == tog2){
			s[i].innerHTML = tog1;
		}
	}
}

/*
Modified from: http://www.skyzyx.com/scripts/acrobat.php
Checks for any acrobat, not versions
*/
function checkForAcrobat(){
	var ai=false;
	n = navigator.plugins;
	if (n && n.length){ // for all non-IE
		for (x=0; x<n.length; x++){
			if (n[x].description.indexOf('Adobe Acrobat') != -1){
				ai=true;
				break;
			}
		}
	}else if (window.ActiveXObject){
		for (x=2; x<10; x++){
			try{
				oAcro=eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
				if (oAcro){
					ai=true;
				}
			}
			catch(e) {}
		}
	}
	return ai;
}

/* Events */
function prosper_addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be attached");
	}
}

function prosper_removeEvent(obj, evType, fn, useCapture){
	if (obj.removeEventListener){
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.detachEvent){
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be removed");
	}
} 

prosper_addEvent(window,"load",zelph_stopIt);

