var http = getHTTPObject(); // We create the HTTP Object

/** UTILITY FUNCTIONS **/

/**
	This function will display a msg inside element $id and fade it out over 10 seconds.
*/
function displayAndFade($id, $msg) {
	$('#'+$id).stop(true,true).hide().html($msg).show();
	$('#'+$id).fadeOut(10000, function() {
       $(this).html(''); 
     });

	//document.getElementById($id).style.display = 'inline';
}

/**
	Jump to a designated <a> anchor on the page
*/
function jumpToAnchor($anchor) {
   window.location = String(window.location).replace(/\#.*$/, "") + "#" + $anchor;
}

/**
	Returns the portion of the URI specifying the ajaxPageController.
	
	Usage:	var url = getAjaxCtl("basketUpdateDonation") + "&donation_id=" + $donation_id
*/
function getAjaxCtl($action) {
	return "app.php?page=ajax&action=" + $action;
}

/**
	Displays a TipBox at the top of the page.  Use in conjuction with jumpToAnchor() if the page is long.
*/
function displayTipBox($tipmsg) {
	document.getElementById("kvTipBox").style.display = "inline";
	
 	return document.getElementById("kvTipBoxfg").innerHTML = $tipmsg;
}


function sleep(milliseconds)
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < milliseconds);
} 

/** BEHAVIOR FUNCTIONS **/

/** Functions for recommending Journals **/
function recommendJournal(entryId) {
	var url = getAjaxCtl("recommendJournal") + "&journalId=" + entryId;
	http.open("GET", url, true);
	http.onreadystatechange = recommendJournalResponse;
	document.getElementById('loading' + entryId).style.visibility = "visible";
	http.send(null);
}

function recommendJournalResponse() {
	if (http.readyState == 4) {

		// Split the comma delimited response into an array
		results = http.responseText.split(",");

		entryId = results[0];
		spanId  = 'numRecs' + entryId;
		numRecommendations = results[1];

		if (numRecommendations == 1) {
			document.getElementById(spanId).innerHTML = numRecommendations + ' recommendation';
		} else {
			document.getElementById(spanId).innerHTML = numRecommendations + ' recommendations';
		}
		document.getElementById('recommend' + entryId).value = 'Recommended';
		document.getElementById('recommend' + entryId).onclick = '';

		document.getElementById('loading' + entryId).style.visibility = "hidden";
	}
}

