// Author: Alex Hawryschuk
// Last Updated: 2/22/2007
var bName = navigator.appName;
var bVer = parseInt(navigator.appVersion);
var bPlatform = navigator.platform;
var NS3 = (bName == "Netscape" && bVer < 4);
var NS4 = (bName == "Netscape" && bVer >= 4);
var NS6 = (bName == "Netscape" && bVer >= 5);
var IE3 = (bName == "Microsoft Internet Explorer" && bVer < 4);
var IE4 = (bName == "Microsoft Internet Explorer" && bVer >= 4);
var MAC = (bPlatform=="MacPPC");
var WINDOWS = (bPlatform=="Win32");
var DOM = (document.getElementById) ? true : false;

// Object background colour settings - specifically for the menu's
function setStyle(i,s,v){
	try {
		if (document.getElementById) {
			document.getElementById(i).style[s] = v;
		} else if (document.all) {
			document.all[i].style[s] = v;
		}
	} catch (e) {
		alert("ERROR: " + e.description);
	}
}

function getStyle(i,s){
	try {
		if (document.getElementById) {
			return document.getElementById(i).style[s];
		} else if (document.all) {
			return document.all[i].style[s];
		}
	} catch (e) {
		alert("ERROR: " + e.description);
	}
}

// This function opens a new URL into a new window, and centers it.
var myWin;
function openwindow(theURL,winName,wwidth,wheight,wscrolls) {
	// re-set the height and width with the offsets
	wwidth+=ow;
	wheight+=oh;

	// set the window features
	var features = "width=" + wwidth + ",height=" + wheight;
	if (wscrolls==0) { features+=",scrollbars=no"; }

	// Open the new window
	myWin = window.open(theURL,winName,features);
	myWin.moveTo( (screen.availWidth-wwidth)/2 , (screen.availHeight-wheight)/2 );
	myWin.resizeTo(wwidth,wheight);
	myWin.focus();
}

// Returns the value of the key sent in the url
function getQueryField(sName) {
	var kvp = document.location.search.substring(1).split('&');
	for (var i in kvp) {
		var kv = kvp[i].split('=');
		if (kv[0]==sName) return kv[1];
	}
	return '';
}

// Cookie functions
// Retrieve the value of the cookie sName
function getCookie(name) {
	var kvp = document.cookie.split(';');
	var strSearch = name + "=";
	for(var i=0;i<kvp.length;i++) {
		var c = kvp[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(strSearch) == 0) return unescape(c.substring(strSearch.length,c.length));
	}
	return '';
}

// Write a cookie to the browser with the name value and expiration
function setCookie(name,value,expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if (expires) expires = expires * 1000 * 60 * 60 * 24;
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name + "=" + escape(value)
		+ ((expires) ? ";expires=" + expires_date.toGMTString() : "" )
		+ ((path) ? ";path=" + path : "" )
		+ ((domain) ? ";domain=" + domain : "" )
		+ ((secure) ? ";secure" : "" );
}

// Get the text (label) of a select input
function getSelectText(f,s) {
	return document.forms[f][s].options[document.forms[f][s].selectedIndex].text;
}

// Get the value of a select input
function getSelectValue(f,s) {
	return document.forms[f][s].selectedIndex>=0 ? document.forms[f][s].options[document.forms[f][s].selectedIndex].value : null;
}

// Return the index of the selected radio button
function getOptionIndex(sForm,sField) {
	var index = -1;
	for (var k=0;k<document.forms[sForm][sField].length;k++) {
		if (document.forms[sForm][sField][k].checked) index = k;
	}
	return index;
}

// Return whether the radio button has an option selected
function getOptionSelected(sForm,sField) {
	return getOptionIndex(sForm,sField)>=0;
}

// Return the value of the selected radio button
function getOptionValue(sForm,sField) {
	if (getOptionSelected(sForm,sField))
		return document.forms[sForm][sField][getOptionIndex(sForm,sField)].value;
	else if(document.forms[sForm][sField].value)
		return document.forms[sForm][sField].value;
	else
		return false;
}


// Clear all the options from a select object
function clearSelectObjectOptions(formName,selectName) {
	var does_exist = false;
	for (i=0;i<document.forms[formName].length;i++) {
		if (document.forms[formName].elements[i].name == selectName) {
			does_exist = true;
		}
	}
	if (does_exist) {
		var nitems = document.forms[formName][selectName].length;
		for (i=nitems-1;i>=0;i--) {
			document.forms[formName][selectName].options[i]=null;
		}
	}
}

function setSelectObjectSelected(formName,selectName,value) {
	var r = document.forms[formName][selectName];
	for (var i=0;i<r.length;i++) r.options[i].selected = r.options[i].value==value;
}

// (Pre-)Loads an image
function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

// Swaps another image into an existing image
function changeImages(img,src) {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[img].src = src;
		}
	}
}

