// JavaScript Document

function getBrowserWidth(){
		if (window.innerWidth){
			return window.innerWidth;}	
		else if (document.documentElement && document.documentElement.clientWidth != 0){
			return document.documentElement.clientWidth;	}
		else if (document.body){return document.body.clientWidth;}		
			return 0;
}

function check( coche, champ, debut, fin ) {
	for ( i = debut; i < fin; i++ ) champ[ i ].checked = coche;
}

function dynamicLayout(){
    var browserWidth = getBrowserWidth();

    //Load Thin CSS Rules
    if (browserWidth < 890){
        changeLayout("mince" );
    }
	
	if (browserWidth < 1200 && browserWidth > 890){
        changeLayout("moyen" );
    }

    //Load Wider CSS Rules
    if (browserWidth > 1200){
        changeLayout("large" );
    }
}

function formButtonFever(formName,action){
	var myString = "document."+formName+"."+action+"();";
	eval(myString);
}

// changeLayout is based on setActiveStyleSheet function by Paul Sowdon 
// http://www.alistapart.com/articles/alternate/
function changeLayout(description){
   var rows = document.getElementsByTagName('link');
   for(var i=0, row; row = rows[i]; i++){
	   if (row.getAttribute("title") == description){row.disabled = false;}
	   else if (row.getAttribute("title") != "normal"){row.disabled = true;}
   }
}

//addEvent() by John Resig
function addEvent( obj, type, fn ){ 
   if (obj.addEventListener){ 
      obj.addEventListener( type, fn, false );
   }
   else if (obj.attachEvent){ 
      obj["e"+type+fn] = fn; 
      obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); } 
      obj.attachEvent( "on"+type, obj[type+fn] ); 
   } 
} 

//Run dynamicLayout function when page loads and when it resizes.
addEvent(window, 'load', dynamicLayout);
addEvent(window, 'resize', dynamicLayout);