///////////////////////////
//Autolending Stuff
///////////////////////////
function tryAutolendingCriteria( ) {
	
	// params will be an '&'-separated list for sending over POST
	var $params = "";
	
	if ($("#keywordOn").attr("checked")) {
		$params += "keyword=" + $("#keywordText").val() + "&";
	}
	if ($("#minRiskRatingOn").attr("checked")) {
		$params += "risk_rating_min=" + $("input[name=minRiskRatingValue]").val() + "&";
	}
	if ($("#genderOn").attr("checked")) {
		$params += "gender=" + $("input[name='genderValue']:checked").val() + "&";
	}
	
	// figure out which countries, sectors, and partners were selected
	var $countryOn = $("#countryOn").attr("checked");
	var $sectorOn = $("#sectorOn").attr("checked");	
	var $partnerOn = $("#partnerOn").attr("checked");	
	var $allChecked = $(":input:checked");

	var $countries = new Array();
	var $sectors = new Array();
	var $partners = new Array();
	for ($i = 0; $i < $allChecked.length; $i++) {
		if ($countryOn && ($allChecked[$i].name.indexOf('country_') == 0)) {
			$countries.push($allChecked[$i].value);
		} else if ($sectorOn && ($allChecked[$i].name.indexOf('sector_') == 0)) {
			$sectors.push($allChecked[$i].value);
		} else if ($partnerOn && ($allChecked[$i].name.indexOf('partner_') == 0)) {
			$partners.push($allChecked[$i].value);
		}
	}
	
	$countriesList = $countries.join(',');
	$sectorsList = $sectors.join(',');
	$partnersList = $partners.join(',');

	if ($countries.length > 0) {
		$params += "countries=" + $countriesList + "&";
	}
	if ($sectors.length > 0) {
		$params += "sectors=" + $sectorsList + "&";
	}
	if ($partners.length > 0) {
		$params += "partners=" + $partnersList + "&";
	}
	
	// notify user that the page is updating
	$('#percentMatchedHtml').html("<span style='font-size: 13px; color: grey;'>Calculating...</span>");

	// perform AJAX magic
	var url = getAjaxCtl("tryAutolendingCriteria");
	http.open("POST", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", $params.length);
	http.setRequestHeader("Connection", "close");
	http.onreadystatechange = tryAutolendingCriteriaResponse;	
	http.send($params);
}

function tryAutolendingCriteriaResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');

		if ($results.showWarning) {
			$('#rareMatchWarning').show();
			$('#percentMatchedHtml').html("<span class='warning'>" + $results.percentMatched + "%</span>");
		} else {
			$('#rareMatchWarning').hide();
			$('#percentMatchedHtml').html($results.percentMatched + "%");
		}
		
		$('#businessPhoto').html($results.businessPhotoHtml);
		$('#entrepNameHtml').html($results.entrepNameHtml);
		$('#entrepCountText').html($results.entrepCountText);
		$('#entrepSector').html($results.entrepSector);
		$('#countryName').html($results.countryName);
		$('#partnerName').html($results.partnerName);
		$('#entrepDescriptionHtml').html($results.entrepDescriptionHtml);
	}
}


///////////////////////////
//Basket Stuff
///////////////////////////
/**
 * Reassign shares to a different team 
 */
 function reassignTeamShares($user_id, $business_id) {
 	var $new_team_id = document.getElementById('biz_team_'+$business_id).value;
 	
 	var url = getAjaxCtl("reassignTeamShares") + "&user_id=" + $user_id + "&business_id=" + $business_id + "&new_team_id=" + $new_team_id;
	http.open("GET", url, true);
	http.onreadystatechange = reassignTeamSharesResponse;
	document.getElementById('loading_biz_team_' + $business_id).src = "images/loading_ajax.gif";
	http.send(null);
 }
 
 function reassignTeamSharesResponse() {
 	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');

		$num_shares_changed = $results.num_shares_changed;
		$new_team_id 		= $results.new_team_id;
		$business_id 		= $results.business_id;
		
		// hide the loading gif
		document.getElementById('loading_biz_team_'+$business_id).style.display = "none";
		
		if ($num_shares_changed > 0) {
			alert($num_shares_changed + ' shares have been reassigned to team ' + $new_team_id);
		} else {
			alert('No shares have been reassigned.');
		}
 	}
 }
 
 
/** Add loan to basket from LEND page */
function addToBasket(loan_id) {
	var url = getAjaxCtl("addToBasket") + "&loan_id=" + loan_id;
	http.open("GET", url, true);
	http.onreadystatechange = addToBasketResponse;
	document.getElementById('addToBasket' + loan_id).src = "images/loading_ajax.gif";
	http.send(null);
}

function addToBasketResponse() {
	if (http.readyState == 4) {
		// Split the comma delimited response into an array
		results = http.responseText.split(",");

		success = results[0];
		loan_id = results[1];
		basket_error = results[2];
		
		document.getElementById('addToBasket' + loan_id).style.visibility = "hidden";
		document.getElementById('addToBasket' + loan_id).onclick = '';
		
		span_id = 'span' + loan_id;
		
		if (success > 0) {
			document.getElementById(span_id).innerHTML = '<a href="app.php?page=basket">Loan added!  Checkout >></a>';
		} else if (basket_error>0) {
			document.getElementById(span_id).innerHTML = '<span style="color: red">Error adding item! <a href="javascript:pop(\'pages/businesses/why_server_error.html\', \'Kiva_Help\', 300, 300)">Help</a></span>';			
		} else {
			document.getElementById(span_id).innerHTML = '<span style="color: red">Loan already funded! <a href="javascript:pop(\'pages/businesses/why_already_funded.html\', \'Kiva_Help\', 300, 300)">Help</a></span>';
		}	
	}

}


