<!-- hide this script from non-javascript-enabled browsers

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

/* Functions that swaps images. */
function MM_swapImage() { //v3.0
   var i,j=0,x,a=MM_swapImage.arguments;
   document.MM_sr=new Array;
   for(i=0;i<(a.length-2);i+=3) {
   	 if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
   }
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) {
    x.src=x.oSrc;
  }
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function isEmailAddress(email)
{
  var result = false
  var index = email.indexOf("@");
  if (index > 0) {
    var pindex = email.indexOf(".",index);
    if ((pindex > index+1) && (email.length > pindex+1))
		result = true;
  }
  return result;
}

function showBalloon(text,event,dx,dy,showleft)
{
    var x, y;
    
	if (isNaN(dx))
	  dx = -200;
	if (isNaN(dy))
	  dy = 10;

    if (document.getElementById)
	{
		obj = document.getElementById('balloonHelp');
	}
	else
	{
	    // for old Netscape browsers
		obj = document.all['balloonHelp'];
	}
	
	if (document.all)
	{
	    // for IE browsers
		x = event.clientX;
		y = event.clientY;
	}
	else
	{
		x = event.pageX;
		y = event.pageY;
	}
	
	if (obj) {
		if(!showleft) {
			obj.innerHTML='<table border=0 cellspacing=0 cellpadding=0><tr><td rowspan=3 valign=top><img src=../images/pics/balloon/dots.gif width=21 height=17 hspace=5></td><td><img src=../images/pics/balloon/tl.gif width=5 height=5></td><td background=../images/pics/balloon/t.gif width=300><img src=../images/pics/balloon/t.gif width=5 height=5></td><td><img src=../images/pics/balloon/tr.gif width=5 height=5></td></tr><tr><td background=../images/pics/balloon/l.gif><img src=../images/pics/balloon/l.gif width=5 height=5></td><td bgcolor=#BBDBF4 class=copy>'+text+'</td><td background=../images/pics/balloon/r.gif><img src=../images/pics/balloon/r.gif width=5 height=5></td></tr><tr><td><img src=../images/pics/balloon/bl.gif width=5 height=5></td><td background=../images/pics/balloon/b.gif><img src=../images/pics/balloon/b.gif width=5 height=5></td><td><img src=../images/pics/balloon/br.gif width=5 height=5></td></tr></table>';
		} else {
			obj.innerHTML='<table border=0 cellspacing=0 cellpadding=0><tr><td><img src=../images/pics/balloon/tl.gif width=5 height=5></td><td background=../images/pics/balloon/t.gif width=300><img src=../images/pics/balloon/t.gif width=5 height=5></td><td><img src=../images/pics/balloon/tr.gif width=5 height=5></td><td rowspan=3 valign=top><img src=../images/pics/balloon/dots_left.gif width=21 height=17 hspace=5></td></tr><tr><td background=../images/pics/balloon/l.gif><img src=../images/pics/balloon/l.gif width=5 height=5></td><td bgcolor=#BBDBF4 class=copy>'+text+'</td><td background=../images/pics/balloon/r.gif><img src=../images/pics/balloon/r.gif width=5 height=5></td></tr><tr><td><img src=../images/pics/balloon/bl.gif width=5 height=5></td><td background=../images/pics/balloon/b.gif><img src=../images/pics/balloon/b.gif width=5 height=5></td><td><img src=../images/pics/balloon/br.gif width=5 height=5></td></tr></table>';
		}
		
		if (document.getElementById)
	    {
			obj.style.left = document.body.scrollLeft + x + dx + "px";
			obj.style.top = document.body.scrollTop + y + dy + "px";
			obj.style.visibility = "visible";
	    }
	    else
	    {
			obj.left = document.body.scrollLeft + x + dx;
			obj.top = document.body.scrollTop + y + dy;
			obj.visibility = "visible";
	    }
	}
}

function hideBalloon()
{
	if (document.all)
		document.all['balloonHelp'].style.visibility="hidden";
	else if (document.getElementById)
		document.getElementById('balloonHelp').style.visibility="hidden";
}

function submit_timer()
{
    var button = document.getElementById("continueButton");
    button.disabled = true;
	setTimeout("enableContinueButton()",5000);
}

function enableContinueButton() {
    var button = document.getElementById("continueButton");
    button.disabled = false;
}

function g_openTab(page, win)
{
	if (!win) win = "_blank";

	popupWin = window.open(page,win);
	popupWin.focus();
	return popupWin;
}

