var updateType = new Array();
var imageToUpdate;
var countryList;
var locationList;

function getAllProjects(showLanguage) {
	var url;

	if (showLanguage == "false")
		url = "/scripts/ajax/load_projects.php?language=false";
	else url = "/scripts/ajax/load_projects.php";
	
	$.ajax({
		type: "GET",
		url: url,
		dataType: "xml",
		success: function(request,success){loadAllProjects(request);},
		error: function(XMLHttpRequest, textStatus, errorThrown){ajaxFailed(XMLHttpRequest, textStatus, errorThrown);}
	});
}

function loadAllProjects(request){
	countryList = request.getElementsByTagName("country");
}



function loadProjects(selectToUpdate,selectedCountry){

	try{
		var options = "";
		selectToUpdate.html("");
				
		if (selectedCountry == "")return false;
    	
    	for (var x=0; x<countryList.length; x++) {
    		if (countryList[x].getAttribute("name") == selectedCountry){
    			project = countryList[x].getElementsByTagName("project")
    			
    			for (var y=0; y<project.length; y++) {
	    			projectName = project[y].childNodes[0].nodeValue;
	    			options = options += '<option value="' + projectName + '">' + projectName + '</option>';
    			}
    	   	}
		}

		if (project.length > 1)	options = '<option value=""></option>' + options;
	
		selectToUpdate.html(options);
		
		//if (project.length == 1)selectToUpdate.change();
		}
	catch (e)
	{//there was no response or the attribute didn't exist - ie only
		alert(e.message);
		return false;
	}
}

/* empty fields ralting to a project */
function emptyProjectDetails(nb)
{
	i = nb.substring(2);
	$("#start_date_" + nb).html('');
	$("#end_date_" + nb).val('');
	$("#duration_" + nb).html('');
	$("#placement_fee_" + nb).val('');
	$("#program_fee_" + nb).val('');
	$("#bottom_program_fee_" + nb).val('');
	$("#lang_fee_" + nb).val('');
	$("#add_on_fee_" + nb).val('');
	$("#prog_additions_list_" + nb).html('');
	$("#prog_additions_list_" + nb).hide();
	$("dl#lang_date_" + nb).hide();
	$("#prog_additions_" + nb).hide();
	$("#no_prog_additions_" + nb).show();
	$("dl#add_on_fee_list_" + nb).hide();
	$("dl#lang_fee_list_" + nb).hide();
	
	priceArray[i] = new Array;
	languageArray[i] = new Array;
	
	if (addOnArray != undefined && addOnArray[i] != undefined && addOnArray[i].length > 0)
	{
		for(x = 0; x < addOnArray[i].length; x++)
		{
			addOnArray[i][x] = 0;
		}
	}	
	
	calculateTotal();
}

function countryChange(caller){
	var nb = caller.attr("id").substring(caller.attr("id").indexOf("nb"));
	loadProjects($("#project_" + nb),caller.val()); 
	getProjectImageCountry(caller.val(),$("#placement_image_" + nb));
	$("#project_" + nb).change();
	return false;	
}


function projectChange(caller){
	var nb = caller.attr("id").substring(caller.attr("id").indexOf("nb"));
	
	$('#placement_header_text_' + nb).text(caller.val());
	
	if (caller.val()== "" || caller.val()== null)
	{//the user has changed the value back to All so empty project fields
		emptyProjectDetails(nb);
		return false;
	}
	
	getProjectExtras(caller.val(),$("#country_" + nb).val(),nb,$("#lang_duration_" + nb));
	
	getProjectImage(caller.val(),$('#placement_image_' + nb));
	
	//load project extras and dates if this isn't blank.
	loadDates(nb,$("#start_date_" + nb),
		$("#duration_" + nb),caller.val(),
		$("#country_" + nb).val(),
		$("#placement_fee_" + nb)); 	
		
	return false;
}