/** Update loan amounts from basket page */
function basketUpdateLoan(loan_id) {
	var new_value = document.getElementById('loan'+loan_id).value;
	var url = getAjaxCtl("basketUpdateLoan") + "&loan_id=" + loan_id + "&loan" + loan_id + "=" + new_value;
	if (document.getElementById('loan_team'+loan_id)){
		url+="&team_id="+document.getElementById('loan_team'+loan_id).value;
	}
	
	http.open("GET", url, true);
	http.onreadystatechange = basketUpdateLoanResponse;
	document.getElementById('loading_loan'+loan_id).style.display = "inline";
	http.send(null);
}

function basketRemoveLoan(loan_id) {
	$entrep_name = document.getElementById("loan_name"+loan_id).innerHTML;
	var answer = confirm ("Are you sure you want to remove your loan to " + $entrep_name + "?");
	if (answer) {
		var new_value = 0;
		var url = getAjaxCtl("basketUpdateLoan") + "&loan_id=" + loan_id + "&loan" + loan_id + "=" + new_value;
		
		http.open("GET", url, true);
		http.onreadystatechange = basketUpdateLoanResponse;
		document.getElementById('loading_loan'+loan_id).style.display = "inline";
		http.send(null);
	}
}

function basketUpdateLoanResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');

		$loan_id      = $results.loan_id;
		$new_amount   = $results.new_amount;
		$loan_total   = $results.loan_total;
		$grand_total  = $results.grand_total;
		$tipmsg		  = $results.tipmsg;
		
		$loan_total_id   	= 'loan_total' + $loan_id;
		$select_id		 	= 'loan' + $loan_id;
		$all_loans_total_id = 'all_loans_total';
		$grand_total_id		= 'grand_total';
		$table_row_id		= 'loan_row' + $loan_id;
		$conf_msg_id		= 'loan_msg_' + $loan_id;

		// remove the table row?
		if ($new_amount == 0) {
			document.getElementById($table_row_id).style.display = "none";
		}

		// hide the loading gif
		document.getElementById('loading_loan'+$loan_id).style.display = "none";
		
		// reset the loan total
		document.getElementById($loan_total_id).innerHTML = '$' + $new_amount + '.00';
		
		// reset the select box (only necessary if selected amount was not able to be added)
		document.getElementById($select_id).value = $results.new_amount;
		
		// @todo SAFARI dies here for some reason
		// reset the sum total of all loans
		if (document.getElementById($all_loans_total_id)) {
			document.getElementById($all_loans_total_id).innerHTML = '$' + $loan_total + '.00';
		}
		
		// reset the grand total
		document.getElementById($grand_total_id).innerHTML = '$' + $grand_total + '.00';
		
		// display the confirmation message
		displayAndFade($conf_msg_id, $tipmsg);
	}
}

function basketAssignLoanToTeam(loan_id) {
	var team_id = document.getElementById('loan_team'+loan_id).value;
	var url = getAjaxCtl("basketAssignLoanToTeam") + "&loan_id=" + loan_id + "&team_id=" + team_id;
	
	http.open("GET", url, true);
	http.onreadystatechange = basketAssignLoanToTeamResponse;
	document.getElementById('loading_team'+loan_id).style.display = "inline";
	http.send(null);
}

function basketAssignLoanToTeamResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');
		$loan_id = $results.loan_id;
		
		document.getElementById('loading_team'+$loan_id).style.display = "none";
	}
}

