

// Banner adds
var si_site_name = 'sri.historiatv';
var si_ord = Math.round(Math.random()*100000000000);
function SIWriteAdvert(si_zone, si_tile_id, si_size) {
  try {
    var dcopt_val = '';
    if (si_tile_id == 1) {
      dcopt_val='dcopt=ist;'
    }
    document.write("<sc"+"ript type=\"text/jav"+"ascript\" src=\"http://ad.double"+"click.net/adj/"+si_site_name+"/"+si_zone+";"+dcopt_val+"tile="+si_tile_id+";sz="+si_size+";ord="+si_ord+"?\"></scr"+"ipt>");
  } catch (e) { 
    alert('error');
    return; 
  }
}


// Browser detect
var browser;
var isIE4 = (document.all) ? true:false; 
if (isIE4) { 
  if (navigator.userAgent.indexOf('MSIE 6') > 0) { 
    browser = 'IE6';
	} else if (navigator.userAgent.indexOf('MSIE 5') > 0) { 
    browser = 'IE5';
  } else {
    browser = 'IE4';
  } 
} else {
	if (navigator.userAgent.indexOf('Firefox') > 0) { 
    browser = 'FFX';
	} else if (navigator.userAgent.indexOf('Netscape/7') > 0) { 
    browser = 'NN7';
  } else if (navigator.userAgent.indexOf('Netscape6/6') > 0) { 
    browser = 'NN6';
  } else {
    browser = 'NN4';
  } 
} 


// OS detect
var OS;
if (navigator.appVersion.indexOf("Mac") != -1) {
  OS = 'mac'; 
} else {
  OS = 'win'; 
}


// Fireworks rollovers
function MM_findObj(n, d) { //v4.01
	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);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}
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];}}
}


// Layers
function MM_showHideLayers() { // v3.0
//	alert("fonction MM_showHideLayers");
	var i, p, v, obj, args = MM_showHideLayers.arguments;
	for (i = 0; i<(args.length - 2); i += 3) if ((obj=MM_findObj(args[i]))!=null) { 
		v = args[i+2];
		if (obj.style) { 
			obj = obj.style; 
			v = (v == 'show') ? 'visible' : (v='hide') ? 'hidden' : v; 
		}
//	alert (v);
	obj.visibility = v; 
	}
}


// Pop-ups
var newWindowVrak = '';
function openNewWindow(popURL, dimX, dimY) {
	var newleft = (screen.width - dimX) / 2;
	var newtop = (screen.height - dimY) / 2; 
	self.name = 'MainWindow';
	if (newWindowVrak.location && !newWindowVrak.closed) {
		newWindowVrak.location.href = popURL;
	} else {
		features = 'top=' + newtop + ',left=' + newleft + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + dimX + ',height=' + dimY;
		newWindowVrak = window.open(popURL, '', features);
		if (!newWindowVrak.opener) newWindowVrak.opener = self;
	}
	if (window.focus) newWindowVrak.focus();
}


// Pop-ups centres
function popup(page, nom, w, h, t, l, d, s, m, sc, r) { 
	var newleft = (screen.width - w) / 2;
	var newtop = (screen.height - h) / 2; 
	var prop1 = "toolbar=" + t + ",location=" + l + ",directories=" + d + ",status=" + s + ",menubar=" + m + ",scrollbars=" + sc + ",resizable=" + r +",";
	var prop2 = "width=" + w + ",height=" + h + ",top=" + newtop + ",left=" + newleft;
	window.open(page, nom, prop1 + prop2);
}


// Print window
function printWindow(){
	bV = parseInt(navigator.appVersion)
	if (bV >= 4) window.print()
}


// Validation email
function checkIfMail(input) {
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	return regex.test(input);
}


// Form validation
function checkMail(input) {
	var isMailAddressOK = false;
	var filterRegExp =/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
	if (filterRegExp.test(input)) isMailAddressOK = true;
	return isMailAddressOK;
}