function MM_swapImgRestore() {
  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_findObj(n, d) {
  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_setTextOfTextfield(objName,x,newText) {
  var obj = MM_findObj(objName); if (obj) obj.value = newText;
}

function MM_swapImage() {
  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_openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}

function MM_popupMsg(msg) {
  alert(msg);
}

function MM_validateForm() {
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i] );
    if (val) { nm=val.name; if ( (val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain a valid e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain numbers only.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('An error occured:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function checkCheckBox(f){
if (f.politique.checked == false ){
alert('You must accept by cheking the appropriate box');
return false;
} else {
return true;
}
}

function checkFields(f){
if (f.motdepasse2.value != f.motdepasse.value )
{
alert('You made a typing mistake in your password.');
return false;
} 
if (f.politique.checked == false ){
alert('You must accept by cheking the appropriate box');
return false;
} 
}

function checkCaracteres(f){
var iChars = "!@#$%^&*()+=-[]\\\';,/{}|\":<>?éèêçàâôûîÉÈÊÇÀÂÔÛÎ";
if (f.img.value.indexOf('\\') != -1 ) { 
var platformimg = f.img.value.substring(f.img.value.lastIndexOf('\\')+1);
} if (f.img.value.indexOf('/') != -1 ) {
var platformimg = f.img.value.substring(f.img.value.lastIndexOf('/')+1);
}
 for (var i = 0; i < platformimg.length; i++) {
if (iChars.indexOf(platformimg.charAt(i)) != -1)
{
alert('You must use a file name without special characters, accents or other.\nRename the file following these rules.');
return false;
}
}
}

function checkCaracteresPDF(f){
var iChars = "!@#$%^&*()+=-[]\\\';,/{}|\":<>?éèêçàâôûîÉÈÊÇÀÂÔÛÎ";
if (f.fichierPDF.value.indexOf('\\') != -1 ) { 
var platformimg = f.fichierPDF.value.substring(f.fichierPDF.value.lastIndexOf('\\')+1);
} if (f.fichierPDF.value.indexOf('/') != -1 ) {
var platformimg = f.fichierPDF.value.substring(f.fichierPDF.value.lastIndexOf('/')+1);
}
 for (var i = 0; i < platformimg.length; i++) {
if (iChars.indexOf(platformimg.charAt(i)) != -1)
{
alert('You must use a file name without special characters, accents or other.\nRename the file following these rules.');
return false;
}
}
}

function checkCaracteresPhoto(f){
var iChars = "!@#$%^&*()+=-[]\\\';,/{}|\":<>?éèêçàâôûîÉÈÊÇÀÂÔÛÎ";
if (f.photo1.value.indexOf('\\') != -1 ) { 
var platformimg = f.photo1.value.substring(f.photo1.value.lastIndexOf('\\')+1);
} if (f.photo1.value.indexOf('/') != -1 ) {
var platformimg = f.photo1.value.substring(f.photo1.value.lastIndexOf('/')+1);
}
 for (var i = 0; i < platformimg.length; i++) {
if (iChars.indexOf(platformimg.charAt(i)) != -1)
{
alert('You must use a file name without special characters, accents or other.\nRename the file following these rules.');
return false;
}
}
}

function MM_jumpMenu(targ,selObj,restore){
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'" );
  if (restore) selObj.selectedIndex=0;
}

function GP_popupConfirmMsg(msg) {
  document.MM_returnValue = confirm(msg);
}

function validerFormulaire( formulaire ) {
	if ( formulaire.noJournaliste.value == '%%' ) {
		alert( 'You must select a journalist!' );
	} else if ( formulaire.noCategorie.value == '%%' ) {
		alert( 'You must insert a valid categorie!' );
	} else if ( formulaire.texte.value == "" ) {
		alert( 'The text box of the article can\'t be empty!' );
	} else {
		texte = formulaire.texte.value.toUpperCase();

		texte.replace( "@T2:", "@T1" );
		formulaire.texte.value = formulaire.texte.value.replace( "@T2:", "@T1:" );

		t = texte.split("@T:" );
		t1 = texte.split("@T1:" );
		t2 = texte.split("@T2:" );
		l = texte.split("@L:" );
		s = texte.split("@S:" );
		r = texte.split("@R:" );
		r2 = texte.split("@R2:" );
		bv = texte.split("@BV:" );
		st = texte.split("@ST:" );

		continuer = true;
		if ( ( texte.indexOf( '@T1:' ) > -1 ) && ( texte.indexOf( '@T2:' ) > -1 ) ) {
			// Il y a un T1 et un T2
			texte = texte.replace( "@T2:", "@ST:" );
			formulaire.texte.value = formulaire.texte.value.replace( "@T2:", "@ST:" );
		}
		if ( t.length > 1 && t1.length == 1 && t2.length == 1 ) {
			texte = texte.replace( "@T:", "@T1:" );
			formulaire.texte.value = formulaire.texte.value.replace( "@T:", "@T1:" );
			t1 = texte.split( "@T1:" );
		}
		if ( r.length == 1 && bv.length > 1 && r2.length == 1 ) {
			texte = texte.replace( "@BV:", "@R:" );
			formulaire.texte.value = formulaire.texte.value.replace( "@BV:", "@R:" );
			formulaire.texte.value = formulaire.texte.value + "\n@BV: ";
		}
		if ( texte.substring( texte.indexOf( "@S:" ) - 1, texte.indexOf( "@S:" ) ) != "\n" && s.length > 1 ) {
			texte = texte.substring( 0, texte.indexOf( "@S:" ) ) + "\n" + texte.substring( texte.indexOf( "@S:" ), texte.length );
			formulaire.texte.value = formulaire.texte.value.substring( 0, formulaire.texte.value.indexOf( "@S:" ) ) + "\n" + formulaire.texte.value.substring( formulaire.texte.value.indexOf( "@S:" ), formulaire.texte.value.length );
		}
		if ( texte.substring( 0, 6 ) == "AGENDA" || texte.substring( 0, 9 ) == "BABILLARD" ) {
			texte = "@T1:" + texte;
			formulaire.texte.value = "@T1:" + formulaire.texte.value;
		} else {
			if ( t1.length == 1 && t2.length == 1 && bv.length == 1 ) {
				nouveauTitre = prompt( 'No title has been detected !\nInsert the article\'s title without the `@T1`:', '' );
				if ( nouveauTitre == "" || nouveauTitre == null ) continuer = false
				else {
					continuer = true;
					texte = "@T1:" + nouveauTitre + "\n" + texte;
					formulaire.texte.value = "@T1:" + nouveauTitre + "\n" + formulaire.texte.value;
				}
			}
		}

		if ( t2.length > 2 ) erreur( 'There is two @T2 production codes.  Please eliminate one of the two.' );
		else if ( l.length > 2 ) erreur( 'There is two @L production codes.  Please eliminate one of the two.' );
		else if ( s.length > 2 ) erreur( 'There is two @S production codes.  Please eliminate one of the two.' );
		else if ( texte.substring( 0, 1 ) != '@' ) erreur( 'Warning, the text must start with a production code (@)' );
		else if ( st.length > 2 && texte.substring( 0, 4 ) != "@T1:" ) erreur( 'Please insert a title!\n\nMake sure the title is a @T1 and not a @ST.' );
		else {
			if ( continuer ) formulaire.submit();
		}
	}
}

function erreur( texte ) {
	alert( 'There is a spelling in the production codes.\n\n' + texte );
}

function validerOrganisme( formulaire ) {
	
	condition = true;
	
	if ( formulaire.conditions ) if ( formulaire.conditions.value == "" ) condition = false;
	
	if ( !condition	) {
		alert( 'You must accept the conditions to continue !');
		formulaire.conditions.focus();
	} else if ( formulaire.nom.value == "" ) {
		alert( 'The name of the organization field cannot be empty.' );
		formulaire.nom.focus();
	} else if ( formulaire.description.value == "" ) {
		alert( 'The description of the organization field cannot be empty.' );
		formulaire.description.focus();
	} else if ( formulaire.contact.value == "" ) {
		alert( 'The contact field cannot be empty.' );
		formulaire.contact.focus();
	} else if ( formulaire.responsable.value == "" ) {
		alert( 'The persone in charge field cannot be empty.' );
		formulaire.responsable.focus();
	} else if ( formulaire.courriel.value == "" ) {
		alert( 'The e-mail address field cannot be empty.' );
		formulaire.courriel.focus();
	} else if ( formulaire.orgpassword.value == "" ) {
		alert( 'The password field cannot be empty.' );
		formulaire.orgpassword.focus();
	} else formulaire.submit();
}

function validerDate( date ) {
	annee = date.substring( 0, 4 );
	mois = date.substring( 5, 7 );
	jour = date.substring( 8, 10 );
	tiret1 = date.substring( 4, 5 );
	tiret2 = date.substring( 7, 8 );

	if ( ( annee > 1970 && annee < 2040 ) &&
		 ( mois >= 1 && mois <= 12 ) &&
		 ( jour >= 1 && jour <= 31 ) &&
		 ( tiret1 == "-" && tiret2 == "-" ) ) retour = true;
	else retour = false;
	
	return retour;
}

function checkFileUpload(form, extensions, requireUpload, sizeLimit, minWidth, minHeight, maxWidth, maxHeight, saveWidth, saveHeight) {
	var allUploadsOK = true;
	document.MM_returnValue = false;
	for (var i = 0; i < form.elements.length; i++) {
		// alert('for loop');
		field = form.elements[i];
		if (field.type.toUpperCase() != 'FILE') {
			continue;
		}
		checkOneFileUpload(field,extensions,requireUpload,sizeLimit,minWidth,minHeight,maxWidth,maxHeight,saveWidth,saveHeight);
		// alert ('Checked filefield '+field.name+', is OK? '+field.uploadOK);
		if (!field.uploadOK) {
			allUploadsOK = false;
			break;
		}
	}
	if (allUploadsOK) {
		document.MM_returnValue = true;
	}
}

function checkOneFileUpload(field, extensions, requireUpload, sizeLimit, minWidth, minHeight, maxWidth, maxHeight, saveWidth, saveHeight) {
	// alert('Start checking filefield '+field.name);
	var fileName = field.value.replace(/"/gi,'');
	field.uploadOK = false;
	if (fileName == '') {
		if (requireUpload) {
			alert('File is required!');
			field.focus();
			return;
		} else {
			field.uploadOK = true;
		}
	} else {
		if (extensions != '') {
			checkFileExtension(field, fileName, extensions);
		} else {
			field.uploadOK = true;
		}
		if (!document.layers && field.uploadOK) {  
			document.PU_uploadForm = field.form;
			re = new RegExp("\.(gif|jpg|png|bmp|jpeg)$","i" );
			if (re.test(fileName) && (sizeLimit != '' || minWidth != '' || minHeight != '' || maxWidth != '' || maxHeight != '' || saveWidth != '' || saveHeight != '')) {
				checkImageDimensions(field,sizeLimit,minWidth,minHeight,maxWidth,maxHeight,saveWidth,saveHeight);
			}
		}
	}
	return;
}

function checkFileExtension(field, fileName, extensions) {
	// alert('start checkFileExtension');
	var re = new RegExp("\\.(" + extensions.replace(/,/gi,"|").replace(/\s/gi,"") + ")$","i" );
	var agt = navigator.userAgent.toLowerCase();
	var is_mac = (agt.indexOf("mac") != -1);
	var is_op = (agt.indexOf("opera") != -1);
	if (is_op) {
		var ext = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length);
		var extArr = extensions.split(',');
		var extCheck = false;
		// alert('ext = ' + ext + ' & extArr = ' + extArr);
		for (var i = 0; i < extArr.length; i++) {
			// alert('if ('+extArr[i].toLowerCase()+' == '+ext.toLowerCase()+')');
			if (extArr[i].toLowerCase() == ext.toLowerCase()) {
				extCheck = true;
				break;
			}
		}
		// alert('check = ' + extCheck);
		if (extCheck == false) {
			alert('This file type is not allowed for uploading.\nOnly the following file extensions are allowed: ' + extensions + '.\nPlease select another file and try again.');
			field.focus();
			field.uploadOK = false;
			return;
		}
	} else {
		if (!re.test(fileName)) {
			alert('This file type is not allowed for uploading.\nOnly the following file extensions are allowed: ' + extensions + '.\nPlease select another file and try again.');
			field.focus();
			field.uploadOK = false;
			return;
		}
	}
	field.uploadOK = true;
}

function checkImageDimensions(field,sizeL,minW,minH,maxW,maxH,saveW,saveH) {
	// alert('start checkImageDimensions');
	var agt = navigator.userAgent.toLowerCase();
	var is_mac = (agt.indexOf("mac") != -1);
  var is_ie = document.all;
	var is_ns6 = (!document.all && document.getElementById ? true : false);
	var fileURL = field.value;
	if (is_ie && is_mac) {
		begPos = fileURL.indexOf('/',1);
		if (begPos != -1) {
			fileURL = fileURL.substring(begPos+1,fileURL.length);
		}
	}
	fileURL = 'file:///' + fileURL.replace(/:\\/gi,'|/').replace(/\\/gi,'/').replace(/:([^|])/gi,'/$1').replace(/"/gi,'').replace(/^\//,'');
	if (!field.gp_img || (field.gp_img && field.gp_img.src != fileURL) || is_ns6) {
		if (is_ie && is_mac) {
			var dummyImage;
			dummyImage = document.createElement('IMG');
			dummyImage.src = 'dummy.gif';
			dummyImage.name = 'PPP';
			// dymmyImage.style = 'DISPLAY:NONE';
			// document.body.appendChild(dummyImage);
			field.gp_img = dummyImage;
		} else {
			field.gp_img = new Image();
		}
		with (field) {
			gp_img.field = field;
			gp_img.sizeLimit = sizeL*1024;
			gp_img.minWidth = minW;
			gp_img.minHeight = minH;
			gp_img.maxWidth = maxW;
			gp_img.maxHeight = maxH;
			gp_img.saveWidth = saveW;
			gp_img.saveHeight = saveH;
			gp_img.onload = showImageDimensions;
			gp_img.src = fileURL+'?a=123'; // +(Math.round(Math.random()*998)+1);
		}
	}
}

function new_freecap()
{
	// loads new freeCap image
	if (document.getElementById)
	{
		// extract image name from image source (i.e. cut off ?randomness)
		thesrc = document.getElementById("freecap").src;
		thesrc = thesrc.substring(0,thesrc.lastIndexOf(".")+4);
		// add ?(random) to prevent browser/isp caching
		document.getElementById("freecap").src = thesrc+"?"+Math.round(Math.random()*100000);
	} else {
		alert("Sorry, cannot autoreload freeCap image\nSubmit the form and a new freeCap will be loaded" );
	}
}