//load get language school and add on data 
function getProjectExtras(project,country,nb,currentDurationValue)
{
	$.ajax({
		type: "GET",
		url: "/scripts/ajax/load-project-extras.php?project=" + project + "&country=" + country,
		dataType: "xml",
		success: function(request,success){updateProjectExtras(request,nb,currentDurationValue);},
		error: function(XMLHttpRequest, textStatus, errorThrown){ajaxFailed(XMLHttpRequest, textStatus, errorThrown);}
	});
	
	return false;
}

//load language school and add on data
function updateProjectExtras(request,nb,currentDurationValue)
{
	var currency = request.getElementsByTagName("extra_data");
	var response = request.getElementsByTagName("language_school");
	var durationOptions = "<option selected=\"selected\" value=\"\">No Thanks</option>";
	var currentExists = false; 
	var n = nb.substring(2);
	var currentLangValue = currentDurationValue.val();
	try{
		var school_name = response[0].getAttribute("name");
		var school_id = response[0].getAttribute("id");
		var arrival_day = response[0].getAttribute("arrival_day");
		var project_type = response[0].getAttribute("project_type");
		
		if(school_name == "none")
		{//no language school is available for this project so hide it
			$("ul#lang_date_" + nb).hide();
			$("#lang_project_" + nb).val('');
			$("#lang_project_id_" + nb).val('');
			$("#lang_arrival_day_" + nb).val('');
			$("#lang_project_type_" + nb).val('');
			$("#lang_fee_" + nb).val('');
			$("dl#lang_date_" + nb).hide();
			$("div.lang-detail_" + nb).hide();
			languageArray[n] = new Array;
		}
		else {//results found
			var weeks = request.getElementsByTagName("duration")
			$("#lang_project_" + nb).val(school_name);
			$("#lang_project_id_" + nb).val(school_id);
			$("#lang_arrival_day_" + nb).val(arrival_day);
			$("#lang_project_type_" + nb).val(project_type);
			$("dl#lang_fee_list_" + nb).show();
			
			for (var y=0; y<weeks.length; y++) {
       			actual = weeks[y].getAttribute("name");
				text = weeks[y].childNodes[0].nodeValue;
				if (actual == currentLangValue)currentExists = true; 
				durationOptions = durationOptions + '<option value="' + actual + '">' + text + '</option>';
       		}
			$("#lang_duration_" + nb).html();
			$("#lang_duration_" + nb).html(durationOptions);
			$("dl#lang_date_" + nb).show();

			if (currentExists)$("#lang_duration_" + nb).val(currentLangValue); 	 

			$("#lang_duration_" + nb).change();
			
		}
		var additionalData = request.getElementsByTagName("additional_data");
		
		//empty the add on price array
		addOnArray[n] = new Array;
		
		if(additionalData.length == 0)
		{//there are no add ons for this project
			$("div#prog_additions_" + nb).hide();
			$("div#no_prog_additions_" + nb).show();
			$("dl#add_on_fee_list_" + nb).hide();
		}
		else
		{//add ons exist so create options for them
			var addOns = additionalData[0].getElementsByTagName("add_on");
			var addOnHtml = "";
			var title;
			var name;
			var id;
			var name = Array();
			var optionValue;
			for (var y=0; y<addOns.length; y++) {
				
				title = addOns[y].getAttribute("title");
				id = addOns[y].getAttribute("id");
				name[y] = "add_on_option_optn" + y + "_pgid" + id + "_" + nb;
				addOnHtml += "<li><label for="  +  "\"option_" + y  + "\">" + title + "</label>"; 
				addOnHtml += "<select class=\"add_on\" name=\"" + name[y] + "\" id=\"" +  name[y] + "\" >";
				options = addOns[y].getElementsByTagName("option");
				
				for (var x=0; x<options.length; x++) {
					addOnHtml += "<option value=\"" + options[x].getAttribute("value") + "\">" + options[x].firstChild.nodeValue + "</option>\n";
				}
				addOnHtml += "</select>";
			}
			$("div#no_prog_additions_" + nb).hide();
			$("ul#prog_additions_list_" + nb).html();
			$("ul#prog_additions_list_" + nb).html(addOnHtml);
			$("div#prog_additions_" + nb).show();
			$("ul#prog_additions_list_" + nb).show();
			$("dl#add_on_fee_list_" + nb).show();

			//bind change functions to all the addons
			for (var y=0; y<addOns.length; y++) {
				$('#' + name[y]).bind("change", function(){
				  	addOnChange($(this));
				});		
			}
		}

		return false;		
	}
	catch (e)
	{//there was no response or the attribute didn't exist - ie only
		alert(e.message);
		return false;
	}
}	