function g_openWindow(page, height, width, win, scrollbars, resizable, toolbar, menubar, left, top)
{
	if (!height)
		height = 400;
	if (!width)
		width = 560;
	if (!win)
		win = "_new"
	var h, w, scrol, siz;
	w = "WIDTH=" + width.toString();
	h = "HEIGHT=" + height.toString();
	scrol = ",scrollbars=" + ( (scrollbars) ? "yes" : "no" );
	siz = ",resizable=" + ( (resizable) ? "yes" : "no" );
	tool = ",toolbar=" + ( (toolbar) ? "yes" : "no" );
	menu = ",menubar=" + ( (menubar) ? "yes" : "no" );
	attr = w + "," + h + scrol + siz + tool + menu;
    if (left)
        attr = attr + ",left=" + left
    if(top)
        attr = attr + ",top=" + top

	popupWin = window.open(page,win,attr);
	popupWin.focus();
	return popupWin;
}

if (document.all || document.getElementById)
	document.write('<div id=balloonHelp style="width:300px;position:absolute;visibility:hidden;z-index:1"></div>');

// generic support for child windows
var childWindows = new Array();

// g_openWindow(page, height, width, win, scrollbars, resizable, toolbar, menubar)

function openChildWindow(name, url, width, height)
{
	childWindows[name] = g_openWindow(url, height, width, name, true, true, false, false);
}

function closeChildWindow(name, dontrefresh)
{
	childWindows[name].close();
	if (!dontrefresh)
		refresh(); // refresh window after ESM window closes
}


function checkSignupForm()
{
	if (document.subscribeFrm.email.value.length < 5) {
		alert('Please enter a valid email address.');
		document.subscribeFrm.email.value.focus();
		document.subscribeFrm.email.value.select();
		return false;
	}
	else if (!document.subscribeFrm.subscribe[0].checked && !document.subscribeFrm.subscribe[1].checked) {
		alert('Please select a subscription option.');
		return false;
	}
	else
		return true;
}

function disableEnterKey(e) {
     var key;
     if(window.event) {
          key = window.event.keyCode;     //IE
     } else {
          key = e.which;     //firefox
     } if(key == 13) {
         return false;
     } else {
         return true;
     }
}

// this function is used by the select for disciplinefocus
// the list contains discipline as well which should not
// be selected, if selected, it should alert and set back
// to "Please Select" item.
function filterDisciplineFocus(selector)
{
    if (selector.selectedIndex > 0) {
        var choice = selector.options[selector.selectedIndex].value;
        if (choice == "") {
            alert("Please select specific subject.");
            selector.selectedIndex = 0;
        }
    }
}

// this function is used by the multi-select for disciplinefocus
// the list contains discipline as well which should not
// be selected, if selected, it should alert and unselect
// the discipline
function filterMultiDisciplineFoci(selector)
{
    var size = selector.options.length;
    for (var i = 0; i < size; i++) {
        if (selector.options[i].selected) {    
	        var choice = selector.options[i].value;
	        if (choice == "") {
	            alert("Please select specific subject.");
	            selector.options[i].selected = false;
	        }        
        }
    }
}

function stripCommas(numString) {
	return numString.replace(/,/g, "");
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


// used in findSchoolForm.jsp
function checkSchoolSelected() {

	var form = document.teacher;
	for (var i = 0; i < form.elements.length; i++) {
	    if (form.elements[i].name == "teacher.school.schoolId" &&
	        form.elements[i].checked == true)
	        return true;
	}
	
	alert("Please select a school first.");
	return false;
}
// used in donation.jsp
function verify_return_donation() {
    return confirm('Are you sure you want to return this donation?');
}

function selectProposal(donation_id,proposal) {
    document.getElementById("vo_partialContribsForSameSubject_sendToProposalId_" + donation_id).value = proposal;
    document.getElementById("radio_partialContribsForSameSubject_" + donation_id).checked = "checked";
}

function DeselectAllMultiSelect(elemID){
  for(var i = 0;i < document.getElementById(elemID).length;i++){
	document.getElementById(elemID).options[i].selected = false;
  }
  return;
}
//cookie functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		var expires = "; expires=";
		if (days != null) {
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
	}
	else var expires = "";
	var domain = "";
	if (window.location.host.indexOf("donorschoose.org") != -1) {
		domain = "; domain=donorschoose.org"		
	}
	document.cookie = name+"="+value+expires+"; path=/" + domain;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
		  var cookieString = c.substring(nameEQ.length,c.length);
		  if (cookieString.charAt(0) == "\"" && cookieString.charAt(cookieString.length-1) == "\"") {
		  	cookieString = cookieString.substring(1,cookieString.length - 1);
		  }
		  return cookieString;
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function trim(string) {
	return string.replace(/^\s+|\s+$/g, "");
}

//Crossbrowser XMLHttpRequest object

function createRequestObject() {
    var ro = false;
    var browser = navigator.appName;
    if(window.ActiveXObject){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else if (window.XMLHttpRequest){
        ro = new XMLHttpRequest();
        ro.overrideMimeType('text/xml');
    }
    return ro;
}

reqObj = createRequestObject();

function sendReq(url,handleResponse) {
	timestamp = new Date();
	if (reqObj) {
		tsSep = "&";
		if (url.indexOf("?") == -1) {
			tsSep = "?";
		}
	    reqObj.open('get', url + tsSep + 'timestamp=' + timestamp.getTime());
	    reqObj.onreadystatechange = handleResponse;
	    reqObj.send(null);
	}
}


var qsParam = new Array();
function qs() {
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParam[key] = val;
		}
	}
}
qs();

