//FUNCTIONS THAT OPERATE ON THE GIFTARRAY
function changeAmount(fundName, amount)
{
	/*changes the appropriate value in the giftarray for 1 particular fund*/
	var i = 0;
	while(i < giftArray.length)
	{
		if(fundName == giftArray[i].fundName) break;
		else i++;
	}
	var fundCode = giftArray[i].fundCode;
	if( !IsNumeric(amount) || amount == null) //check for non number values
	{
		//alert("non numeric");
		if(amount != "") //dont give error when it is blank
		{
			erMess = "Only numbers and a decimal are permitted.";
			if(document.getElementById("pageErrors")) dm.remElById("pageErrors");
			dm.addElement('span', 'pageErrorsList', 'pageErrors');
			dm.addElement('li', 'pageErrors', ["pageError"+i], ['class:giftErrorText', 'fadeIn:20', 'text:'+erMess ]);
			window.setTimeout( "dm.remElById('pageErrors')", 5000);
			//dm.addEl( 'span', fundName, [fundName+"giftError"], ['text:'+erMess, 'class:giftErrorText'] );
			//window.setTimeout( "dm.remElById(\'"+[fundName+"giftError"]+"'\)", 5000);
		}
		document.getElementById( [fundCode + "Amount"] ).value = 0.00;
		amount = 0;
	}
	
	var theAmount = parseFloat(amount);
	//giftArray[i].amount = theAmount.toFixed(2); //convert string to number add make that the new gift amount
	giftArray[i].amount = theAmount;
	//alert(amount);
	//alert(giftArray[i].amount);
	//now calculate the total
	calculateGiftTotal();
}

function changeCreditTo(fundCode, creditTo)
{
	var i = 0;
	while(i < giftArray.length)
	{
		if(fundCode == giftArray[i].fundCode) break;
		else i++;
	}
	giftArray[i].creditTo = creditTo;
}

function calculateGiftTotal()
{
	/*calculates the gift total from the giftarray and displays it*/
	var i = 0;
	var total = 0;
	while(i < giftArray.length)
	{
		if(giftArray[i].amount != 0) total += giftArray[i].amount;
		i++;
	}
	
	total = total.toFixed(2);
	dm.remElById("giftTotalAmount");
	dm.addEl( "span", "giftTotal", "giftTotalAmount", ["text:$"+total] );
	//removeById("giftTotalAmount");
	//createSpan("giftTotal", "giftTotalAmount", ['$'+total], "", "");
	
	return total;
}

function compareAmounts()
{
	var i = 0;
	var curTotal = 0;
	var amountLeft = 0;
	var total = calculateGiftTotal();
	
	return amountLeft;
}


//Removes a fund from both the visible giftcart and the giftArray
function removeFund(fundName)
{
	var i = 0;
	while(i < giftArray.length)
	{
		if(fundName == giftArray[i].fundName) break;
		else i++;
	}
	
	giftArray.splice(i, 1); //remove the gift from the array
	dm.remElById( fundName ); //remove the gift from the page
	//removeById( fundName ); 
	calculateGiftTotal();
}

//Things to do when preparing to go to the payment page..
//Rewrite the giftcart
//Check for a spouse
function preparePaymentPage()
{
	var creditToSpouse = false;

	var i = 0;
	//Rewrite the giftcart
	while(i < giftArray.length)
	{
		var fundCode = giftArray[i].fundCode + "Li";
		var fundName = giftArray[i].fundName;
		var creditTo = giftArray[i].creditTo;
		var isEndowed = giftArray[i].isEndowed;
		var amount = giftArray[i].amount;
		if(giftArray[i].creditTo != "Donor") creditToSpouse = true;
		dm.remElById(fundName);
		if(curAlt == "listAltCol1") curAlt="listAltCol2";
		else {curAlt="listAltCol1";}
		dm.addEl( "li", "giftList", fundCode, ["class:"+curAlt] );
		if(isEndowed == 1) dm.addEl( "img", fundCode, fundCode+"EndImg", ["src:images/endowedSymbolCart.gif", "title:This is an Endowment Fund", "alt:Endowed Fund"]);
		dm.addEl( "span", fundCode, fundCode+"MainLabel", ["text:"+fundName, "class:fundDonated"] );
		dm.addEl( "br", fundCode );
		dm.addEl( "span", fundCode, fundCode+"amount", ["text:$"+amount.toFixed(2), "class:subHeadWhite"] );
		dm.addEl( "br", fundCode );
		dm.addEl( "span", fundCode, fundCode+"creditTo", ["text:Gift Credit: "+creditTo, "class:giftSubText"] );
		i++;
	}
	
	if(creditToSpouse == true) document.getElementById("spouseTextHolder").style.display = "block";	
	//compareAmounts(); //supply the correct amount for the outstandingbalance on page switch
	dm.remElById( "reminder" );
	//dm.remInById( "continueBtn" );
	dm.addAttributes("continueBtn", ["onclick:switchDonationPage('process')"]);
	//dm.remInById( "fundBtn" );
	//dm.addEl( "img", "fundBtn", "", ["src:images/btnbilling.gif", "alt:Proceed to Billing", "onclick:switchDonationPage('process')"] );
	dm.addAttributes("step1", ["class:completed"]);
	dm.addAttributes("step2", ["class:active"]);
	document.getElementById('checkPerson').style.display = "block";
}