function durationChange(caller)
{
	var nb = caller.attr("id").substring(caller.attr("id").indexOf("nb"));
	setEndDate($("#start_date_" + nb),$("#duration_" + nb),$("#end_date_" + nb),$("#sql_end_date_" + nb));
	duration = caller.val().substring(0,caller.val().indexOf("_"));	

	recalculateAddOns(nb,parseFloat(duration) / 7);
	reloadPricing();
}

function recalculateAddOns(nb,duration)
{
	var i = nb.substring(2);
	
	if (addOnArray[i] != undefined)
	{
		for (n = 0;n < addOnArray[i].length;n++)
		{
			if (addOnArray[i][n] != undefined && " " + addOnArray[i][n].indexOf("wr") != -1)
			{
				newPrice = addOnArray[i][n].substring(0,addOnArray[i][n].indexOf("wr") + 2);			
				$("#add_on_fee_" + nb).val(newPrice);
				addOnArray[i][n] = newPrice + duration;
			}
		}
	}	
	return false;
}
	

function removePlacement(caller)
	{
	try{
		var nb = caller.attr("id").substring(caller.attr("id").indexOf("nb"));
		var answer = confirm("Remove this placement?");
		if (!answer)
			return false;

		/* remove price array elements */
		priceArray.splice(noOfPlacements,1);
		languageArray.splice(noOfPlacements,1)
		addOnArray.splice(noOfPlacements,1)
		
		$("div#program_container").children(":last-child").remove();
		
		noOfPlacements = noOfPlacements - 1;
		$("#no_of_placements").val(noOfPlacements);
		
		if (noOfPlacements > 1)//add remove button to the last placement
			$("#remove_placement_nb" + noOfPlacements).show();
		
		$.ajax({
		type: "GET",
		url: "/scripts/ajax/remove-placement.php?id=" + nb,
		dataType: "xml",
		success: function(request,success){return false;},
		error: function(XMLHttpRequest, textStatus, errorThrown){ajaxFailed(XMLHttpRequest, textStatus, errorThrown);}
		});
		calculateTotal();
		return false;
	}
	catch (e)
	{
		showErrorMessage(e.message);
		return false;
	}
}
	