//QUESTIONAIRE FUNCTIONS

function submitSurvey(url) {
	submitString = "";
	checkBoxString = "";
	

	if (document.getElementsByTagName) {
		allfields = document.getElementById("surveyPopup").getElementsByTagName("input");
		for (i=0;i<allfields.length;i++) {
			if (allfields[i].getAttribute("type")=="hidden") {
				submitString += "&" + allfields[i].getAttribute("name") + "=" + allfields[i].getAttribute("value");
			} else if (allfields[i].getAttribute("type")=="radio" && allfields[i].checked && allfields[i].name != "other") {
				submitString += "&" + allfields[i].getAttribute("name") + "=" + allfields[i].getAttribute("value");
			} else if (allfields[i].getAttribute("type")=="checkbox" && allfields[i].checked && allfields[i].name != "other") {
				submitString += "&" + allfields[i].getAttribute("name") + "=on";
			} else if (allfields[i].getAttribute("type")=="text" && document.surveyForm.elements[allfields[i].getAttribute("name")].value!="") {
				submitString += "&" + allfields[i].getAttribute("name") + "=" + document.surveyForm.elements[allfields[i].getAttribute("name")].value;
			}				
		}
		allfields = null;
	}
	if (submitString != "") {
		//alert(submitString);
		reqObj.onreadystatechange = acknowlegeSurvey;
  		reqObj.open('POST', url, true);
  		reqObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  		reqObj.setRequestHeader("Content-length", submitString.length-1);
  		reqObj.setRequestHeader("Connection", "close");
  		reqObj.send(submitString.substring(1));
		//sendReq("${secureBaseURL}common/process_questionaire.html?"+submitString.substring(1),acknowlegeSurvey);
	} else {
		document.getElementById("surveyPopup").style.display="none";
	}
}
function acknowlegeSurvey() {
	//alert("Thank you for submitting your survey!");
	document.getElementById("surveyPopup").style.display="none";
	if (document.getElementById("surveyPopupHider")) {
		document.getElementById("surveyPopupHider").style.display="none";
	}
}

function getMatchingGrantPopup(matchingKey) {
	var matchingwindow = window.open("../donors/matching_grant_popup.html?v=2&matchingKey="+matchingKey,"matchingwindow","WIDTH=350,HEIGHT=500");
	matchingwindow.focus();
	return false;
}

function getDefaultImage(i,url) {
	i.src = url;
}


function getAltImage(i,url) {
	if (i.src.indexOf(".jpg") > -1) {
 		i.src = i.src.replace(".jpg",".png");
 	} else if (i.src != url) {
 		i.src = url;
 	}
}


function getDefaultImage(i,url,defaultImg) {
	i.src = url;
	if (defaultImg == true) {
		i.className = "default";
	}
}

function getDefaultDonorImage(i) {
	if (i.src.indexOf(".jpg") > -1) {
 		i.src = i.src.replace(".jpg",".gif");
 	} else {
 		i.src = "../images/sp.gif";
 		i.style.display = "none";
 	}
}

function getAltImageType(i) {
	if (i.src.indexOf(".jpg") > -1) {
 		i.src = i.src.replace(".jpg",".gif");
 	} else {
 		i.src = "../images/sp.gif";
 		i.style.display = "none";
 	}
}

function isEmailAddress(email) {
  var addressPattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
  return addressPattern.test(email);
}