// whether a value is in an array
function inArray(v,a) {
	for (var i in a) if (a[i]==v) return true;
	return false;
}

// Load an XML Doc from an url, executing f when the server sends the response back
function loadXMLDoc(url,parameters,f) {
	// Overloaded function : loadXMLDoc(url,parameters,f) or loadXMLDoc(url,f)
	if (!f) { f = parameters; parameters={}; }

	// convert parameters
	var parameters2 = [];
	for (var i in parameters) parameters2.push(FormCollect_Encode(i) + '=' + FormCollect_Encode(parameters[i]));
	parameters=parameters2.join('&');

    // branch for native XMLHttpRequest object
	var req = false;
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
		req.onreadystatechange = function() {
			if (req.readyState == 4 && f) f(req.status==200,req);
		}
		if (parameters.length>0) {
			req.open('POST', url, true);
			req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			req.setRequestHeader('Connection', 'close');
			req.send(parameters);
		} else {
			req.open('GET', url, true);
			req.send('');
		}
	} else {
		alert('unable to make the request');
	}
}

function FormCollect(oForm) {
	// sort elements so same names will be adjacent to each other
	var arrElts = getFormElements(oForm).sort(function(a,b){return ((a.name<b.name)?1:(a.name==b.name)?0:-1);});

	// for each form element ; append value to url
	var oRetvals={};
	var oCurrent;
	while (oCurrent = arrElts.pop()) {
		var sCTName = oCurrent.tagName.toLowerCase();
		var sCName = oCurrent.name.toLowerCase();
		var sCType = ((oCurrent.type)?oCurrent.type:'').toLowerCase();

		// handle input[type="radio|checkbox"]
		if (sCTName == "input" && /^(?:radio|checkbox)$/.test(sCType)) {
			if (oCurrent.checked || oCurrent.selected)
				oRetvals[oCurrent.name] = oCurrent.value;
		}

		// handle select[multiple]
		if (sCTName == "select" && oCurrent.multiple && oCurrent.options) {
			var sTemp='';
			for (i=0,len=oCurrent.options.length,sTemp=''; i < len; i++)
				if (oCurrent.options[i].selected)
					sTemp+=FormCollect_Encode(oCurrent.options[i].value) + ',';
			oRetvals[oCurrent.name] = sTemp;
		} else if ((sCTName == "input" && /^(?:text|password|hidden)$/.test(sCType)) || /^(?:select|textarea)$/.test(sCTName)) {
			oRetvals[oCurrent.name] = oCurrent.value;
		}
	}
	return oRetvals;
}

function FormCollect_Encode(s) {
	return escape(s);
	return encodeURIComponent(s);
}

// Form collect - returns a js object
function FormCollect_Record(oForm) {
	var arrElts = getFormElements(oForm);
	var oCurrent;
	var oRecord = {};
	while (oCurrent = arrElts.pop()) {
		var sCTName = oCurrent.tagName.toLowerCase();
		var sCName = oCurrent.name.toLowerCase();
		var sCType = ((oCurrent.type)?oCurrent.type:'').toLowerCase();

		/* handle input[type="radio|checkbox"] */
		if (sCTName == "input" && /^(?:radio|checkbox)$/.test(sCType)) {
			if (!oRecord[oCurrent.name]) oRecord[oCurrent.name]=[];
			if (oCurrent.checked || oCurrent.selected) oRecord[oCurrent.name].push(oCurrent.value);
		}

		/* handle select[multiple] */
		if (sCTName == "select" && oCurrent.multiple && oCurrent.options) {
			oRecord[oCurrent.name] = [];
			for (i=0,len=oCurrent.options.length,sTemp=''; i < len; i++)
				if (oCurrent.options[i].selected)
					oRecord[oCurrent.name].push(oCurrent.options[i].value);
		} else if ((sCTName == "input" && /^(?:text|password|hidden)$/.test(sCType)) || /^(?:select|textarea)$/.test(sCTName)) {
			oRecord[oCurrent.name] = oCurrent.value;
		} else if (sCTName == "input" && sCType == "file") {
		}
	}
	return oRecord;
}