function addNewPlacement(){
	
	if (noOfPlacements > 8)
	{//max placements is 9, any more and we'd have problems with nb10 matching nb1
		alert("Maximum number of placements reached");
		return false;
	}	
	try{
		var oldDivNb = noOfPlacements;
		noOfPlacements = noOfPlacements + 1;
		$("#no_of_placements").val(noOfPlacements);
		priceArray[noOfPlacements] = 0;
		languageArray[noOfPlacements] = 0;
		addOnArray[noOfPlacements] = new Array();
		
		var placements = $("div#program_container").children("div.body_inner_860:last").html();
		
		var newDivNb = noOfPlacements;
		var nb = "nb" + newDivNb;
		var repString = 'nb' + oldDivNb;
		var re = new RegExp(repString, "g");/*we need to create a regExp object otherwise we can't put variables in our expression - the /g means global/replace all*/
		placements = placements.replace(re, "nb" + noOfPlacements);
		$("div#program_container").append("<div class=\"body_inner_860\">" + placements + "</div>");
		
		/* bind functions to newly created elements */
		$("#country_" + nb).bind("change", function(){
				  countryChange($("#country_" + nb));
				});
		$("#project_" + nb).bind("change", function(){
				  projectChange($("#project_" + nb));
				});	
				
		$("#duration_" + nb).bind("change", function(){
				  durationChange($("#project_" + nb));
				});			
		
		$("#start_date_" + nb).bind("change", function(){
				  projectChange($("#project_" + nb));
				});	
		
		$("#lang_duration_" + nb).bind("change", function(){
				  languageChange($("#lang_duration_" + nb));
				});
		
		headerText = $("#placement_header_" + nb).html().replace(oldDivNb,newDivNb);
		$("#placement_header_" + nb).html(headerText);
		$("#placement_header_text_" + nb).text('');
		
		
		$("#remove_placement_" + nb).bind("click", function(){
			 removePlacement($("#remove_placement_" + nb));
			 return false;
			});
		$("#error_" + nb).hide();	
		$("#remove_placement_nb" + oldDivNb).hide();
		$("#remove_placement_" + nb).show();
		$("#project_" + nb).html("");//empty project select
		$("#country_" + nb).val("");//reset country select
		$("#duration_" + nb).html("");//reset duration select
		$("#start_date_" + nb).html("");
		$("#end_date_" + nb).val("");
		$("#lang_date_" + nb).css("display","none");
		$("#bottom_program_fee_" + nb).val("-");
		$("#placement_fee_" + nb).val("-");
		$("div#no_prog_additions_" + nb).show();
		$("div#prog_additions_" + nb).hide();
		$("#lang_fee_" + nb).val("-");
		$("#add_on_fee_" + nb).val("-");
		$("li#add_on_fee_list_" + nb).hide();
		$("li#lang_fee_list_" + nb).hide();
		
		$("#placement_image_" + nb).attr("src","/costa-rica/images/thumbnails/tn-volunteer-travel-abroad.jpg");
		return false;
	}
	catch (e)
	{
		alert(  "An error occurred! " 
       + (e.number      || e.name   ) + ": " 
       + (e.description || e.message) ); 
		showErrorMessage(e.message);
		return false;
	}
}
	
function reloadPricing()
{
	var nb;
	var ajaxString = "";
	
	for (i = 1; i <= noOfPlacements;i++)
	{
		nb = "nb" + i; 
		ajaxString = ajaxString + "&project_" + nb + "=" + $("#project_" + nb).val() + "&";
		ajaxString = ajaxString + "country_" + nb + "=" + $("#country_" + nb).val() + "&";
		ajaxString = ajaxString + "duration_" + nb + "=" + $("#duration_" + nb).val() + "&";
		ajaxString = ajaxString + "start_date_" + nb + "=" + $("#start_date_" + nb).val();
	}
	
	$.ajax({
	type: "GET",
	url: "/scripts/ajax/load-prices.php?placements=" + noOfPlacements + ajaxString,
	dataType: "xml",
	success: function(request,success){updatePricing(request);},
	error: function(XMLHttpRequest, textStatus, errorThrown){ajaxFailed(XMLHttpRequest, textStatus, errorThrown);}
	});
	
	return false;
	
}
	
function updatePricing(request)
{
	var response = request.getElementsByTagName("price");
	var totalPrice;

	for (i = 1;i <= noOfPlacements;i++)
	{
		price = response[0].getAttribute("nb" + i + "_price");
		
		if (price == "-")
		{
			priceArray[i] = 0;
			totalPrice = 0 + parseFloat(languageArray[i]);
			$('#program_fee_nb' + i).val("-");
			$('#bottom_program_fee_nb' + i).val("-"); 			
			$('#placement_fee_nb' + i).val("-"); 
		}
		else {
			priceArray[i] = parseFloat(price);
			price = roundToCurrency(price);
			totalPrice = roundToCurrency(parseFloat(price) + parseFloat(languageArray[i]));
			$('#bottom_program_fee_nb' + i).val(price + " " + currencyCode); 
			$('#program_fee_nb' + i).val(price + " " + currencyCode); 
			$('#placement_fee_nb' + i).val(totalPrice + " " + currencyCode); 
		}
	}
	calculateTotal();
	
}
	