function getRadioValue(radioElement) {
	var checkedValue = -1;
	for (i=0; i<radioElement.length; i++) {
		if (radioElement[i].checked) {
			checkedValue = radioElement[i].value;
		}
	}
	return checkedValue;
}

function checkIfNumeric(input) {
	var isNumeric = false;
	var NUMERIC = "0123456789";
	input = input.toUpperCase();
	for(var i=0; i<input.length; i++) {
		var CHAR = input.charAt(i);
		if((NUMERIC.indexOf(CHAR) >= 0) && !isNumeric) {
			isNumeric = true;
		}
	}
	return isNumeric;
}


// Recrutements
function isValidEmail(emailAddress) {
	var isValid = false;
	var filterRegExp =/.(.*)\@(.*)\...(.*)/;
	if (filterRegExp.test(emailAddress)) {
		isValid = true;
	}
	return isValid;
}
function isValidFile(file) {
	var isValid = true;
	var indexJpeg;
	var indexJpg;
	var indexGif;
	indexJpeg = file.toLowerCase().lastIndexOf('.jpeg');
	indexJpg = file.toLowerCase().lastIndexOf('.jpg');
	indexGif = file.toLowerCase().lastIndexOf('.gif');
	if ((indexJpeg == -1) && (indexJpg == -1) && (indexGif == -1)) {
		isValid = false;
	}
	return isValid;
}
function checkRecr(recrForm) {
	var errorMsg = "Erreur :\n";
	for (var i=0; i<recrForm.length; i++) {
		var element = recrForm.elements[i];
		if ((element.type != "hidden") && (element.type != "submit")) {
			// Text
			if (element.type == "text") {
				if ((element.name.indexOf("optionnel") == -1) && (element.value == "")) {
					errorMsg += "Veuillez remplir le champ \"" + element.name + "\".\n";
				} else if (element.name == "Courriel") {
					if (!isValidEmail(element.value)) {
						errorMsg += "Votre adresse de courriel ne semble pas valide.\n";
					}
				}
			}
			// Textarea
			if (element.type == "textarea") {
				if (element.value == "") {
					errorMsg += "Veuillez remplir le champ \"" + element.name + "\".\n";
				}						
			}
			// Radio
			if (element.type == "radio") {
				if (getRadioValue(recrForm.elements[element.name]) == -1) {
					errorMsg += "Veuillez faire votre choix pour \"" + element.name + "\".\n";
				}	
			}
			// Checkbox (release - voir www.canalvie.com/emission/monenfant_monheros/recrutement2.jsp)
			if (element.type == "checkbox" && element.name == "Release" && element.checked == false) {
				errorMsg += "\nVeuillez cocher la case \"" + element.value + "\".\nEn soumettant votre témoignage, vous devez accepter que \nLes Chaînes Télé Astral puissent publier votre texte, \nune partie de celui-ci ou encore toute photo \nque vous aurez jointe à votre témoignage.";
			}
			// File
			if (element.type == "file") {
				if (element.value == "") {
					errorMsg += "Veuillez sélectionner un fichier pour le champ \"" + element.name + "\".\n";
				} else {
					if (!isValidFile(element.value)) {
						errorMsg += "Les seuls fichiers acceptés sont \".gif\", \".jpg\" ou \".jpeg\".\n";
					}
				}
			}
		}
	}
	if (errorMsg != "Erreur :\n") {
		alert(errorMsg);
		return false;
	} else {
		if (recrForm.elements["Go"]) {
			recrForm.elements["Go"].disabled = true;
		}
		return true;
	}
}


// Cookies
function getCookie(cookieName) {
	var results = document.cookie.match (cookieName + '=(.*?)(;|$)');
	if (results) {
		return (unescape(results[1]));
	} else {
		return null;
	}
}
function setCookie(cookieName, cookieValue, cookieDays) {
	if (cookieDays) {
		var date = new Date();
		date.setTime(date.getTime() + (cookieDays*24*60*60*1000));
		var cookieExpires = "; expires=" + date.toGMTString();
	} else {
		var cookieExpires = "";
	}
	document.cookie = cookieName + "=" + cookieValue + cookieExpires + "; path=/";
}


