//
//Blackbaud (c) 2010
//Localization startup code
//created by Dean Huntley
//Ver 0.9
//

//
//this file should be placed at the end of the template
//translation table for js validation scripts
//submit is in the list to translate the submit buttons on IE only
//problem arises on the estore cc page since there is a script that contains SubmitClick - so there is a replace to put that oen back
//
var locals = {
	"Please enter a minimum donation amount of"				: "Veuillez entrer un don minimum de",
	"Please enter keywords or price to search."				: "Veuillez entrer des mots clés ou un prix \u00E0 rechercher",
	"Please stand by..." 									: "S\\'il vous pla\u00EEt se par ...",
	"Please enter a correct format zip/postal code" 		: "S\\'il vous pla\u00EEt entrer un zip format correct / code postal",
	"Your credit card is expired - please reenter" 			: "Votre carte de cr\u00E9dit est expir\u00E9 - s\\'il vous pla\u00EEt entrer \u00E0 nouveau",
	"Your CVV number is invalid - please reenter" 			: "Votre num\u00E9ro CVV est invalide - s\\'il vous plaît entrer \u00E0 nouveau ",
	"Your credit card number is invalid - please reenter" 	: "Votre num\u00E9ro de carte de cr\u00E9dit n'est pas valide - s\'il vous pla\u00EEt entrer \u00E0 nouveau",
	"Please enter the following fields to continue:" 		: "S\\'il vous pla\u00EEt entrer dans le champs ci-dessous pour continuer: ",
	"Please enter the special event you are commemorating." : "S.V.P. Veuillez indiquer l\\'\u00E9v\u00E9nement sp\u00E9cial que vous voulez comm\u00E9morer",
	"Please enter a first name for your tribute." 			: "S.V.P. Veuillez \u00E9crire un pr\u00E9nom pour votre hommage.",
	"Please enter a last name for your tribute." 			: "S.V.P., Veuillez \u00E9crire un nom pour votre hommage.",
	"Please fill out the required fields" 					: "S.V.P. veuillez remplir les champs requis",
	"The donation amount can not contain any punctuation." 	: "Le montant du don ne doit contenir aucune ponctuation.",
	"Please re-enter your donation amount." 				: "Veuillez entrer de nouveau le montant de votre don.",
	"A $0 donation cannot be entered." 						: "Entrer un don de plus de 0$.",
	"You have entered an invalid character in this field." 	: "Vous avez entr\u00E9 un caractère inadmissible dans ce champ.",
	"Please use the MM/DD/YYYY format without spaces." 		: "S.V.P. utiliserle format suivant MM/JJ/AAAA sans espace",
	"You have entered an invalid email address." 			: "Vous avez entr\u00E9 une adresse courriel invalide",
	"Please enter the year in YYYY format.  ex 1990" 		: "S.V.P. veuillez entrer l\\'ann\u00E9e dans le format suivant AAAA. Ex 1990",
	"Please enter a year later than 1752." 					: "Nous n\\'acceptons  pas de date avant 1753.  S.V.P. choisir une ann\u00E9e ult\u00E9rieure.",
	"field requires at least"								: "Le champ exige au moins",
	"characters or more." 									: "caractères ou plus.",
	"The Team you have chosen is in use. /\nPlease select another Team name."							: "@The Team you have chosen is in use. /\nPlease select another Team name.",
	"The Team name was blank. Please enter a Team name."												: "@The Team name was blank. Please enter a Team name.",
	"The Team you have chosen is in use. Please select another Team name."								: "@The Team you have chosen is in use. Please select another Team name.",
	"Please enter a valid fundraising goal."															: "@Please enter a valid fundraising goal.",
	"Please enter a valid recruiting goal."																: "@Please enter a valid recruiting goal.",
	"Please select a Team to join from the list."														: "@Please select a Team to join from the list.",
	"This entry accepts only letters, periods, commas, hyphens and spaces." 							: "Cette entr\u00E9e accepte seulement des lettres, des p\u00E9riodes, des virgules, des traits d\\'union et des espaces.",
	"Please enter a donation amount greater than or equal to 5." 										: "S.V.P.,Veuillez entrer un montant de 5$ ou plus.",
	"This entry must be a number.  Please remove all letters, special characters, and spaces." 			: "Cette entr\u00E9e doit être un nombre. Veuillez enlever tous les lettres, caractères sp\u00E9ciaux, et espaces.",
	"You have entered an invalid date or date format.  Please use the MM/DD/YYYY format without spaces.": "Vous avez entr\u00E9 un format de date invalide.  S\\'il vous pla\u00EEt utiliser le format suivant MM/JJ/AAAA.",
	"We do not support dates before 1753.  Please choose a later year and try again." 					: "Nous n\'acceptons pas de date avant 1753.  S.V.P. choisir une ann\u00E9e ult\u00E9rieure. ",
	"You have entered an invalid 'Area Code',Please try again." 										: "Vous avez entr\u00E9 un code r\u00E9gional invalide, s\\'il vous pla\u00EEt entrer \u00E0 nouveau.",
	"You have entered an invalid 'Phone Number', Please try again." 									: "Vous avez entr\u00E9 un num\u00E9ro de t\u00E9l\u00E9phone invalide.  S\\'il vous pla\u00EEt, veuillez utiliser le format suivant xxx-xxx-xxxx.",
	"You have entered an invalid phone \\#.  Please re-enter your \\# in the form xxx-xxx-xxxx." 		: "Vous avez entr\u00E9 un num\u00E9ro de t\u00E9l\u00E9phone invalide.  S\\'il vous pla\u00EEt, veuillez utiliser le format suivant xxx-xxx-xxxx.",
	"Please enter a valid credit card.  We accept Visa, Mastercard, Discover or American Express only." : "S.V.P.,Veuillez entrer un num\u00E9ro de carte de cr\u00E9dit valide.  Nous acceptons Visa, Master Card et American Express seulement.",
	"For credit card donations a minimum donation of $5 is required" 									: "Pour les cartes de cr\u00E9dit, un don minimum de 5$ est requis",
	"Total for Range"																					: "Total pour cette cat\u00E9gorie",
	"No Donations Available"																			: "Aucun don disponible",
	"Please enter a first name"																			: "Veuillez \u00E9crire un pr\u00E9nom",
	"Add to Cart"																						: "Ajouter au panier",
	"Order More Items"																					: "Commander d'autres articles.",
	"Update Total"																						: "Mettre \u00E0 jour le total",
	"Proceed to Checkout"																				: "Quitter",
	"Back"																								: "Retour",
	"Back to"																							: "Retour au",
	"Back to National Events Calendar"																	: "Retour au calendrier des activit\u00E9s nationales",
	"Cancel"																							: "Annuler",
	"Done"																								: "Termin\u00E9",
	"Submit"																							: "Soumettre",
	"SoumettreClick"																					: "SubmitClick",
	"Continue Shopping"																					: "Poursuivre Panier",
	"Go"																								: "Aller",
	"Search"																							: "Rechercher",
	"Show All"																							: "Tout afficher",
	"Restart"																							: "Recommencer",
	"Send"																								: "Envoyer",
	"Step 2 of 4"																						: "\u00C9tape 2 sur 4",
	"Step 3 of 4"																						: "\u00C9tape 3 sur 4",
	"Step 4 of 4"																						: "\u00C9tape 4 sur 4",
	"Back to Calendrier des activités nationales"														: "Retour au Calendrier des activités nationales",
	"Please enter quantity"																				: "*Please enter quantity",
	"Please enter a valid quantity"																		: "*Please enter a valid quantity",
	"formPointer.elements\\['addAmount'\\]" 				: "$('input[name=addAmount]')[0]",
	"fieldname.elements\\['addAmount'\\]" 					: "$('input[name=addAmount]')[0]"
}