// Set a form's value
function setFormValue(oForm,name,v) {
	// Error check the input
	if (!oForm) return alert('Error: no form');
	if (!name) return alert('Error: no name');
	if (!v && v!=0) v = '';

	// Go through each element : Set the value
	var arrElts = getFormElements(oForm);
	var oCurrent;
	while (oCurrent = arrElts.pop()) {
		if (oCurrent.name==name) {
			var sCTName = oCurrent.tagName.toLowerCase();
			var sCName = oCurrent.name.toLowerCase();
			var sCType = ((oCurrent.type)?oCurrent.type:'').toLowerCase();

			/* handle input[type="radio|checkbox"] */
			if (sCTName == "input" && /^(?:radio|checkbox)$/.test(sCType)) {
				if (!v.join) v = [v];
				if ('checked' in oCurrent) oCurrent.checked = inArray(oCurrent.value,v);
				if ('selected' in oCurrent) oCurrent.selected = inArray(oCurrent.value,v);
			}

			/* handle select[multiple] */
			if (sCTName == "select" && oCurrent.multiple && oCurrent.options) {
				if (!v.join) v = [v];
				for (i=0; i < oCurrent.options.length; i++)
					oCurrent.options[i].selected = inArray(oCurrent.options[i].value,v);
			} else if ((sCTName == "input" && /^(?:text|password|hidden)$/.test(sCType)) || /^(?:select|textarea)$/.test(sCTName)) {
				oCurrent.value = v;
			} else if (sCTName == "input" && sCType == 'file') {
				// reset the file field only
				oCurrent.value = '';
				oCurrent.parentNode.replaceChild(oCurrent.cloneNode(false), oCurrent);
			}
		}
	}
}

// Retreives a list of form elements
function getFormElements(oForm) {
	var arrElts=[];
	// put all elements of the form into an array
	for (var i=oForm.elements.length-1; i >= 0; i--) {
		oCurrent = oForm.elements[i];
		if (oCurrent.name && !oCurrent.disabled) arrElts.push(oCurrent);
	}
	return arrElts;
}

// Get the values from a form where the name of the input = name ; returns an array
function getFormValue(oForm,name) {
	var aRetvals = [];
	var arrElts = getFormElements(oForm);
	var oCurrent;
	while (oCurrent = arrElts.pop()) {
		if (oCurrent.name==name) {
			var sCTName = oCurrent.tagName.toLowerCase();
			var sCName = oCurrent.name.toLowerCase();
			var sCType = ((oCurrent.type)?oCurrent.type:'').toLowerCase();

			/* handle input[type="radio|checkbox"] */
			if (sCTName == "input" && /^(?:radio|checkbox)$/.test(sCType)) {
				if (oCurrent.checked || oCurrent.selected) aRetvals.push(oCurrent.value);
			}

			/* handle select[multiple] */
			if (sCTName == "select") {
				for (i=0;i<oCurrent.options.length;i++)
					if (oCurrent.options[i].selected) 
						aRetvals.push(oCurrent.options[i].value);
			} else if ((sCTName == "input" && /^(?:text|password|hidden)$/.test(sCType)) || /^(?:select|textarea)$/.test(sCTName)) {
				aRetvals.push(oCurrent.value);
			}
		}
	}
	return aRetvals;
}

function addEvent(obj, evType, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent('on'+evType, fn);
		return r;
	} else {
		return false;
	}
}

function refresh() {
	var sURL = unescape(window.location.pathname);
    window.location.reload( false ); // JS 1.2
    return;
	window.location.href = sURL; // JS 1.0
	window.location.replace( sURL ); // JS 1.1
}

// inform the user to complete field f
function informUser(f) {
	alert("Les champs n'ont pas tous ete remplis. Veuillez repondre a ce qui suit : " + "\n" + f.replace(/\* /g,""));
}

// Validate the form
function validateForm(f,requiredString,customValidator) {
	var fields=[];
	var labels={};
	var ret = true;
	try {
		// gather the fields and labels from the DOM
		var oLabels = document.getElementsByTagName("label");
		for (var i=0;i<oLabels.length;i++) { 
			var sRel = oLabels[i].rel || (oLabels[i].getAttribute!=undefined ? oLabels[i].getAttribute("rel") : '') || '';
			var sFor = oLabels[i].htmlFor || (oLabels[i].getAttribute!=undefined ? oLabels[i].getAttribute("for") : '') || '';
			var sText = oLabels[i].innerText || oLabels[i].textContent || '';
			if (sFor!='' && sRel!='optional' && (!requiredString || sText.indexOf(requiredString)>=0)) {
				fields.push(sFor);
				labels[ sFor ] = sText.replace(':','');
			}
		}
		// check each field
		var invalid_fields = [];
		var invalid_labels = [];
		for (var i in fields) {
			var field = fields[i];
			var label = labels[field];
			try {
				var v = getFormValue(f,field);
				if (v.length==0 || v[0].length==0 
					|| (/email/i.test(fields[i]) && !/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(v))
					|| !(customValidator==undefined || customValidator(field,v,f))
				) {
					invalid_labels.push(label);
					invalid_fields.push(field);
				}
			} catch(e) {
				alert("ERROR on field: " + fields[i] + " , " + (e.name || e.description) + " on line: " + e.lineNumber);
				ret=false; 
			}
		}

		if (invalid_fields.length>0) {
			informUser(invalid_labels.join("\n"));
			var field = invalid_fields[0];
			if (f[field].type && f[field].type.toLowerCase()!='radio') f[field].focus();
			ret = false;
		}
	} catch (e) {
		alert("ERROR: " + e.description);
		ret = false;
	} finally {
		return ret;
	}
}