/** Update Gifts from Basket */
function basketUpdateGift($gift_id) {
	var new_value = document.getElementById('gift'+$gift_id).value;
	var url = getAjaxCtl("basketUpdateGift") + "&gift_id=" + $gift_id + "&gift" + $gift_id + "=" + new_value;

	http.open("GET", url, true);
	http.onreadystatechange = basketUpdateGiftResponse;
	document.getElementById('loading_gift'+$gift_id).style.display = "inline";
	http.send(null);
}

function basketRemoveGift(gift_id) {
	var answer = confirm ("Are you sure you want to remove this gift?");
	if (answer) {
		var new_value = 0;
		var url = getAjaxCtl("basketUpdateGift") + "&gift_id=" + gift_id + "&gift" + gift_id + "=" + new_value;
		
		http.open("GET", url, true);
		http.onreadystatechange = basketUpdateGiftResponse;
		document.getElementById('loading_gift'+gift_id).style.display = "inline";
		http.send(null);
	}
}

function basketUpdateGiftResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');
	
		$gift_id      = $results.gift_id;
		$new_amount   = $results.new_amount;
		$gift_total   = $results.gift_total;
		$grand_total  = $results.grand_total;
		$tipmsg		  = $results.tipmsg;
		
		$gift_total_id   	= 'gift_total' + $gift_id;
		$select_id		 	= 'gift' + $gift_id;
		$all_gifts_total_id = 'all_gifts_total';
		$grand_total_id		= 'grand_total';
		$table_row_id		= 'gift_row' + $gift_id;
		$conf_msg_id		= 'gift_msg_' + $gift_id;

		// remove the table row?
		if ($new_amount == 0) {
			document.getElementById($table_row_id).style.display = "none";
		}

		// hide the loading gif
		document.getElementById('loading_gift'+$gift_id).style.display = "none";
		
		// reset the gift total
		document.getElementById($gift_total_id).innerHTML = '$' + $new_amount + '.00';
		
		// reset the select box (only necessary if selected amount was not able to be added)
		document.getElementById($select_id).value = $results.new_amount;
		
		// @todo SAFARI dies here for some reason
		// reset the sum total of all gifts
		if (document.getElementById($all_gifts_total_id)) {
			document.getElementById($all_gifts_total_id).innerHTML = '$' + $gift_total + '.00';
		}
		
		// reset the grand total
		document.getElementById($grand_total_id).innerHTML = '$' + $grand_total + '.00';
		
		// display the confirmation message
		displayAndFade($conf_msg_id, $tipmsg);
	}
}

/** Update Donations from Basket */
function basketUpdateDonation($donation_id) {
	var new_value = document.getElementById('donation'+$donation_id).value;
	var url = getAjaxCtl("basketUpdateDonation") + "&donation_id=" + $donation_id + "&donation" + $donation_id + "=" + new_value;

	http.open("GET", url, true);
	http.onreadystatechange = basketUpdateDonationResponse;
	document.getElementById('loading_donation'+$donation_id).style.display = "inline";
	http.send(null);
}

function basketRemoveDonation(donation_id) {
	var answer = confirm ("Are you sure you want to remove this donation to Kiva?");
	if (answer) {
		var new_value = 0;
		var url = getAjaxCtl("basketUpdateDonation") + "&donation_id=" + donation_id + "&donation" + donation_id + "=" + new_value;
	
		http.open("GET", url, true);
		http.onreadystatechange = basketUpdateDonationResponse;
		document.getElementById('loading_donation'+donation_id).style.display = "inline";
		http.send(null);
	}
}

function basketUpdateDonationResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');

		$donation_id      = $results.donation_id;
		$new_amount   = $results.new_amount;
		$donation_total   = $results.donation_total;
		$grand_total  = $results.grand_total;
		$tipmsg		  = $results.tipmsg;
		
		$donation_total_id   	= 'donation_total' + $donation_id;
		$select_id		 	= 'donation' + $donation_id;
		$all_donations_total_id = 'all_donations_total';
		$grand_total_id		= 'grand_total';
		$table_row_id		= 'donation_row' + $donation_id;
		$conf_msg_id		= 'donation_msg_' + $donation_id;

		// remove the table row?
		if ($new_amount == 0) {
			document.getElementById($table_row_id).style.display = "none";
		}

		// hide the loading gif
		document.getElementById('loading_donation'+$donation_id).style.display = "none";
		
		// reset the donation total
		document.getElementById($donation_total_id).innerHTML = '$' + $new_amount + '.00';
		
		// reset the select box (only necessary if selected amount was not able to be added)
		document.getElementById($select_id).value = $results.new_amount;
		
		// @todo SAFARI dies here for some reason
		// reset the sum total of all donations
		if (document.getElementById($all_donations_total_id)) {
			document.getElementById($all_donations_total_id).innerHTML = '$' + $donation_total + '.00';
		}
		
		// reset the grand total
		document.getElementById($grand_total_id).innerHTML = '$' + $grand_total + '.00';
		
		// display the confirmation message
		displayAndFade($conf_msg_id, $tipmsg);
	}
}

/** Lend tab **/

var getFundingCounter = 0;

function getFundingInfo(biz_ids) {
	this.biz_ids = biz_ids;
	getFundingCounter++;	
	if (biz_ids && getFundingCounter < 11) {
		// Call AjaxPageController::getFundingInfo
		var url = getAjaxCtl("getFundingInfo");
		
		// Pass all the biz_ids on the page
		var params = "biz_ids=" + biz_ids;
		
		http.open("POST", url, true);
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");
		http.onreadystatechange = getFundingInfoResponse;
		http.send(params);

		interval = window.setTimeout(function(){ this.getFundingInfo(this.biz_ids); }, 30000);
	}
}

function getFundingInfoResponse() {
	if (http.readyState == 4) {
		// Pull the results array off the http response
		results = eval('(' + http.responseText + ')');
		// for each business, dynamically update the row on the Lend tab
		for(biz_id in results) {
  			funding_info = results[biz_id];
  			// pull everything out of the array to make things easier to read
  			loan_status = funding_info['status'];
  			in_baskets = Number(funding_info['in_baskets']); 
  			amount_raised = Number(funding_info['amount_raised']);
  			loan_amount = Number(funding_info['loan_amount']);
  			
  			// The thermometers show amt_raised for fundRaising loans, amt_repaid for all others
  			if (loan_status == 'fundRaising') {
  				percent_paid = Math.round((in_baskets + amount_raised) / loan_amount * 100);	
				
				// Update DOM (see loanStatusBar.tpl)
				$('#'+biz_id+'_percent_paid').text(percent_paid + '%');
				$('#'+biz_id+'_bar0').css({'width' : percent_paid + 'px'});
				$('#'+biz_id+'_bar1').css({'width' : (100 - percent_paid) + 'px'});

				if (in_baskets + amount_raised == loan_amount) { 
					$('#biz_row_' + biz_id).children().fadeTo('slow', 0.33);
					$('#funding' + biz_id).hide()
					$('#funded' + biz_id).show()
				}
				else {
					$('#biz_row_' + biz_id).children().fadeTo('slow', 1);
					$('#funding' + biz_id).show()
					$('#funded' + biz_id).hide()
				}
			}
		}
	}
}

/** Kiva_Map stuff **/
function getLatLongs($addresses, $callback) {
	if($addresses) {
		var url = getAjaxCtl("getLatLongs");
		var params = "addresses=" + $addresses;
		http.open("POST", url, true);
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");

		http.onreadystatechange = getLatLongsResponse;
		http.send(params);
	}
}

var lender_addresses = [];

function getLatLongsResponse() {
	if (http.readyState == 4) {
		// @todo let's get this working sometime, eh?
		//lender_addresses = eval('(' + http.responseText + ')');
	}
}

function getLenderLat($md5_address) {	
	for(address in lender_addresses) {
  		if (address == $md5_address) { return lender_addresses[$md5_address]["lat"]; }
	}
	
	return null;
}