function getStyle(el,styleProp) {
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

function getLastSearch(el) {
	if (readCookie("searchTermsURL") != null) {
  		el.href = readCookie("searchTermsURL");
  	} else {
  		if (window.location.toString().search("http://www") > 0 || window.location.toString().search("http://secure") > 0) {
  			el.href = "http://www.donorschoose.org/donors/search.html";
  		} else if (window.location.toString().search("dev") > 0) {
  			el.href = "http://dev.donorschoose.org/donors/search.html";
  		} else if (window.location.toString().search("stage") > 0) {
  			el.href = "http://stage.donorschoose.org/donors/search.html";
  		} else if (window.location.toString().search("qa") > 0) {
  			el.href = "http://qa.donorschoose.org/donors/search.html";
  		} else if (window.location.toString().search("local") > 0) {
  			el.href = "http://local.donorschoose.org/donors/search.html";
  		}
  	}
}

// reverse is a support function for getMiniCart()
String.prototype.reverse = function() {
    var res = "";
    for (var i = this.length; i > 0; --i) {
        res += this.charAt(i - 1);
    }
    return res;
}	

function getMiniCart() {
	cartItems = readCookie("cartItems");
	cartTotal = readCookie("cartTotal");
	if (cartTotal != null && cartTotal != "") {
 		cartTotal = cartTotal.reverse().replace(/(\d{3})/g, "$1,").reverse().replace(/^(-)?,/, "$1");
 	}
	if (document.location.href.indexOf('cartThankYou.html') > -1) {
		document.getElementById("miniCart").innerHTML = '<a href="#">Giving Cart: Thank you</a>';		
		document.getElementById("miniCart").className = "minicart off";
	} else if (cartItems == null || cartItems == 0) {
		document.getElementById("miniCart").innerHTML = " <a href=\"#\">Giving Cart: 0 items</a>";
		document.getElementById("miniCart").className = "minicart off";
	} else if (cartItems == 1) {
		document.getElementById("miniCart").innerHTML = " <a href=\"#\">Giving Cart: " + cartItems + " item, $" + cartTotal+"</a>";
	} else {
		document.getElementById("miniCart").innerHTML = " <a href=\"#\">Giving Cart: " + cartItems + " items, $" + cartTotal+"</a>";
	}
}

function setCursor(el,st,end) {
	if (el.setSelectionRange) {
		el.focus();
		el.setSelectionRange(st,end);
	} else if (el.createTextRange) {
		range=el.createTextRange();
		range.collapse(true);
		range.moveend('character',end);
		range.moveStart('character',st);
		range.select();
	}
} 

function checkDonationAmount(frm) {
	var donAmt = trim(frm.donationAmount.value.replace("$",""));
	frm.donationAmount.value = donAmt;
	var regexp = /^[0-9\.]+$/;
	if (donAmt == "" || donAmt.match(regexp) == null || parseFloat(donAmt) <= 0) {
		alert("Please enter a dollar amount.\n\n(Redeeming a gift card? Enter your code during checkout.)");
		return false;
	}
	return true;
}


/** 
 * Returns index of array element. If
 * element is not in array, returns -1.
 */ 
function indexOfArrayElement(val, arr) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == val) {
	    	return i;
	    }
	}
	return -1;
}

/** 
 * Remove element from array. For example, if the array is [1, 2, 3, 4, 5, 6], 
 * calling removeArrayElement(3, arr) will change the array into [1, 2, 3, 5, 6] 
 * with a length of 5.	
 */
function removeArrayElement(index, arr) {
	if (arr.length == 0) {
		return arr;
	}
	if (index < 0 || index >= arr.length) {
		return arr;
	}
	for (var i = index + 1; i < arr.length; i++) {
		arr[i-1] = arr[i];
	}
	arr.length = arr.length - 1;
}

function resizeImage(myImage,width,height) {
	ratio = myImage.width / myImage.height;
	if (ratio > parseInt(width)/parseInt(height)) {
		myImage.setAttribute("height",height);
		myImage.removeAttribute("width"); 
	} else {
		myImage.setAttribute("width",width);
		myImage.removeAttribute("height"); 
	}
} 

function submitFundingWidgetToCart(frm,amount) {
	frm.donationAmount.value = amount;
	if (checkDonationAmount(frm)) {
		frm.submit();
	}
}

function parseDate(myDate) {
	year = myDate.getFullYear();
	month = parseInt(myDate.getMonth()) + 1;
	if (month < 10) {		
		month = "0" + month;
	}
	date = myDate.getDate();
	if (date < 10) {
		date = "0" + date;
	}	
	fixedDate = year + '-' + month + '-' + date;
	return fixedDate;
}

geoZoneId = 0;
geoZoneName = "National";

function updateGeoZone() {
	if (readCookie("geoZone") != null && readCookie("geoZone") != "") {
		geoZone = readCookie("geoZone").split("*");
		geoZoneId = geoZone[0];
		geoZoneName = unescape(geoZone[1]).replace(/\+/g," ");
	}
}
updateGeoZone();

function getReturnHomePage(el) {
	if (readCookie("v") == "teacher") {
		if (el.href.indexOf("?") > -1) el.href += "&return=true";
		else  el.href += "?return=true";
	}
}

function createFaqPopupClosure(el,faqContainerWidth) {
	return function() {
		displayFaqPopup(el,faqContainerWidth);
	}
}

faqClosure = null;

function getFaqPopup(el,faqURL) {
	getFaqPopupAndWidth(el,faqURL,350);
}

function getFaqPopupAndWidth(el,faqURL,faqContainerWidth) {
	if (document.getElementById("faqFrame") == undefined || document.getElementById("faqFrame") == null) {
		faqFrame = document.createElement('iframe');
		faqFrame.setAttribute("id","faqFrame");
		faqFrame.setAttribute("name","faqFrame");
		faqFrame.setAttribute("width","0");
		faqFrame.setAttribute("height","0");
		faqFrame.setAttribute("frameBorder","0");
		/*
		faqFrame.width = 0;
		faqFrame.height = 0;
		faqFrame.frameBorder = 0;
		*/
		document.body.appendChild(faqFrame);
	}
	document.getElementById("faqFrame").src = faqURL + "&textOnly=true";	
	if (faqClosure != null) eventRemove(document.getElementById('faqFrame'),'load', faqClosure);
	faqClosure = createFaqPopupClosure(el,faqContainerWidth);
	eventPush(document.getElementById('faqFrame'),'load', faqClosure);	
	
	/*
	document.getElementById("faqFrame").onload = function() {
		displayFaqPopup(el);
	};
	*/
}