function calculateTotal()
{
	var totalPrice = 0;
	var thisProjectPrice;
	var thisAddOnPrice;
	
	for (i = 1;i < priceArray.length; i++)
	{
		if (priceArray[i] == undefined || priceArray[i] == '')priceArray[i] = 0;
		
		thisProjectPrice = parseFloat(priceArray[i]);
		if (languageArray[i] != undefined && languageArray[i] != '')
			{
			thisProjectPrice = parseFloat(thisProjectPrice) + parseFloat(languageArray[i]); 
			}
			
		thisAddOnPrice = 0;
		if (addOnArray != undefined && addOnArray[i] != undefined)
		{
			for(x = 0; x <= addOnArray[i].length; x++)
			{
				if (addOnArray[i][x] != undefined && addOnArray[i][x] != "")
				{
					if (addOnArray[i][x].indexOf("wr") != -1)
					{//some adds on are priced weekly - data is stored as price+"wr"+weeks multiply these out 
						duration = addOnArray[i][x].substring(addOnArray[i][x].indexOf("wr")+2);
						price = addOnArray[i][x].substring(0,addOnArray[i][x].indexOf("wr"));
						thisAddOnPrice = thisAddOnPrice + parseFloat(price * duration);
					}
					else thisAddOnPrice = thisAddOnPrice + parseFloat(addOnArray[i][x]);
				}
			}
			$('#add_on_fee_nb' + i).val(roundToCurrency(thisAddOnPrice) + " " + currencyCode); 
		}
				
		thisProjectPrice = thisProjectPrice + thisAddOnPrice;
		
		if (thisProjectPrice == 0)
			$('#placement_fee_nb' + i).val("-"); 
		else $('#placement_fee_nb' + i).val(thisProjectPrice + " " + currencyCode); 
		
		totalPrice = totalPrice + parseFloat(thisProjectPrice);
	}
	
	if (totalPrice == 0)
		$('#total_program_fee').val("-"); 
	else {
		$('#total_program_fee').val(roundToCurrency(totalPrice + " " + currencyCode)); 
	}
}

function addOnChange(caller)
	{
		var nb = caller.attr("id").substring(caller.attr("id").indexOf("nb"));
		var opt = caller.attr("id").substring(caller.attr("id").indexOf("optn") + 4,caller.attr("id").indexOf("optn") + 5);
		var n = nb.substring(2);
		var box = caller.attr("id");
		
		var value = $('#' + box + ' option:selected').text();
		
		if (value != "No")
		{
			value = value.substring(value.indexOf("-")+ 1);
			value = value.substring(value.indexOf(" ")+ 1);
			value = value.replace(currencyCode,'');
			
			if (value.indexOf("per week") != -1)
			{	
				value = value.substring(0,value.indexOf(" "));
				var duration = $('#duration_' + nb).val().substring(0,$('#duration_' + nb).val().indexOf("_"));
				duration = duration / 7;
				addOnArray[n][opt] = value + "wr" + duration;//store the current weeks as well - we need if we have to recalculate
			}
			else addOnArray[n][opt] = value;
		}
		else addOnArray[n][opt] = '0';
		calculateTotal();
	}		

function setEndDate(startDateField,durationField,endDateField,sqlEndDateField)
{
	var endDate = new Date;
	var durationString = durationField.val();
	var startDate = startDateField.val();
	
	if (durationString.indexOf("|") != "-1")
		durationString = durationString.substring(0,durationString.indexOf("|"));
		
	//either start date or duration is unset so cannot calculate end date
	if ((durationString === "All") || (startDate === "All"))endDateField.value = "End Date";
	else //calculate end date
	{
		var position = durationString.indexOf("_");
		var duration = durationString.substring(0,position);
		var durationInt = parseFloat(duration) - 1;
		//set month using start date
		startYear = startDate.substring(0,4);
		startMonth = startDate.substring(5,7);
		startDay = startDate.substring(8,10);
		
		startMonth = startMonth - 1;
		
		endDate.setYear(startYear);
		endDate.setMonth(startMonth);//javascript months run 0 to 11
		endDate.setDate(startDay);
		endDate.setDate(endDate.getDate()+durationInt);//add the number of days the volunteer will be staying (durationInt) to end date	
		
		monthName = getMonthName(endDate.getMonth());//set end date string format '10 September 2007', used for input box
		var monthNum = endDate.getMonth() + 1;
		if (monthNum < 10)
			monthNum = "0" + monthNum;
		
		var monthDay;
		if (endDate.getDate() < 10)
			monthDay = "0" + endDate.getDate(); else monthDay = endDate.getDate();
		
		endDateString = getWeekDay(endDate.getDay()) + " " + monthDay;	
		endDateString = endDateString + " " + monthName + " ";
		endDateString = endDateString + endDate.getFullYear();

		sqlEndDateString = endDate.getFullYear() + "-" + monthNum + "-" + monthDay; 
		alert(sqlEndDateString);
		//populate the end date input box
		endDateField.val(endDateString);
		sqlEndDateField.val(sqlEndDateString);
		alert(sqlEndDateField.val());
	}
}