//write to page so script will translate then hide
//for (var key in locals) {
//	$('form').append(key+"<br />");
//}
var labels = [];	//all label fields stored here
var onclick = [];	//where all onclicks are stored
var hrefs = [];
var svals = [];		//all default state dropdown selections
var cvals = [];		//all default country dropdown selections
	
$(document).ready(function(){
	//$('#progressbar').progressBar();
	
	//perform translations
	//localize();
	//----
	//translate state dropdowns - seperate from standard translation
	//----
	//getStates();
	//----
	//translate country dropdowns - seperate from standard translation
	//----
	//getCountries();
});

function localize(tracex) {
	//clean up html for some Sphere pages since IE doesn't do it
	if (location.href.indexOf("category.asp") > 0) {
	//	$('#local').html($.htmlClean($('#local').html()));
		//page will need to be manually localized due to the bad html
	}	
	if ($.browser.msie && 
	   (location.href.indexOf("Product.asp") > 0 ||
		 location.href.indexOf("basket.asp") > 0 ||
		 location.href.indexOf("createCard.asp") > 0)) {
		//$('#local').html($.htmlClean($('#local').html()));
	}	
	
	//add hidden field to show page has been localized
	$('#local').before("<input type='hidden' value='localize' id='localize' name='localize' />");
	
	//another strange oddity because of the : on the note
	if ($('font.CT:contains(NOTE)').length > 0) {
		$('font.CT:contains(NOTE)').html($('font.CT:contains(NOTE)').html().replace(":","_cln_"));
	}
	
	//save off dropdown defaults and
	//clear out all state and country fields since jquery still traverses them even if not specified
	$('select[name=state], select[name=BillState], select[name=ShiptoState], select[name=billing_state]').each(function(){
		svals.push($(this).val());
		$(this).removeOption(/./);
	});
	$('select[name=country], select[name=BillCountry], select[name=ShiptoCountry], select[name=billing_country]').each(function(){
		cvals.push($(this).val());
		$(this).removeOption(/./);
	});
	
	//reset onclick events due to escape invalidating the click here link
	$('#local [onclick]').each(function(x){
		onclick[x] = this.getAttribute("onclick");
	});
	$('#local [href]').each(function(x){
		hrefs[x] = this.getAttribute("href");
	});
	//convert any input values with NCR to character
	$('input[type=button]').each(function(){
		$(this).val(convertDecNCR2Char($(this).val()));
	});

	//get original value for all labels/titles
	var i = 0;
	$('.Alert').each(function(){
	   var oldlabel = $(this).closest('td').find('font:first');
	   if ($(oldlabel).find('label').length > 0) {
		  oldlabel = $(oldlabel).find('label').html();
	   } else {
		  oldlabel = $(oldlabel).html();
	   }
	   labels[i] = oldlabel;
	   labels[i] = labels[i].replace(":","");
	   i++;
	});
	
	//this is for FAF but shouldn't affect a regular page
	$('p font[color="#ff0000"]').closest('p').each(function(){
		var text = $(this).html().split(":");
	   labels[i] = text[0];
	   labels[i] = labels[i].replace(":","");
	   i++;
	});
	
	$('td font[color="#ff0000"]').each(function(){
	   var oldlabel = $(this).closest('td');
	   if ($(oldlabel).find('label').length > 0) {
		  oldlabel = $(oldlabel).find('label').html();
	   } else {
			if ($(oldlabel).find('font').length > 0) {
				oldlabel = $(oldlabel).find('font:first').html();
			} else {
				oldlabel = $(oldlabel).html();
			}
	   }
	   labels[i] = oldlabel;
	   labels[i] = labels[i].replace(":","");
	   i++;
	});
	
	if (tracex == undefined) tracestat = false;
	else tracestat=tracex;

	$('body').translate('en', 'fr', {not: '.notrans, head, #quicklinks, #header, #mainNav, #sidebarContent, #utility, #primaryNav, #footer, #a2apage_dropdown, select[name=Field5121940], select[name^=Field5121941], select[name=Field5121942], select[name=Field5121950], select[name=Field5121951], select[name=Field5121952], select[name=day], select[name=year], select[name=country], select[name=BillCountry], select[name=ShiptoCountry], select[name=state], select[name=BillState], select[name=ShiptoState], select[name=billing_state], select[name=billing_country]', google:false, table: 'ccfc', trace : tracestat, 
		complete: function(){
			//----
			//translate warning strings in validation scripts
			//----
			//if not an faf
			if (location.href.indexOf("/faf/") == -1) {
				$('script').each(function(){
					//standard cms forms have this check subroutine
					var checkform = new RegExp("CheckForm\\d{1,5}");
					var m = checkform.exec($(this).html());
					if (m != null) {
						if (m.index > 0) {
							doTranslate(this);
						}
					} else {
						//standard cms forms have this check subroutine
						var checkform = new RegExp("CheckForm");
						var m = checkform.exec($(this).html());
						if (m != null) {
							if (m.index > 0) {
								doTranslate(this);
							}
						}
						//estore search
						var checkform = new RegExp("DoSearch");
						var m = checkform.exec($(this).html());
						if (m != null) {
							if (m.index > 0) {
								doTranslate(this);
							}
						}	
						//ecard search
						var checkform = new RegExp("noCard2");
						var m = checkform.exec($(this).html());
						if (m != null) {
							if (m.index > 0) {
								doTranslate(this);
							}
						}	
				   }
				});
				if (location.href.toLowerCase().indexOf("category.asp") > 0 ||
					location.href.toLowerCase().indexOf("basket.asp") > 0 ||
					location.href.toLowerCase().indexOf("product.asp") > 0 ||
					location.href.toLowerCase().indexOf("catalog.asp") > 0 ||					
					location.href.toLowerCase().indexOf("contactus.asp") > 0 ||
					location.href.toLowerCase().indexOf("searchit.asp") > 0 ||
					location.href.toLowerCase().indexOf("searchpage.asp") > 0 ||
					location.href.toLowerCase().indexOf("content.asp") > 0 ||
					location.href.toLowerCase().indexOf("createcard.asp") > 0) {
					//go through locals array above for input translations on bad html pages
					$('input:button, input:submit').each(function() {
						if (locals[$(this).val()] != undefined) $(this).val(locals[$(this).val()]);
					});
				}
			} else {
				//correct bad html in FAF
				//FORM tag is written between the TABLE and TR tags so when the dom gets rewritten
				//the form tags get moved.
				//This code will put the tags back in the correct position
				if ((location.href.indexOf("donorPledge.asp") > 0) && (!$.browser.msie)) {
					var x = $('form[name=registrationForm]');
					$('form[name=registrationForm]').remove();
					$('.FAFBodyTable table:eq(6)').wrap(x);
				}
				
				//in FAF translations are handled different
				$('script').each(function(){
					if (($(this).html().indexOf("javaEnabled") == -1) && ($(this).html().indexOf("PopupCVV") == -1)) {
						doTranslate(this);
					}
				});
				formPointer = document.registrationForm;
			}
			//setTimeout(function(){$('#fade').fadeOut();$('#light').slideUp();},600);
			//remove overlay
			//$('#fade').hide('fast');
			//$('#light').fadeOut();
			//put original onclicks and hrefs back on href
			$('#local [onclick]').each(function(x){
				if (onclick[x] != undefined) this.setAttribute("onclick",onclick[x]);
			});	
			$('#local [href]').each(function(x){
				if (hrefs[x] != undefined) this.setAttribute("href",hrefs[x]);
			});	

			$('#local').show();
			$('.FAFBodyTable, .FAFLeftNav, .newMenuHeaderText, .newMenuTextColor').show();
			addClickEvent();
		}
	});
	//translate state dropdowns - seperate from standard translation
	//----
	getStates();
	//----
	//translate country dropdowns - seperate from standard translation
	//----
	getCountries();

}