function eventPush(obj, event, handler) {
  if (obj.addEventListener) {
  	obj.addEventListener(event, handler, false);
  } else if (obj.attachEvent) {
    obj.attachEvent('on'+event, handler);
  }
}

function eventRemove(obj, event, handler) {
  if (obj.removeEventListener) {
  	obj.removeEventListener(event, handler, false);
  } else if (obj.detachEvent) {
    obj.detachEvent('on'+event, handler);
  }
}

function getContentDocument(id) {
	var cd = null;
	if (document.getElementById(id) && document.getElementById(id).contentDocument) {
        cd = document.getElementById(id).contentDocument;
    } else if (document.getElementById(id) && document.getElementById(id).contentWindow) {
        cd = document.getElementById(id).contentWindow.document;
    } else if (window.frames[id]) {
        cd = window.frames[id].document;
    }
    return cd;
}


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

  function findPosY(obj)
  {
    var curtop = 0;
    var oldPos = "";
    if(obj.offsetParent)
        while(1) {
		  if ((obj.tagName == "A") && navigator.appVersion.indexOf("MSIE") != -1) {
			oldPos = obj.style.height;
			obj.style.height = "auto"; 
		  } else if ((obj.tagName == "LI") && navigator.appVersion.indexOf("MSIE") != -1) {
			oldPos = obj.style.position;
			obj.style.position = "relative"; 
		  }
          curtop += obj.offsetTop;
          if ((obj.tagName == "A") && navigator.appVersion.indexOf("MSIE") != -1) obj.style.height = oldPos;
          else if ((obj.tagName == "LI") && navigator.appVersion.indexOf("MSIE") != -1) obj.style.position = oldPos;
          
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }


function findPos(obj) {
	return [findPosX(obj),findPosY(obj)];
}


function displayFaqPopupText(el,newFaqString,faqContainerWidth) {
	var oldPos = "";	
  	if ((el.tagName == "A") && navigator.appVersion.indexOf("MSIE") != -1) {
		oldPos = el.style.position;
		el.style.position = "relative"; 
  	}		
	var elPos = findPos(el);
	if ((el.tagName == "A") && navigator.appVersion.indexOf("MSIE") != -1) el.style.position = oldPos; 
	if (document.getElementById("faqContainer") == undefined || document.getElementById("faqContainer") == null) {
		faqHeader = '<table border="0" cellpadding="0" cellspacing="0" width="100%" class="faqPopupHeader"><tr>';
		faqHeader += '<td align="right"><a class="proplink closeBtn" href="#" onclick="hideFaqPopup();return false;"><span>close</span> <img src="../images/logos/popup_close.gif"></a></td></tr></table>';
		faqContainer = document.createElement('div');
		faqContainer.setAttribute("id","faqContainer");	
		faqContainer.innerHTML = faqHeader;	
		faqHolder = document.createElement('div');
		faqHolder.setAttribute("id","faqHolder");
		faqContainer.appendChild(faqHolder);
		document.body.appendChild(faqContainer);	
		eventPush(document.getElementById('faqContainer'),'mouseover', showFaqPopup);						
		eventPush(document.getElementById('faqContainer'),'mouseout', hideFaqPopup);						
		eventPush(el,'mouseout', hideFaqPopup);						
	}
	//var newFaqString = getContentDocument("faqFrame").body.innerHTML;
	document.getElementById("faqHolder").innerHTML = newFaqString;
	document.getElementById("faqContainer").style.width = faqContainerWidth + "px";
	if (elPos[0] + faqContainerWidth < document.body.clientWidth) {
		document.getElementById("faqContainer").style.left = (elPos[0] - 10) + "px";
	} else {
		document.getElementById("faqContainer").style.left = (document.body.clientWidth - faqContainerWidth -20) + "px";
	}		
	document.getElementById("faqContainer").style.top = (elPos[1]) + "px";
	
	var faqTopY = (elPos[1]);
	var browserHeight = 0;
	var browserTopY = 0;
	if ( document.documentElement && (document.documentElement.scrollTop)) {
		browserTopY = document.documentElement.scrollTop;
	} else {
		browserTopY = document.body.scrollTop;
	}
	if ( typeof( window.innerHeight ) == 'number' ) {
		browserHeight = window.innerHeight;
	} else {
		browserHeight = document.documentElement.clientHeight;
	}
	
	document.getElementById("faqContainer").style.display = "block";
	var faqHeight = document.getElementById("faqContainer").offsetHeight;
	
	if (faqHeight + faqTopY > browserHeight + browserTopY) {
		document.getElementById("faqContainer").style.top = (browserHeight + browserTopY - faqHeight) + "px";
	}
		
	
}

function displayFaqPopup(el,faqContainerWidth) {
	if (getContentDocument("faqFrame") != null && trim(getContentDocument("faqFrame").body.innerHTML) == "") {
		faqPopupTimeOut = setTimeout(createFaqPopupClosure(el),500);
	} else {
		displayFaqPopupText(el,getContentDocument("faqFrame").body.innerHTML,faqContainerWidth);
	}
}

function showFaqPopup() {
	document.getElementById("faqContainer").style.display = "block";
}

function hideFaqPopup() {
	document.getElementById("faqContainer").style.display = "none";
}

function addLinkTimestamp(el) {
	var newLinkArray = el.href.split("#");
	var newLink = newLinkArray[0];
	if (newLink.indexOf("?") > -1) { newLink+= "&"; } else { newLink+= "?"; }
	newLink += (new Date()).getTime();
	if (newLinkArray[1] != null && newLinkArray[1] != "") newLink += "#" + newLinkArray[1];
	el.href = newLink;
}

/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
* (ADAPTED)
***********************************************/

function enforceMaxLength(obj, maxLength){
	if (obj.value.length > maxLength) {
		obj.value = obj.value.substring(0,maxLength);
		if (obj.setSelectionRange) {
			obj.setSelectionRange(obj.value.length, obj.value.length);
		}
		else if (obj.createTextRange) {
			var range = obj.createTextRange();
			range.moveStart('character', obj.value.length);
			range.select();
		}
	}
}

function validateQuickDonation(pageName) {
	var donAmt = trim(document.quickDonate.donationAmount.value.replace("$",""));
	donAmt = donAmt.replace(",","");
	document.quickDonate.donationAmount.value = donAmt;
	if (document.quickDonate.donationAmount.value == "") {
		alert("Please enter a donation amount.");
		document.quickDonate.donationAmount.focus();
		return false;
	}
	var regexp = /^[0-9\.]+$/;	
	if (document.quickDonate.donationAmount.value.match(regexp) == null) {
		alert("Please enter a dollar amount.\n\n(Redeeming a gift card? Enter your code during checkout.)");
		document.quickDonate.donationAmount.focus();
		return false;		
	}
	if (document.quickDonate.donationAmount.value <= 0) {
		alert("Please enter a donation amount.");
		document.quickDonate.donationAmount.focus();
		return false;		
	}		
	try {
		_gaq.push(['_trackEvent',pageName,'Quick Donation', 'Submit']);
	} catch(err) {
		//do nothing
	}
	return true;
}

function returnFalse() {
	if('undefined' != typeof(event) )event.returnValue = false;
	return false;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

//first number is index
function pickNextProject(replaceIt) {
	if (readCookie("proposalPickerIds") != null) {
		var proposalPickerIds = readCookie("proposalPickerIds").split(",");
		var proposalIndex = parseInt(proposalPickerIds[0]) + 1;
		var proposalIds = proposalPickerIds.slice(1);
		if (proposalIndex > (proposalIds.length - 1) || proposalIndex < 0) proposalIndex = 0;
		createCookie("proposalPickerIds",proposalIndex.toString() + "," + proposalIds.toString(),0);
		if (replaceIt) location.replace( "/donors/proposal.html?id=" + proposalIds[proposalIndex] );
		else location.href = "/donors/proposal.html?id=" + proposalIds[proposalIndex]; 
	}	
}

function loadjscssfile(filename, filetype) {
	 if (filetype=="js"){ //if filename is a external JavaScript file
	  var fileref=document.createElement('script')
	  fileref.setAttribute("type","text/javascript")
	  fileref.setAttribute("src", filename)
	 }
	 else if (filetype=="css"){ //if filename is an external CSS file
	  var fileref=document.createElement("link")
	  fileref.setAttribute("rel", "stylesheet")
	  fileref.setAttribute("type", "text/css")
	  fileref.setAttribute("href", filename)
	 }
	 if (typeof fileref!="undefined")
	  document.getElementsByTagName("head")[0].appendChild(fileref)
	}

function initShadowbox() {
	if (window.Shadowbox !== undefined) {
		Shadowbox.init({
			handleOversize:"none",
			modal:"true",
			enableKeys:"false"
		});
	} else {
		window.setTimeout(initShadowbox,200);
	}
}

function checkTeacherUserAgent(clientUserAgent,allowContinue) {
	if (!allowContinue) {
		allowContinue = false;
	}
	if (window.Shadowbox === undefined) {
		loadjscssfile("/js/shadowbox-3.0.3/shadowbox.js", "js"); //dynamically load and add the shadowbox .js file
		loadjscssfile("/js/shadowbox-3.0.3/shadowbox.css", "css"); //dynamically load and add the shadowbox .css file
		window.setTimeout(initShadowbox,200);
	}
	window.onload = function() {
		var content = '<div id="ie6_error"><h3>Upgrade your web browser to use DonorsChoose.org</h3>';
		content += '<p>In order to provide the best experience for all users, we no longer support versions of Internet Explorer below 7.0. Please use a different web browser and try again. <a href="http://help.donorschoose.org/app/answers/detail/a_id/352" target="_blank">Learn more.</a></p><ul>';
		content += '<li><a href="http://www.microsoft.com/windows/internet-explorer/ie7/" target="_blank"><img src="/images/browsers/explorer.png" width="96" height="96" border="0" /></a><br/><a href="http://www.microsoft.com/windows/internet-explorer/ie7/" target="_blank">Internet Explorer 7.0+</a></li>';
		content += '<li><a href="http://www.mozilla.org" target="_blank"><img src="/images/browsers/firefox.png" width="96" height="96" border="0" /></a><br/><a href="http://www.mozilla.org" target="_blank">Firefox</a></li>';
		content += '<li><a href="http://www.apple.com/safari" target="_blank"><img src="/images/browsers/safari.png" width="96" height="96" border="0" /></a><br/><a href="http://www.apple.com/safari" target="_blank">Safari</a></li>';
		content += '<li style="border-right:none;"><a href="http://www.google.com/chrome/" target="_blank"><img src="/images/browsers/chrome.png" width="96" height="96" border="0" /></a><br/><a href="http://www.google.com/chrome/" target="_blank">Google Chrome</a></li>';
		content += '</ul>';
		if (allowContinue === true) {
			content += '<p style="text-align:right;"><a href="#" onclick="parent.Shadowbox.close();">Continue</a></p>';
		}
		content += '<p style="clear:both; font-size:7pt;">Your browser: '+clientUserAgent+'</p></div>';
		document.getElementById('sb-nav-close').style.visibility = 'hidden';
		if (window.Shadowbox !== undefined) {
			Shadowbox.open({
				content:    content,
				player:     "html",
				height:     350,
				width:      700,
				options:    {modal:true, enableKeys:false}
			});
		} else {
			alert('In order to provide the best experience for all users, we no longer support versions of Internet Explorer below 7.0. Please use a different web browser and try again.')
		}
	}
}

function checkDonorUserAgent(clientUserAgent) {
	var content = '<div id="ie6_header_error"><p><strong>Your web browser might not work well with DonorsChoose.org.</strong> We recommend you <a href="#" onclick="document.getElementById(\'other_browsers\').style.display=\'block\';return false;">upgade your browser</a>.</p>';
	content += '<div id="other_browsers" style="display:none;"><ul>';
	content += '<li><a href="http://www.microsoft.com/windows/internet-explorer/ie7/" target="_blank"><img src="/images/browsers/explorer.png" width="96" height="96" border="0" /></a><br/><a href="http://www.microsoft.com/windows/internet-explorer/ie7/" target="_blank">Internet Explorer 7.0+</a></li>';
	content += '<li><a href="http://www.mozilla.org" target="_blank"><img src="/images/browsers/firefox.png" width="96" height="96" border="0" /></a><br/><a href="http://www.mozilla.org" target="_blank">Firefox</a></li>';
	content += '<li><a href="http://www.apple.com/safari" target="_blank"><img src="/images/browsers/safari.png" width="96" height="96" border="0" /></a><br/><a href="http://www.apple.com/safari" target="_blank">Safari</a></li>';
	content += '<li style="border-right:none;"><a href="http://www.google.com/chrome/" target="_blank"><img src="/images/browsers/chrome.png" width="96" height="96" border="0" /></a><br/><a href="http://www.google.com/chrome/" target="_blank">Google Chrome</a></li>';
	content += '</ul><p style="clear:both"><a href="http://help.donorschoose.org/app/answers/detail/a_id/352" target="_blank">Learn more.</a></p><p style="clear:both; font-size:7pt;">Your browser: '+clientUserAgent+'</p></div>';
	document.getElementById('ie6_header_error_holder').innerHTML = content;
	document.getElementById('ie6_header_error_holder').style.display = 'block';
}

function showLightbox(page,feature) {
	if (!document.getElementById('lightboxBackgroundOpacity')) {
		var lightboxBackgroundOpacity = document.createElement("div");
		lightboxBackgroundOpacity.id = "lightboxBackgroundOpacity";
		lightboxBackgroundOpacity.setAttribute('onclick', 'hideLightbox(\''+page+'\',\''+feature+'\');');		
		document.body.appendChild(lightboxBackgroundOpacity);
	}
	if (!document.getElementById('lightboxContainer')) {
		var lightboxContainer = document.createElement("div");
		lightboxContainer.id = "lightboxContainer";
		lightboxContainer.className = "lightboxContainer";
		lightboxContainer.setAttribute('onclick', 'hideLightbox(\''+page+'\',\''+feature+'\');');		
		document.body.appendChild(lightboxContainer);
	}
	if (!document.getElementById('lightboxBackground')) {
		var lightboxBackground = document.createElement("div");
		lightboxBackground.id = "lightboxBackground";
		lightboxBackground.className = "lightboxBackground";
		document.getElementById('lightboxContainer').appendChild(lightboxBackground);
	}
	if (!document.getElementById('lightboxCloseButton')) {
		var lightboxCloseButton = document.createElement("div");
		lightboxCloseButton.id = "lightboxCloseButton";
		lightboxCloseButton.className = "lightboxCloseButton";
		lightboxCloseButton.innerHTML = '<a style="float:right" href="#" onclick="hideLightbox(\''+page+'\',\''+feature+'\'); return returnFalse();"><img src="../images/close_right.png" alt="close" /></a>'
		document.getElementById('lightboxBackground').appendChild(lightboxCloseButton);
	}
	// $("#lightboxBackground").html($("#lightboxBackground").html()+$('#lightbox'+feature).html());
	$('#lightbox'+feature).show();
	$("#lightboxBackground").append($('#lightbox'+feature));
	// document.getElementById("lightboxBackground").appendChild(document.getElementById("#lightbox"+feature));
	// document.getElementById("#lightbox"+feature).style.display = "";
	$("#lightboxBackgroundOpacity").height($(document).height());
	$(".lightboxBackground").show();
	$(".lightboxContainer").css("top",$(document).scrollTop() + 50 + "px");
	$(".lightboxContainer").show('blind');
	$("#lightboxBackgroundOpacity").fadeIn(500);
	$(document).keyup(function(e) { if (e.keyCode == 27) { hideLightbox(page,feature); } });	
	_gaq.push(['_trackEvent', page, feature, 'Open']);
}

function hideLightbox(page,feature) {
	//alert($('#lightboxBackgroundOpacity').css('display'));
	if ($('#lightboxBackgroundOpacity').css('display') == 'block') {
		$("#lightboxBackgroundOpacity").fadeOut(500);
		$(".lightboxContainer").stop().hide('blind', function() { $("#lightboxBackground").html(''); } );
		_gaq.push(['_trackEvent',page,feature, 'Close']);
	}
}

//helper for debugging
function stringify(jsonData) {
    var strJsonData = '{';
    var itemCount = 0;
    for (var item in jsonData) {
        if (itemCount > 0) {
            strJsonData += ', ';
        }
    temp = jsonData[item];
    if (typeof(temp) == 'object') {
        s =  Stringify(temp);   
    } else {
        s = '"' + temp + '"';
    }   
    strJsonData += '"' + item + '":' + s;
        itemCount++;
    }
    strJsonData += '}';
    return strJsonData;
}

function setupErrorMessage(message) {
	if (document.getElementById('errorMessageText')) document.getElementById('errorMessageText').innerHTML = '<div id="errorMessages">' + message + '</div>';
}
function showErrorMessage() {
	showErrorMessageAndFadeout(true);
}

function showErrorMessageAndFadeout(fadeout) {
	if (document.getElementById("body1") && document.getElementById("backgroundOpacity")) {
		document.getElementById("backgroundOpacity").style.display = "";
		document.getElementById("errorMessagePopup").style.display = "";
		document.getElementById("backgroundOpacity").style.height = document.getElementById("body1").offsetHeight + "px";
		var errorMessagePopupTop=document.all? iebody.scrollTop : pageYOffset;
		document.getElementById("errorMessagePopup").style.top = errorMessagePopupTop + "px";
		if (fadeout) {
			var t=setTimeout("hideErrorMessagePopup()",7000);
		}
	} else if (document.getElementById("errorMessagePopup")) {
		document.getElementById("errorMessagePopup").style.display = "";
		document.getElementById("errorMessagePopup").style.color = "#cc0000";
	}
}


function hideErrorMessagePopup() {
	$('#errorMessagePopup').fadeOut(500, function() {});
	$('#backgroundOpacity').fadeOut(500, function() {});
}



var userId = "";
var userName = "";
var userHasPW = "";
var userHash = "";

function setUpUserCookies() {
	if (readCookie("userId") != null && readCookie("userId") != "") {
		var userCookie = readCookie("userId");
		var userCookieSplit = userCookie.split("##");
		if  (userCookieSplit.length > 0) {
			userId = userCookieSplit[0];
			userName = userCookieSplit[1];
			userHasPW = userCookieSplit[2];
			userHash = userCookieSplit[3];
			if (userName != "") userName = unescape(userName);
			if (userName.length > 23) userName = userName.substring(0,20) + "...";
		}
		if (!isNaN( parseInt(userName) ) || (qsParam['pmaId'] != null && userId != qsParam['pmaId'] )) {
			eraseCookie("userId");		
			userId = "";
			userName = "";
			userHasPW = "";
			userHash = "";			
		}
		
	}
}

setUpUserCookies();


createCookie("hasCookies","true",0);



// stop hiding -->