function languageChange(caller)
{
	var nb = caller.attr("id").substring(caller.attr("id").indexOf("nb"));
	var i = nb.substring(2);
	
	/*show/hide details */
	if (caller.val() != "")
		$('.lang-detail_' + nb).show();
	else $('.lang-detail_' + nb).hide();
	
	var price = ($('#lang_duration_' + nb).val().substring($('#lang_duration_' + nb).val().indexOf("|") + 1));

	if (price == "")
	{
		$("#lang_fee_" + nb).val("-");
		languageArray[i] = 0;
	}
	else {
		$("#lang_fee_" + nb).val(price + " " + currencyCode);
		languageArray[i] = price;
	}
	
	languageStart(nb);
	if($("#sql_lang_start_date_" + nb).val() != null && $("#sql_lang_start_date_" + nb).val() != '')
		setEndDate($("#sql_lang_start_date_" + nb),$("#lang_duration_" + nb),$("#lang_end_date_" + nb),$("#sql_lang_end_date_" + nb));
	
	calculateTotal();
}

function languageStart(nb)
	{
	if ($('#lang_duration_' + nb).val() == "" || $('#lang_duration_' + nb).val() == null)
		{
			$('#lang_start_date_' + nb).val("");
			$('#sql_lang_start_date_' + nb).val("");
		}
		else {
			newDate = new Date;
			newDate = calculateStart(nb);
			$('#lang_start_date_' + nb).val(newDate[0]);
			$('#sql_lang_start_date_' + nb).val(newDate[1]);
		}
		
	}
	
//calculate the start date of a volunteers language start date
function calculateStart(nb)
	{
	var duration = $('#lang_duration_' + nb).val();
	var projectStartDate = $('#start_date_' + nb).val();
	var langArrivalDay = $('#lang_arrival_day_' + nb).val();
	var langStartDate = new Date;
	
	var weekday=new Array(7);//array of weekdays, javascript doesn't have a function to return weekday
	weekday[0]="Sunday";
	weekday[1]="Monday";
	weekday[2]="Tuesday";
	weekday[3]="Wednesday";
	weekday[4]="Thursday";
	weekday[5]="Friday";
	weekday[6]="Saturday";
	
	var monthtext=new Array(12);//array of monthtexts, javascript doesn't have a function do return monthtext!!
		monthtext[0]="January"; monthtext[1]="February"; monthtext[2]="March"; 	monthtext[3]="April"; monthtext[4]="May";
		monthtext[5]="June"; monthtext[6]="July"; monthtext[7]="August"; monthtext[8]="September"; monthtext[9]="October"; monthtext[10]="November";
		monthtext[11]="December";
		
	try{
		if ($('#lang_project_type_' + nb).val() == "Part Time")
		{
			projectStartDate = $('#start_date_' + nb).val();
			langStartDate.setYear(projectStartDate.substr(0,4));
			langStartDate.setMonth(projectStartDate.substr(5,2) - 1);
			langStartDate.setDate(projectStartDate.substr(8,2));
			
			while (weekday[langStartDate.getDay()] != langArrivalDay)
			{//make sure the lang start date is the correct day of the week
				langStartDate.setDate(langStartDate.getDate() + 1);
			}
		}
		else {		
		
			langStartDate.setYear(projectStartDate.substr(0,4));
			langStartDate.setMonth(projectStartDate.substr(5,2) - 1);
			langStartDate.setDate(projectStartDate.substr(8,2));
		
			var durationDays = new Array;
			var durationWeeks = duration.split('_');
			durationWeeks = durationWeeks[1].substring(0,durationWeeks[1].indexOf(" "));
			
			langStartDate.setDate(langStartDate.getDate() - durationWeeks * 7);
				
			//move forward one, so if the language course finishes on the same day as the program starts we don't leave a gap
			langStartDate.setDate(langStartDate.getDate() + 1);
		
			while (weekday[langStartDate.getDay()] != langArrivalDay)
			{//make sure the lang start date is the correct day of the week
				langStartDate.setDate(langStartDate.getDate() - 1);
			}
		}	
		var startMonth = langStartDate.getMonth()+ 1;
		if (startMonth < 10)startMonth = "0" + startMonth;
	
		var startDay;
		if (langStartDate.getDate() < 10)
			startDay = "0" + langStartDate.getDate(); else startDay = langStartDate.getDate();
		//text date to display
		var textFormat = weekday[langStartDate.getDay()].substring(0,3);
		textFormat = textFormat + " " + startDay;
		textFormat = textFormat + " "  + monthtext[langStartDate.getMonth()] + " " + langStartDate.getFullYear();

		var sqlFormat = langStartDate.getFullYear() + "-" + startMonth + "-" + startDay; 
		
		dates = new Array();
		
		dates[0] = textFormat;
		dates[1] = sqlFormat;
		
		
		return dates;
			
		}
	catch (e)
	{//there was no response or the attribute didn't exist - ie only
		alert(e.message);
		return false;
	}
}	
 