//this translates the warnings in the js validation
//by using the inputs that have class=Alert and replacing the warning text
function doTranslate(script) {
	var newjs = $(script).html();
	var i = 0;
	//go through all alert tags and get new label names then replace in the js warnings
	$('.Alert').each(function(){
		var newlabel = $(this).closest('td').find('font:first');
		if ($(newlabel).find('label').length > 0) {
		   newlabel = $(newlabel).find('label').html();
		} else {
		   newlabel = $(newlabel).html();
		}
		newlabel = newlabel.replace(":","");
		newjs = newjs.replace(labels[i]+'"',newlabel+'"');
		i++;
	});
	//if faf then get p font tags
	$('p font[color="#ff0000"]').closest('p').each(function(){
		var text = $(this).html().split(":");
		var newlabel = text[0];
		newlabel = newlabel.replace(":","");
		newjs = newjs.replace(labels[i]+'"',newlabel+'"');
		//for faf modify profile page
		newjs = newjs.replace("- "+labels[i],"- "+newlabel);
		i++;
	});
	//if faf get label tags
	$('td font[color="#ff0000"]').each(function(){
		var newlabel = $(this).closest('td');
		if ($(newlabel).find('label').length > 0) {
			newlabel = $(newlabel).find('label').html();
		} else {
			if ($(newlabel).find('font').length > 0) {
				newlabel = $(newlabel).find('font:first').html();
			} else {
				newlabel = $(newlabel).html();
			}
		}
		newlabel = newlabel.replace(":","");
		newjs = newjs.replace(labels[i]+'"',newlabel+'"');
		i++;
	});
	//go through locals array above for inline js translations
	for (var key in locals) {
		var nr = new RegExp(key,"g");
		newjs = newjs.replace(nr, locals[key]);
	}
	//remove comment tags and write new script files
	newjs = newjs.replace('<!--','');
	newjs = newjs.replace('//-->','');
	$('table:last').after("<sc"+"ript>"+newjs+"</sc"+"ript>");
}