function addGift(fromWhere)
{
		//alert("Value: " + selectValue);
		//alert("Name: " + selectName);
// --------------------------------------------------------------------- //
	//check if there is already a paymentsource
	var isPaySource = false;
	var isGood = true;
	var i = 0;
	var origin;
	/*while(i<paymentSourceCount.length)
	{
		if(paymentSourceCount[i] == true) isPaySource = true;
		i++;
	}
	if(isPaySource == false) addPaymentSource(); //add if there is only 1 pay source*/
	//alert('called addGift from: ' + fromWhere);
// --------------------------------------------------------------------//
	//if the gift call is being made from DIG
	if(fromWhere=="DIG") // origin = DIG
	{
		//alert("addGift function initiated");
		var selectValue = document.getElementById("desi_code").value;
		var selectName = document.getElementById("desig_descrip").value;
		origin = "DIG";
		if(selectValue == 0) isGood = false;
	}
// --------------------------------------------------------------------//

 	//if the gift call is being made from College Priorities
	if(fromWhere=="CP" || fromWhere=="Scenario") // origin = CP
	{
		var cbPath = document.getElementsByName("cb_funds");
		//alert(cbPath.length);
		for (i = 0; i < cbPath.length; i++) {
			if (cbPath[i].checked) {
				addToCart(cbPath[i].fundName, cbPath[i].fundCode, cbPath[i].isEndowed, "CP");
			}
		}
		removeOverlay();
		origin == "CP"; 
		isGood = false;	//adds in an alternate way because its adding more than one fund
	}
// --------------------------------------------------------------------//
// --------------------------------------------------------------------//
	//if the gift call is being made from SCENARIOS
	//uses the same fund chooser as College Priorities does
	if(fromWhere=="Scenario") // origin = SC
	{
		origin="SC";
	}
// --------------------------------------------------------------------//	
	if(fromWhere=="fundSearch") //origin = TQ
	{
		origin = "TQ";
		dm.remElById("textHolder");
		var searchPath = document.getElementById("typeQueryInput");
		
		searchPath.setAttribute("class", "greyText");
		searchPath.setAttribute("className", "greyText");
		
		if(searchPath.value == searchTextDefault) //searchTextDefault is a global that says what is in the search box by default
		{
			var erMess = "Invalid selection, please try adding another.";
			disGiftMsg(origin, erMess, 1);
			isGood = false;
		}
		
		var selectName = searchPath.curGift.fundName;
		var selectValue = searchPath.curGift.fundCode;
		var isEndowed = searchPath.curGift.isEndowed;
		searchPath.value = searchTextDefault; //reset back to normal text
		
		//don't add the gift if the same name has been added or the same code as long as it wasn't 0 (general fund)
		if( giftExists(selectValue, selectName) == 1 )
		{
			var erMess = "You have already added this fund to the gift cart.";
			disGiftMsg(origin, erMess, 1);
			isGood = false;
		}
	}
// --------------------------------------------------------------------//
	//now add it no matter where it came from
	if(isGood == true)
	{		
		addToCart(selectName, selectValue, isEndowed, origin);
		var erMess = "The selected gift now appears in the Gift Cart on the right.";
		disGiftMsg(origin, erMess, 0);
	}
}

function initScenarioFunds()
{
	//alert("addGift function initiated for Scenario");
	var sid = document.getElementById("sid").value;
	//origin = "SC";
	isGood = false; //adds in an alternate way because its adding more than one fund
	if(sid != "") DWREngine._execute("scenarioResponder.cfc", null, 'getScenarioFunds', sid, showScenarioFunds);
}

function showScenarioFunds(r)
{
	if (r.returnfunds.length > 0) {
		document.getElementById("appeal").value = r.appealcode;
		if (r.autopopulate == 1) //AUTO POPULATE
		{
			for (i in r.returnfunds) {
				addToCart(r.returnfunds[i].fundname, r.returnfunds[i].fundcode, r.returnfunds[i].isendowed, "SC");
			}
		}
		else //SHOW POPUP
		{
			createFundPopup(r.hostcollege, r.scenarioname, r.returnfunds);
		}
	}
}