function ajaxFailed(XMLHttpRequest, textStatus, errorThrown)
{
	alert("Request Failed " + textStatus);
}

function showProjectArea(areaToShow)
{
	projectDiv = window.document.getElementById(areaToShow);
	if(projectDiv.style.display == "none")showArea(areaToShow);	else hideArea(areaToShow);
}

function loadDates(nb,dateSelectBox,durationSelectBox,project,country, priceBox) {
	//sends a request for an xml of possible arrival dates and durations for the specified project
	var i = dateSelectBox.attr("id").substring(dateSelectBox.attr("id").indexOf("nb") + 2);
	
	if (i == 1)
		currentUpdateType = "single"; 
	else currentUpdateType = "combination";
	
	$.ajax({
		type: "GET",
		url: "/scripts/ajax/load-dates.php?project=" +project +  "&country=" + country + "&type=" + currentUpdateType,
		dataType: "xml",
		success: function(request,success){updateDates(request,dateSelectBox,durationSelectBox,project,dateSelectBox.val(),durationSelectBox.val(),priceBox,currentUpdateType);},
		error: function(XMLHttpRequest, textStatus, errorThrown){ajaxFailed(XMLHttpRequest, textStatus, errorThrown);}
	});
	
	return false;
}

function updateDates(request,dateSelectBox,durationSelectBox,project,currentDateValue,currentDurationValue,priceBox,currentUpdateType) {
	var dateOptions = ""; 
	var elements = request.getElementsByTagName("arrival_date");
	var currentExists = false; 
	var nb = dateSelectBox.attr("id").substring(dateSelectBox.attr("id").indexOf("nb"));

	for (var x=0; x<elements.length; x++) {
       	var actualValue = elements[x].getElementsByTagName("actual_value");
        var textValue = elements[x].getElementsByTagName("text_value");
       	for (var y=0; y<actualValue.length; y++) {
       		 try{//use try catch as we are relying on actualVale and textValue being pairs 	
       			actual = actualValue[y].childNodes[0].nodeValue;
        		text = textValue[y].childNodes[0].nodeValue;
				
				if (actual == currentDateValue)currentExists = true; 
				dateOptions = dateOptions += '<option value="' + actual + '">' + text + '</option>';
       		 }
        	catch(e){
        	   	}			
        	}   	
         }
	dateSelectBox.html(dateOptions);
	
	/* if the current selected value is in the new box set it*/
	if (currentExists)dateSelectBox.val(currentDateValue); 	 
	
	durationSelectBox.html();
	var durationOptions = ""; 
	currentExists = false; 
	  var durationElements = request.getElementsByTagName("duration");
	  var single; var combination; var actual; var text; var actualValue; var textValue;  
	
	  for (var x=0; x<durationElements.length; x++) {
       	actualValue = durationElements[x].getElementsByTagName("actual_value");
        textValue = durationElements[x].getElementsByTagName("text_value");
		
		for (var y=0; y<actualValue.length; y++) {
       		 try{//use try catch as we are relying on actualVale and textValue being pairs 	
       		 	actual = actualValue[y].childNodes[0].nodeValue;
        		text = textValue[y].childNodes[0].nodeValue;
       			durationOptions = durationOptions += '<option value="' + actual + '">' + text + '</option>';
             	if (actual == currentDurationValue)currentExists = true; 
				}
        	catch(e){}			
        }   	
       }	
	
	//call the onchange event on the duration box, this will update prices 
    durationSelectBox.html(durationOptions);
	
	/* if the current selected value is in the new box set it*/
	if (currentExists)dateSelectBox.val(currentDateValue); 	 
	
	$("#duration_" + nb).change();

	return false;	
}



	//update a project image		