//get states from db and replace separately from translate process
//these are large dropdowns and slow down the translation process
function getStates() {
	var opts = {};
	var url = "https://www.kinteratools.com/local/localize-states.php?callback=?";
	$.ajax({
		type : "GET",
		data : "data=",
		dataType : "json",
		url : url,
		contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
		success : function(result){
			var opts = {};
			for (var key in result.data) {;
				opts[result.data[key].prefix] = {};
				opts[result.data[key].prefix] = result.data[key].to;
			}
			$('select[name=state], select[name=BillState], select[name=ShiptoState], select[name=billing_state]').each(function(i){
				$(this).removeOption(0)
 					   .addOption(opts,false)
					   .selectOptions(svals[i],true);
			});
		}
	});

}

//get countries from db and replace separately from translate process
//these are large dropdowns and slow down the translation process
function getCountries() {
	var opts = {};
	var url = "https://www.kinteratools.com/local/localize-countries.php?callback=?";
	$.ajax({
		type : "GET",
		data : "data=",
		dataType : "json",
		url : url,
		contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
		success : function(result){
			var opts = {};
			for (var key in result.data) {
				opts[result.data[key].prefix] = {};
				opts[result.data[key].prefix] = result.data[key].to;
			}
			$('select[name=country], select[name=BillCountry], select[name=ShiptoCountry], select[name=billing_country]').each(function(i){
				$(this).removeOption(0)
					   .addOption(opts,false)
					   .selectOptions(cvals[i],true);
			});
		}
	});

}