/**
 * SWFObject v1.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, xiRedirectUrl, redirectUrl, detectKey){
	if (!document.createElement || !document.getElementById) { return; }
	this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
	this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
	this.params = new Object();
	this.variables = new Object();
	this.attributes = new Array();
	if(swf) { this.setAttribute('swf', swf); }
	if(id) { this.setAttribute('id', id); }
	if(w) { this.setAttribute('width', w); }
	if(h) { this.setAttribute('height', h); }
	if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
	this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute('version'), useExpressInstall);
	if(c) { this.addParam('bgcolor', c); }
	var q = quality ? quality : 'high';
	this.addParam('quality', q);
	this.setAttribute('useExpressInstall', useExpressInstall);
	this.setAttribute('doExpressInstall', false);
	var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
	this.setAttribute('xiRedirectUrl', xir);
	this.setAttribute('redirectUrl', '');
	if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
	setAttribute: function(name, value){
		this.attributes[name] = value;
	},
	getAttribute: function(name){
		return this.attributes[name];
	},
	addParam: function(name, value){
		this.params[name] = value;
	},
	getParams: function(){
		return this.params;
	},
	addVariable: function(name, value){
		this.variables[name] = value;
	},
	getVariable: function(name){
		return this.variables[name];
	},
	getVariables: function(){
		return this.variables;
	},
	getVariablePairs: function(){
		var variablePairs = new Array();
		var key;
		var variables = this.getVariables();
		for(key in variables){
			variablePairs.push(key +"="+ variables[key]);
		}
		return variablePairs;
	},
	getSWFHTML: function() {
		var swfNode = "";
		if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
			if (this.getAttribute("doExpressInstall")) this.addVariable("MMplayerType", "PlugIn");
			swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"';
			swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
			var params = this.getParams();
			 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
			var pairs = this.getVariablePairs().join("&");
			 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
			swfNode += '/>';
		} else { // PC IE
			if (this.getAttribute("doExpressInstall")) this.addVariable("MMplayerType", "ActiveX");
			swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
			swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
			var params = this.getParams();
			for(var key in params) {
			 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
			}
			var pairs = this.getVariablePairs().join("&");
			if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
			swfNode += "</object>";
		}
		return swfNode;
	},
	write: function(elementId){
		if(this.getAttribute('useExpressInstall')) {
			// check to see if we need to do an express install
			var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
			if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
				this.setAttribute('doExpressInstall', true);
				this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
				document.title = document.title.slice(0, 47) + " - Flash Player Installation";
				this.addVariable("MMdoctitle", document.title);
			}
		}
		if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
			var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
			n.innerHTML = this.getSWFHTML();
			return true;
		}else{
			if(this.getAttribute('redirectUrl') != "") {
				document.location.replace(this.getAttribute('redirectUrl'));
			}
		}
		return false;
	}
}

// Function used to include js files. Script must "end" before included script can be active.
function jsInclude(jsFile) {
	document.write('<' + 'script');
	document.write(' language="JavaScript"');
	document.write(' type="text/javascript"');
	document.write(' src="' + jsFile + '">');
	document.write('</' + 'script' + '>');
}


/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(reqVer, xiInstall){
	var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
	if(navigator.plugins && navigator.mimeTypes.length){
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description) {
			PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
		}
	}else{
		try{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			for (var i=3; axo!=null; i++) {
				axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
				PlayerVersion = new deconcept.PlayerVersion([i,0,0]);
			}
		}catch(e){}
		if (reqVer && PlayerVersion.major > reqVer.major) return PlayerVersion; // version is ok, skip minor detection
		// this only does the minor rev lookup if the user's major version 
		// is not 6 or we are checking for a specific minor or revision number
		// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
		if (!reqVer || ((reqVer.minor != 0 || reqVer.rev != 0) && PlayerVersion.major == reqVer.major) || PlayerVersion.major != 6 || xiInstall) {
			try{
				PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
			}catch(e){}
		}
	}
	return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
	this.major = parseInt(arrVersion[0]) != null ? parseInt(arrVersion[0]) : 0;
	this.minor = parseInt(arrVersion[1]) || 0;
	this.rev = parseInt(arrVersion[2]) || 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
	if(this.major < fv.major) return false;
	if(this.major > fv.major) return true;
	if(this.minor < fv.minor) return false;
	if(this.minor > fv.minor) return true;
	if(this.rev < fv.rev) return false;
	return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
	getRequestParameter: function(param){
		var q = document.location.search || document.location.hash;
		if(q){
			var startIndex = q.indexOf(param +"=");
			var endIndex = (q.indexOf("&", startIndex) > -1) ? q.indexOf("&", startIndex) : q.length;
			if (q.length > 1 && startIndex > -1) {
				return q.substring(q.indexOf("=", startIndex)+1, endIndex);
			}
		}
		return "";
	}
}


/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;


// Print window
function printWindow(){
   bV = parseInt(navigator.appVersion);
   if (bV >= 4) window.print();
}


// Correctly handle PNG transparency in Win IE 5.5 or higher.
// http://homepage.ntlworld.com/bobosola. Updated 02-March-2004


function correctPNG() {
	for(var i=0; i<document.images.length; i++) {
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:inline-block;" + img.style.cssText 
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle		
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
			img.outerHTML = strNewHTML
			i = i-1
		}
	}
}
if (isIE4) { 
	window.attachEvent("onload", correctPNG);
}




// Presse - menu déroulant pour Archives
function jumpBox(list) {location.href =list.options[list.selectedIndex].value}
function dropdown() {document.theform.jump.options[0].selected=true}


// Pour imprimer une section de page

var gAutoPrint = true; // Tells whether to automatically call the print function

function printSpecial()
{
if (document.getElementById != null)
{
var html = '<HTML>\n<HEAD>\n';

if (document.getElementsByTagName != null)
{
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}

html += '\n</HE>\n<BODY>\n';

var printReadyElem = document.getElementById("printReady");

if (printReadyElem != null)
{
html += printReadyElem.innerHTML;
}
else
{
alert("Ne trouve pas fonction printReady");
return;
}

html += '\n</BO>\n</HT>';

var printWin = window.open("","printSpecial");
printWin.document.open();
printWin.document.write(html);
printWin.document.close();
if (gAutoPrint)
printWin.print();
}
else
{
alert("Votre fureteur ne supporte pas cette fonction. Veuillez le mettre à jour.");
}
}

// Build a flash videoPlayer (Marco)
function videoPlayer(videoUrl, videoId, firstFrameUrl, autoPlay, isCanadaOnly, divId, SWFObject, proxyId, serverUrl, zoneId) {
	
	SWFObject.addParam("quality", "high");
	SWFObject.addParam("menu", false);
	SWFObject.addParam("wmode", "transparent");
	SWFObject.addParam('swliveconnect', 'true');
	SWFObject.addParam("allowScriptAccess","always");   

	if (serverUrl) {
		SWFObject.addVariable("serverUrl", serverUrl);
		SWFObject.addVariable("zoneid", "'" + zoneId + "'");
	}
	
	SWFObject.addVariable("lcId", proxyId);
	SWFObject.addVariable('videoFirstFrameUrl', firstFrameUrl);
	SWFObject.addVariable("automaticPlay", autoPlay);
	SWFObject.addVariable("isCanadaOnly", isCanadaOnly);
	SWFObject.addVariable('videoUrl', videoUrl);
	SWFObject.addVariable("videoId", videoId);
	SWFObject.addVariable("urlMovie", document.location);

	SWFObject.write(divId);
}


// Menu déroulant
function jumpBox(list) {location.href =list.options[list.selectedIndex].value}

function jumpBoxBlank(list) {
	url = list.options[list.selectedIndex].value;
	if (url != '') {
		window.open(url);
		}
	}
	
// Ajouter aux favoris
function favoris(pageName, pageUrl) {
	if ( navigator.appName != 'Microsoft Internet Explorer' ){
		window.sidebar.addPanel(pageName,pageUrl,"");
	} else {
		window.external.AddFavorite(pageUrl, pageName);
	}
}

// Submit Research in webtele
function submitFormRechercheWebtele() {
	var typeId = $("#typeId").val();
	var programId = $("#programId").val();
	var episodeId = 0;
	self.location.href = "/webtele/recherche/?type=" + typeId + "&emission=" + programId + "&episode=" + episodeId + "&tri=0";
	return false;
}


function printFlash(div, sourceSwf, swfWidth, swfHeight) {
	// Print flash 
	$(div).flash(
		{ src: sourceSwf, width: swfWidth, height: swfHeight, bgcolor: '#ffffff', quality: 'high', menu: false, wmode: 'transparent', swliveconnect: 'true', allowScriptAccess: 'always', allowFullScreen: true },
	{ version: '9.0.115' }
	);
}

// On incrémente le compteur de bannière concours
function clickThroughDraw(drawId, imageId, statZone) {
	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "GET",
		url: "/_dyn/incDrawCount.jsp",
		data: "drawId=" + drawId + "&imageId=" + imageId + "&statZone=" + statZone + "&ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml) {
			var opResult = $(xml).find("opResult").text();
			var opMessage = $(xml).find("opMessage").text();
			var linkUrl = $(xml).find("linkUrl").text();
			if (opResult == 'ok') {
				self.location.href = linkUrl;
			} else {
				alert(opMessage);
			}
		}
	});
}

// Endswith
function endsWith(str, endStr) {

	// http://preprod.canalvie.com/ decoration/ : 39
	// decoration/ : 11
	var originalStringWithEndStrInserted = str.substring(0, str.length - endStr.length) + endStr;
	
	//alert("str.substring(str.length - endStr.length) + endStr : " + str.substring(0, str.length - endStr.length) + endStr);
	//alert("originalStringWithEndStrInserted : " + originalStringWithEndStrInserted);

	if (str == originalStringWithEndStrInserted) {
		return true;
	} else {
		return false;
	}
}

// Removes white space (leading and trailing)
function trim(toTrim) {
	return toTrim.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

// Clear selects
function clearSelect(selectId, previousSelectText) {
	$("#" + selectId).removeOption(/./);
	$("#" + selectId).addOption("0", "Choisissez " + previousSelectText + " avant");
}

// Load country select
function loadCountrySelect(selectedCountryId, selectId) {

	// Max characters for option
	var maxChar = 25;

	var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
	$.ajax({
		type: "GET",
		url:"/_dyn/getCountries.jsp",
		data: "&ieRant=" + ieRant,
		dataType: "xml",
		success: function(xml){

			// Clear the list
			$("#" + selectId).removeOption(/./);

			$(xml).find("country").each(function(){

				// Get values from XML
				var countryId = $(this).attr("id");
				var countryName = $(this).text();
				var countrySelected = false;
				if (countryId == selectedCountryId) {
					countrySelected = true;
				}

				// Truncate name
				if (countryName.length > maxChar) {
					countryName = countryName.substring(0, maxChar) + "...";
				}

				// Add option to select
				$("#" + selectId).addOption(countryId, countryName, countrySelected);

			});
		}
	});

}

// Load province select
function loadProvinceSelect(countryId, selectedProvinceId, selectId) {

	// Max characters for option
	var maxChar = 25;

	if (countryId == 0) {
		clearSelect(selectId, "un pays");
	} else {

		var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
		$.ajax({
			type: "GET",
			url:"/_dyn/getProvinces.jsp",
			data: "countryId=" + countryId + "&ieRant=" + ieRant,
			dataType: "xml",
			success: function(xml){

				// Clear the list
				$("#" + selectId).removeOption(/./);

				$(xml).find("province").each(function(){

					// Get values from XML
					var provinceId = $(this).attr("id");
					var provinceName = $(this).text();
					var provinceSelected = false;
					if (provinceId == selectedProvinceId) {
						provinceSelected = true;
					}

					// Truncate name
					if (provinceName.length > maxChar) {
						provinceName = provinceName.substring(0, maxChar) + "...";
					}

					// Add option to select
					$("#" + selectId).addOption(provinceId, provinceName, provinceSelected);

				});
			}
		});

	}

}

// Load region select
function loadRegionSelect(provinceId, selectedRegionId, selectId) {

	// Max characters for option
	var maxChar = 25;

	if (provinceId == 0) {
		clearSelect(selectId, "une province");
	} else {

		var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
		$.ajax({
			type: "GET",
			url:"/_dyn/getRegions.jsp",
			data: "provinceId=" + provinceId + "&ieRant=" + ieRant,
			dataType: "xml",
			success: function(xml){

				// Clear the list
				$("#" + selectId).removeOption(/./);

				$(xml).find("region").each(function(){

					// Get values from XML
					var regionId = $(this).attr("id");
					var regionName = $(this).text();
					var regionSelected = false;
					if (regionId == selectedRegionId) {
						regionSelected = true;
					}

					// Truncate name
					if (regionName.length > maxChar) {
						regionName = regionName.substring(0, maxChar) + "...";
					}

					// Add option to select
					$("#" + selectId).addOption(regionId, regionName, regionSelected);

				});

			}
		});

	}

}

// Load municipality select
function loadMunicipalitySelect(regionId, selectedMunicipalityId, selectId) {

	// Max characters for option
	var maxChar = 25;

	if (regionId == 0) {
		clearSelect(selectId, "une région");
	} else {

		var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
		$.ajax({
			type: "GET",
			url:"/_dyn/getMunicipalities.jsp",
			data: "regionId=" + regionId + "&ieRant=" + ieRant,
			dataType: "xml",
			success: function(xml){
				// Clear the list
				$("#" + selectId).removeOption(/./);

				$(xml).find("municipality").each(function(){

					// Get values from XML
					var municipalityId = $(this).attr("id");
					var municipalityName = $(this).text();
					var municipalitySelected = false;
					if (municipalityId == selectedMunicipalityId) {
						municipalitySelected = true;
					}

					// Truncate name
					if (municipalityName.length > maxChar) {
						municipalityName = municipalityName.substring(0, maxChar) + "...";
					}

					// Add option to select
					$("#" + selectId).addOption(municipalityId, municipalityName, municipalitySelected);

				});
			}
		});

	}

}

// Load municipality select
function loadBoroughSelect(municipalityId, selectedBoroughId, selectId) {

	// Max characters for option
	var maxChar = 25;

	if (municipalityId == 0) {
		clearSelect(selectId, "une municipalité");
	} else {

		var ieRant = Math.floor(Math.random()*1000001); // Generate random so that this f***ing IE browser does not cache xml response
		$.ajax({
			type: "GET",
			url:"/_dyn/getBoroughs.jsp",
			data: "municipalityId=" + municipalityId + "&ieRant=" + ieRant,
			dataType: "xml",
			success: function(xml){
				// Clear the list
				$("#" + selectId).removeOption(/./);

				$(xml).find("borough").each(function(){

					// Get values from XML
					var boroughId = $(this).attr("id");
					var boroughName = $(this).text();
					var boroughSelected = false;
					if (boroughId == selectedBoroughId) {
						boroughSelected = true;
					}

					// Truncate name
					if (boroughName.length > maxChar) {
						boroughName = boroughName.substring(0, maxChar) + "...";
					}

					// Add option to select
					$("#" + selectId).addOption(boroughId, boroughName, boroughSelected);

				});
			}
		});

	}

}