function addToCart(fundName, fundCode, isEndowed, origin)
{
	dm.addEl( "li", "giftList", fundName, ["class: giftLi "+curAlt] );
	if(curAlt == "listAltCol1") curAlt="listAltCol2";
	else {curAlt="listAltCol1";}
	if(isEndowed == 1) dm.addEl( "img", fundName, fundCode+"EndImg", ["src:images/endowedSymbolCart.gif", "title:This is an Endowment Fund", "alt:Endowed Fund"]);
	dm.addEl( "span", fundName, fundCode+"MainLabel", ["text:"+fundName, "class:fundDonated"] );
	dm.addEl( "a", fundName, fundCode+"DeleteLink", ["href:#", "onclick:removeFund(\""+fundName+"\")", "class:corTR deleteGiftLink"] );
	//dm.addEl( "span", fundCode+"DeleteLink", fundCode+"DeleteLabel", ["text:[Remove Fund]", "class:fundDelete"] );
	dm.addEl( "img", fundCode+"DeleteLink", fundCode+"DeleteImg", ["src:images/xCart.gif", "title:Remove Fund", "alt:Remove Fund"] );
	
	dm.addEl( "br", fundName );
	dm.addEl( "label", fundName, fundCode+"AmountLabel", ["for:"+fundCode+"Amount", "text:Donation: $", "class:giftSubText"] );
	dm.addEl( "input", fundName, fundCode+"Amount", ["value:0.00", "size:5", "maxlength:10", "onblur:changeAmount(\""+fundName+"\",this.value)", "onclick:if(this.value == '0.00' || this.value == '0') this.value=''"] );
	dm.addEl( "br", fundName );
	
	//CREATE THE CREDIT SELECT
	dm.addEl("label", fundName, fundCode+"SelectLabel", ["text:Gift Credit: ", "class:giftSubText"]);
	dm.addEl("select", fundName, fundCode+"CreditSelect", ["class:creditSelect"]);
	dm.addOptionGroup(fundCode+"CreditSelect", 'relp', ['Donor', 'Couple'], ['Donor', 'Couple',], []);
	var CreditSelectEl = document.getElementById(fundCode+"CreditSelect");
	CreditSelectEl.fundCode = fundCode;
	CreditSelectEl.onchange = function() { changeCreditTo(this.fundCode, this.value); };
	
	dm.addEl( "br", fundName);
	
	newGift = new giftObject(fundName, fundCode, isEndowed, origin);
	giftArray.push( newGift ); //create a giftobject and add it to the giftarray
	focusGift(newGift, 7000, 500); //flash the gift to get attention
}

function focusGift(whatGift, howLong, howQuick) //whatGift is a giftObject
{
	var gift = searchGiftArrayAC(whatGift.fundCode);
	if(gift != 0) //check to make sure its in the giftArray
	{
		var giftLiId = whatGift.fundName;
		var startingClass = document.getElementById(giftLiId).getAttribute("class");			//get the original class
		var firstClass = startingClass;															//set the original class to the first argument var
		var secondClass = "giftLi listAltCol3";													//define our blinking class
		//var intervalID = setInterval(alternateClass, howQuick, giftLiId, firstClass, secondClass); 	//start alternating the borders //Correct Way
		var intervalID = setInterval('alternateClass("' + giftLiId + '","' + firstClass + '","' + secondClass + '")', howQuick);        //IE Way
		setTimeout("clearInterval(" + intervalID + ")", howLong);	       						//stop the alternating after 3 seconds
		alternateClass(giftLiId, firstClass, secondClass);										//initial call
		setTimeout('switchClass("' + giftLiId + '","' + startingClass + '")', howLong+howQuick);//set back to original class
	}
}

function disGiftMsg(origin, erMess, isError)
{
	var messHolder;
	var messDiv;
	if(origin == "CP"){
		messHolder = "selectErrors";
		messDiv = "dropDownError";
	}
	else if(origin == "TQ"){
		messHolder = "donateMethods";
		messDiv = "typeQueryError";
	}
	else if(origin == "DIG")
	{
		messHolder = "selectErrors";
		messDiv = "dropDownError";
	}
	
	var img = "images/check.gif";
	if(isError == 1) img = "images/x.gif";
	
	dm.addEl( "div", messHolder, messDiv, ["class:giftErrorText", "fadeIn:25"] );
	dm.addEl( "img", messDiv, [messDiv+"Img"], ["src:"+img, "alt:error", "class:errorImg"] );
	dm.addEl( "span", messDiv, [messDiv+"Text"], ["text:"+erMess] );
	window.setTimeout( 'dm.remElById( "' +messDiv+ '" )', 5000);
}

function alternateClass(whatId, firstClass, secondClass)
{
	if(document.getElementById(whatId)){
		if(document.getElementById(whatId).getAttribute("class") == firstClass)
		{
			switchClass(whatId, secondClass);
		}
		else if(document.getElementById(whatId).getAttribute("class") == secondClass)
		{
			switchClass(whatId, firstClass);
		}
	}
}

//searchs the gift array by allocation code and returns a copy of the gift
function searchGiftArrayAC(whatAC) //whatAC is allocation code
{
	var giftReturn = 0;
	var i = 0;
	while(i < giftArray.length)
	{
		if(giftArray[i].fundCode == whatAC)
		{
			giftReturn = giftArray[i];
		}
		i++;		
	}
	return giftReturn;
}

//searchs gift array by allocation code and returns 1 if it exists
function giftExists(whatAC, whatAN) //whatAC is allocation code
{
	var giftReturn = new Boolean(0);
	var i = 0;
	while(i < giftArray.length)
	{
		if(giftArray[i].fundCode == whatAC && giftArray[i].fundName == whatAN)
		{
			giftReturn = 1;
		}
		i++;		
	}
	return giftReturn;
}