//override current popup cvv window and point to translated page
var c;
function PopupCVV() {
	c = window.open('/atf/cf/{51785C68-280A-46C5-9D15-9C3886290AC4}/41_CVV.htm','file','scrollbars=yes,resizable=yes,width=640,height=480,left=100,top=100');
	c.focus();
}
function CloseCVV() {
	if (c) {	
		if (!c.closed) c.close();
		c = null;
	}
}
window.onfocus = CloseCVV;

//convert numerical character reference to characters
function dec2char ( n ) {
	// converts a single string representing a decimal number to a character
	// note that no checking is performed to ensure that this is just a hex number, eg. no spaces etc
	// dec: string, the dec codepoint to be converted
	var result = '';
    if (n <= 0xFFFF) { result += String.fromCharCode(n); } 
	else if (n <= 0x10FFFF) {
		n -= 0x10000
		result += String.fromCharCode(0xD800 | (n >> 10)) + String.fromCharCode(0xDC00 | (n & 0x3FF));
    	} 
	else { result += 'dec2char error: Code point out of range: '+dec2hex(n); }
	return result;
}

function convertDecNCR2Char ( str ) { 
	// converts a string containing &#...; escapes to a string of characters
	// str: string, the input
	
	// convert up to 6 digit escapes to characters
	str = str.replace(/&#([0-9]{1,7});/g, 
					function(matchstr, parens) {
						return dec2char(parens);
						}
						);
	return str;
}