function getProjectImage(project,image)
{
	$.ajax({
		type: "GET",
		url: "/scripts/ajax/update_project_image.php?name=" + project,
		dataType: "xml",
		success: function(request,success){updatePhoto(request,image);},
		error: function(XMLHttpRequest, textStatus, errorThrown){ajaxFailed(XMLHttpRequest, textStatus, errorThrown);}
	});	
	
	return false;
}

//update a project image with the default for the country
function getProjectImageCountry(country,image)
{
	$.ajax({
		type: "GET",
		url: "/scripts/ajax/update_project_image_country.php?name=" + country,
		dataType: "xml",
		success: function(request,success){updatePhoto(request,image);},
		error: function(XMLHttpRequest, textStatus, errorThrown){ajaxFailed(XMLHttpRequest, textStatus, errorThrown);}
	});
	
	return false;
}

function updatePhoto(request,image)
{
	var response = request.getElementsByTagName("document");
			
	try{
		var filename = response[0].getAttribute("filename");
		image.attr("src","/" + filename);
		return true;		
	}
	catch (e)
	{//there was no response or the attribute didn't exist - ie only
		image.attr("src","/costa-rica/images/thumbnails/tn-volunteer-travel-abroad.jpg");
		return false;
	}
}

function getWeekDay(day)
{//returns a weekday given a number
	switch (day)
	{
		case 0:	return 'Sun'; break;
		case 1: return 'Mon'; break;
		case 2: return 'Tue'; break;
		case 3:	return 'Wed'; break;
		case 4: return 'Thu'; break;
		case 5: return 'Fri'; break;
		case 6: return 'Sat'; }
}

function getMonthName(numericMonth)
{
	switch(numericMonth)//javascript months are 0 to 11 not 1 to 12!!
	{
		case 0:	return 'January';break;
		case 1: return 'February';break;
		case 2: return 'March';break;
		case 3:	return 'April';	break;
		case 4: return 'May'; break;
		case 5: return 'June'; break;
		case 6: return 'July';break;
		case 7: return 'August'; break;
		case 8: return 'September'; break;
		case 9: return 'October'; break;
		case 10: return 'November'; break;
		case 11: return 'December'; break;
	}
}

function openViewPricing(country,project)
{
	url = "view_prices_by_project.php?country=" + country + "&project=" + project;
		top.window.location.href = url;
}

function mysqlDateTime(year,month,day,hours,mins)
{//given a day, month and year value returns an mysql formatted date YYYY-MM-DD HH:MM:SS with time also formatted
	var formatted_date = year + "-" + month + "-" + day + " " + hours + ":" + mins + ":00";
	return formatted_date;
}	

//make sure a number is either 32 or 32.50 not 32.5
function roundToCurrency(value)
{
	value = value + "";
	if (value.indexOf(".") != -1 && (value.length - value.indexOf(".") == 2))
			value = value + "0";//make sure the number is either 32 or 32.50 not 32.5
	
	return value;	
}

function showErrorMessage(message)
{
	alert(message);
	//alert("An unexpected error occured");
	return false;
}