function getLenderLon($md5_address) {
	for(address in lender_addresses) {
  		if (address == $md5_address) { return lender_addresses[$md5_address]["lon"]; }
	}
	
	return null;
}


/** Team stuff */

/*
 * Accepts a request to join a team.  Should only be used by captains.
 */
function acceptRequest($team_id, $user_id) {
	var url = getAjaxCtl("acceptRequest") + "&team_id=" + $team_id + "&user_id=" + $user_id;
	http.open("GET", url, true);
	http.onreadystatechange = acceptRequestResponse;
	document.getElementById('accept_u'+$user_id+'t'+$team_id).src = "images/loading_ajax.gif";
	http.send(null);
}

function acceptRequestResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');
		
		$team_id = $results.team_id;
		$user_id = $results.user_id;
		$element_id = 'u' + $user_id + 't' + $team_id;
		
		if ($results.errmsg != null) {
			document.getElementById($element_id).innerHTML = '<span style="color: red">' + $results.errmsg + '</span>';	
		} else {
			document.getElementById($element_id).innerHTML = $results.tipmsg; 
		}
	}
}

/*
 * Rejects a request to join a team.  Should only be used by captains.
 */
function rejectRequest($team_id, $user_id) {
	var url = getAjaxCtl("rejectRequest") + "&team_id=" + $team_id + "&user_id=" + $user_id;
	http.open("GET", url, true);
	http.onreadystatechange = rejectRequestResponse;
	document.getElementById('reject_u'+$user_id+'t'+$team_id).src = "images/loading_ajax.gif";
	http.send(null);
}

function rejectRequestResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');
		
		$team_id = $results.team_id;
		$user_id = $results.user_id;
		$element_id = 'u' + $user_id + 't' + $team_id;
		
		if ($results.errmsg != null) {
			document.getElementById($element_id).innerHTML = '<span style="color: red">' + $results.errmsg + '</span>';	
		} else {
			document.getElementById($element_id).innerHTML = $results.tipmsg; 
		}
	}
}


/** Activate reviewed businesses from Kiva Admin */
function activateBusiness(biz_id) {
	var url = getAjaxCtl("activateBusiness") + "&business_id=" + biz_id;
	http.open("GET", url, true);
	http.onreadystatechange = activateBusinessResponse;
	document.getElementById('activate' + biz_id).innerHTML = '<img src="images/loading_ajax.gif"/>';
	http.send(null);
}

function activateBusinessResponse() {
if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');
		$span_id = 'activate' + $results.business_id;
		if ($results.tipmsg != null) {
			document.getElementById($span_id).innerHTML = $results.tipmsg;	
		} else {
			document.getElementById($span_id).innerHTML = '<span style="color: red">' + $results.errmsg + '</span>';
		}
	}
}

function runIntegrityTest($classname,$method) {
	var url = getAjaxCtl("runIntegrityTest") + "&class=" + $classname+"&method="+$method;
	http.open("GET", url, true);
	http.onreadystatechange = runIntegrityTestResponse;
	document.getElementById($method+'_'+$classname).innerHTML = '<img src="images/loading_ajax.gif"/>';
	http.send(null);
}

function runIntegrityTestResponse() {
	if (http.readyState == 4) {
		$results = eval('(' + http.responseText + ')');

		$class = $results.classname;
		$msg = $results.msg;
		$method = $results.method;
		
		document.getElementById($class).innerHTML = $msg;
		document.getElementById($method+'_'+$class).innerHTML = '';
	}
}


/**

AJAX Framework Functions

**/

function getHTTPObject() {

	var xmlhttp;

	/*@cc_on

	@if (@_jscript_version >= 5)

	try {

	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

	} catch (e) {

	try {

	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

	} catch (E) {

	xmlhttp = false;

	}

	}

	@else

	xmlhttp = false;

	@end @*/

	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {

		try {

			xmlhttp = new XMLHttpRequest();

		} catch (e) {

			xmlhttp = false;

		}

	}

	return xmlhttp;

}
