var TYPE_ACCES = "non_securise";
var B_AUTHENTIFIED = false;
var B_CARTOLOADED = false;
var B_ADMIN = false;
var EXTENT_URL = false;

function navCurrent(nomNav,iCur,nbreNav){
	for(nav=1;nav<=nbreNav;nav++){
		cur = $(nomNav+nav);		
		if (iCur == nav) {
			cur.className="current";
		}else {
			cur.className="";
		}
	}
}

function showDiv(nomDiv, mode){
	if(cibleClass = $(nomDiv)) {
		cibleClass.style.display = mode;	
		if(mode != 'none') nomDiv.className = "current";
	}
}

function ctrlClick(nTab){
	showDiv('pnrlegend', 'none');
	showDiv('pnrtheme', 'none');
	showDiv('pnrinfo', 'none');
	showDiv(nTab, 'block');
}

function tabClick(nTab){
	showDiv('contenudemo', 'none');
	showDiv('contenuhmcarto', 'none');
	showDiv('contenuloisir', 'none');
	showDiv('contenulogin', 'none');
	showDiv('contenuadmin', 'none'); 
	if(nTab == 'contenuadmin'){
		if($('contenuadmin').getElementsByTagName('div').length == 0){
			new Ajax('admin.php',{
					method: 'post',
					evalScripts: false,
					update:'contenuadmin'
				}).request();
		}
		showDiv('contenuadmin', 'block');
	}
	else{
		showDiv(nTab, 'block');
	}
}

function bmapClick(nTab){
	showDiv('bmapchoice', 'none');
	showDiv('bmapcreate', 'none');
	if(nTab == 'bmapchoice'){
		$('bmaphidcount').value='0';
	}else if(nTab == 'bmapcreate'){
		$('bmaphidcount').value='1';
	}
	showDiv(nTab, 'block');
}

function padmClick(nTab){
	showDiv('pnradmbase', 'none');
	showDiv('pnradmuser', 'none');
	showDiv('pnradmdoc', 'none');
	showDiv('pnrstatexport', 'none');
	showDiv('donneesCommunale', 'none');
	
	showDiv(nTab, 'block');
}

function pusrClick(nTab){
	showDiv('formUser', 'none');
	showDiv('validUser', 'none');
	showDiv(nTab, 'block');
}

function sh(idO, oClick){
	var elt = $(idO);
	if(elt != null){
		if(elt.style.display == 'none'){
			elt.style.display = 'block';
			oClick.src = 'images/control/expand.gif';
			elt.parentNode.childNodes[2].style.color = "#afb3a5";
		}
		else{
			 elt.style.display = 'none';
			 oClick.src = 'images/control/collapse.gif';
			elt.parentNode.childNodes[2].style.color = "#cfc06b";
		}
	}
}

function chargeListeCarte(iIdRubrique){
    var parurl = 'listeCarte.php';
    switch(TYPE_ACCES){
        case 'non_securise':
            var sRequest = 'id_rubrique='+iIdRubrique+'&type_acces='+TYPE_ACCES;
            break;
        case 'securise':        
            var sRequest = 'id_rubrique='+iIdRubrique+'&type_acces='+TYPE_ACCES;
            break;
        case 'mes_cartes':
            var sRequest = 'type_acces='+TYPE_ACCES;
            break; 
       case 'par_commune':        
            var sRequest = 'type_acces='+TYPE_ACCES;
            parurl = "accesCommune.php";
            break;            
    }
    
    new Ajax(parurl,{
    			method: 'get',
    			postBody: sRequest,
    			evalScripts: true,
    			update:'contenuloisir'
    		}).request();
}

function editLegend(layerName){
	openCadre_arc('cadreGestionLayer','Gestion de couche',500,388,360,50,'arcViewWeb/layerForm.php?layerName='+layerName);
}

function editLegendLabel(layerName){
	openCadre_arc('cadreGestionLayer','Edition du label',100,388,205,183,'arcViewWeb/labelEdit.php?hiddenAfter=true&layer='+layerName);
}


function openCadre_arc(divNomT,titleT,le,wi,he,to,UrlT){
	if(divNomT == 'cadreGestionLayer'){
		var par = document.body;
	}else{
		 var par = Windows.getWindow('cadreGestionLayer').getContent();
	}
	gWindowz.calledAjaxContent(divNomT,{title:titleT,left:le,width:wi,height:he,top:to,parent:par,zIndex: 2000},UrlT)
}

function chargeLogin(iIdRubrique){
    var sRequest = "id_rubrique="+iIdRubrique;
    new Ajax('authent.inc.php',{
    			method: 'post',
    			postBody: sRequest,
    			evalScripts: true,
    			update:'contenulogin'
    		}).request();
}

function authentify(iIdRubrique){
    var sLogin = $('pseudo').value;
    var sPass = $('pass').value;
    if(sPass == "" || sLogin == ""){
        alert('Veuillez remplir les champs!');
        return;
    }
    var sRequest = 'pseudo='+sLogin+"&pass="+sPass+"&type_acces="+TYPE_ACCES+"&id_rubrique="+iIdRubrique;
    new Ajax('login.php',{
    			method: 'post',
    			postBody: sRequest,
    			evalScripts: true
    		}).request();
}

function fermerAllFrameOnChangePage(){
	try{
		if($('divarret_imprimCarto'))$('divarret_imprimCarto').remove();	
		if($('divarret_Detail'))$('divarret_Detail').remove();	
		if($('divarret_exportCarto'))$('divarret_exportCarto').remove();	
		if($('cadreGestionLayer'))$('cadreGestionLayer').remove();	
		if($('divarret_listpanier'))$('divarret_listpanier').remove();	
	}catch(e){}
}

function loadContent(iIdRubrique){
	fermerAllFrameOnChangePage() ;
	
	 $('srcresultat').innerHTML = "" ;
    switch(TYPE_ACCES){
        case 'mes_cartes':
            if(B_AUTHENTIFIED == false){
                
                tabClick('contenulogin');
                
                chargeLogin(iIdRubrique);               
            } else{
                tabClick('contenuloisir');
                chargeListeCarte(iIdRubrique);
            }
            break;
        case 'non_securise':            
            tabClick('contenuloisir');
            chargeListeCarte(iIdRubrique);
            break;
        case 'securise':
            if(B_AUTHENTIFIED == false){
                tabClick('contenulogin');
                chargeLogin(iIdRubrique);               
            } else{
                tabClick('contenuloisir');
                chargeListeCarte(iIdRubrique);
            }
            break;
        case 'par_commune':            
            tabClick('contenuloisir');
            chargeListeCarte(iIdRubrique);
            //alert('');
            break;
    }    
}

function searchCarte(sTypeAcces){
    var id_rubrique= (arguments[1]) ? arguments[1] : 0;
    var motcle = "";
    
    if(sTypeAcces != 'acces_commune'){
        TYPE_ACCES = sTypeAcces;
        if(id_rubrique != "none"){
            if($('searchMapTxt')) motcle = $('searchMapTxt').value;
            if(motcle == ""){
                return;
            }
            var sRequest= "act=search&id_rubrique="+id_rubrique+"&type_acces="+TYPE_ACCES+"&motcle="+motcle;
            new Ajax('listeCarte.php',{
    			method: 'post',
    			postBody: sRequest,
    			evalScripts: true
    		}).request();
        }
    } 
}

function reloadBaseAdm(typeBaseAdm,libId,valueId){
	url = "ajax.inc.php?act=disabled_bouton&id_rubrique="+valueId;
	new Ajax(url, {
		method: 'get',
		onComplete : function(str) {
				if(str == "")return false ;
				var res = eval("("+str+")");
				if(res.etat_bouton=='TRUE'){
					$('ajouter_themesAdm').disabled=true;
					if(!res.etat_mod_butt)$('modifier_themesAdm').disabled=true;
					else $('modifier_themesAdm').disabled=false;
					$('supprimer_themesAdm').disabled=true;
				}
				else{
					$('ajouter_themesAdm').disabled=false;
					$('modifier_themesAdm').disabled=false;
					$('supprimer_themesAdm').disabled=false;
				}
		}
	}).request();
	 
	urlBase = "ajax.inc.php?act=baseAdm&"+libId+"="+valueId+"&niveau="+typeBaseAdm;
	new Ajax(urlBase, {
		method: 'get',
		onComplete : function(str) {
			eval(str);
		},
		evalScripts: true
	}).request();
}

function openCadre(url,param,titre,w,h,idDiv,idDivCenter){
	switch(idDiv){
		case "ajoutFam":
			param += "&action=ajoutFam"; 
			break;
		case "modifFam":
			idFam = $('selFamAdm').value;
			if(idFam == null || idFam == ""){
				alert("Vous devez choisir une famille à modifier !!");
				return false;
			}
			param += "&action=modifFam&idFam="+idFam; 
			break;
		case "ajoutRub":
			idFam = $('selFamAdm').value;
			if(idFam == null || idFam == ""){
				alert("Vous devez choisir une famille à associer avec cette nouvelle rubrique !!");
				return false;
			}
			param += "&action=ajoutRub&idFam="+idFam;
			break;
		case "modifRub":
			idFam = $('selFamAdm').value;
			idRub = $('selRubAdm').value;
			if(idRub == null || idRub == ""){
				alert("Vous devez choisir une rubrique à modifier !!");
				return false;
			}
			param += "&action=modifRub&idRub="+idRub+"&idFam="+idFam; 
			break;
			
		case "ajoutThem":
			idFam = $('selFamAdm').value;
			idRub = $('selRubAdm').value;
			if(idRub == null || idRub == ""){
				alert("Vous devez choisir une rubrique à associer avec ce nouveau théme !!");
				return false;
			}
			param += "&action=ajoutThem&idFam="+idFam+"&idRub="+idRub;
			break;
		case "modifThem":
			idFam = $('selFamAdm').value ;
			idRub = $('selRubAdm').value ;
			idThem = $('selThmAdm').value ;
			if(idThem == null || idThem == ""){
				alert("Vous devez choisir un thème à modifier !!") ;
				return false ;
			}
			param += "&action=modifThem&idRub="+idRub+"&idFam="+idFam+"&idThem="+idThem ; 
			break ;
		case "ajoutCarte":
			idCarte = $('selCrtAdm').value ;
			idTheme = $('selThmAdm').value ;
			if(idTheme == null || idTheme == ""){
				alert("Vous devez choisir un thème à associer avec cette nouvelle carte !!") ;
				return false ;
			}
			param += "&action=ajoutCarte&idTheme="+idTheme+"&idCarte="+idCarte ; 
			break ;
		case "modifCarte":
			idCarte = $('selCrtAdm').value ;
			idTheme = $('selThmAdm').value ;
			if(idCarte == null || idCarte == ""){
				alert("Vous devez choisir une carte à modifier !!") ;
				return false ;
			}
			param += "&action=modifCarte&idTheme="+idTheme+"&idCarte="+idCarte ; 
		break ;
		
	}
	openCadreAdm(titre,url,param,{id:idDiv,divCenter:idDivCenter,width:w,height:h});		
}
function getOffset(element,attr){
	var offset=0;
	element = $(element);
	while(element){
		offset+=element[attr];
		element=element.offsetParent
  	}
	return offset;
}
function ajoutModifFammille(){
	var idFam = $("idFamille").value;
	var titreFam = $("titreFam").value;
	
}

function loadLien(idlien, idobjet){
  if(typeof(gMap) == 'undefined'){
  	initMap();
  }
	referenceByRub.builref() ;
  gMap.sendX_Load('act=zoomLien&id_lien='+idlien+'&id_objet='+idobjet) ;
}

function changeAdmin(){
	new Ajax('ajax.inc.php',{
		method: 'post',
		postBody: 'act=whereiam',
		evalScripts: true
	}).request();
}

function loadCarte(iIdDoc){
	ID_CARTO_CURENT = iIdDoc ;
	$('ariane').innerHTML = "" ;
  idObj = (arguments[1]) ? arguments[1] : "none";
  tabClick('contenudemo'); 
  if(B_AUTHENTIFIED){
      $('drawtools').style.display = 'block';
      $('addmap').style.display = 'block';
      if(TYPE_ACCES == 'non_securise'){
          $('sendmail').style.display = 'block';
      } else {        
          $('sendmail').style.display = 'none';
      }
  } else {
      if(TYPE_ACCES == 'non_securise'){
          $('sendmail').style.display = 'block';
          $('drawtools').style.display = 'none';
          $('addmap').style.display = 'none';
      } else {        
          $('sendmail').style.display = 'none';
          $('drawtools').style.display = 'block';
          $('addmap').style.display = 'block';
      }
  }
  
  if(B_CARTOLOADED  == false){             
     if(typeof(gMap) == 'undefined')initMap();
     B_CARTOLOADED = true;           
  }else{
  }
  if(gMap){ 
  		deleteDessin();       
      param = "act=loadMap&idDoc="+iIdDoc+"&type_acces="+TYPE_ACCES; 
      if(idObj != "none") param += "&idObj="+idObj;           
      $('ulctrlCouche').innerHTML = "Chargement ..." ;
      $('pnrlegend').innerHTML = "Chargement ..." ;
      $('imgA').style.display = "none" ;
      $('imgB').style.display = "none" ;
      referenceByRub.builref() ;
      gMap.sendX_Load(param);
	}     
	if(TYPE_ACCES != 'non_securise'){
		countnbrCarte(iIdDoc,TYPE_ACCES);
	}
	
}
function refreshSendMail(iIdDoc,sUrlProj, mapextent){
    if(TYPE_ACCES == 'non_securise'){
        sURL = sUrlProj+"index.php?act=parURL&idDoc="+iIdDoc+"&type_acces="+TYPE_ACCES;
        if(mapextent != "")sURL += "&mapextent="+mapextent;
        $('sendmail').href = 'mailto:?subject=url de la carte en cours&body='+encodeURIComponent(sURL); 
    }
}

function ajoutMesCartes(evt){
  var titre = $('titre').value;
  var sstitre = $('sstitre').value;
  if(titre == "" || sstitre == "" ){
      alert("Veuillez remplir tous les champs!!!");
      return;
  }
	var extent = gMap.extent.get();
  var sRequest= "act=ajout&titre="+titre+"&sstitre="+sstitre+"&extent="+extent;
	if(typeof(_Photo) != 'undefined'){
	    var paramDessin = _Photo.buildParam();
	    if(paramDessin != "empty"){
	        sRequest += '&'+paramDessin ;
	    }
	}
  new Ajax('formCarte.php',{
		method: 'post',
		postBody: sRequest,
		evalScripts: true
	}).request();
}





function listedetail(val){
	if(val != "" && $('ctrldet').style.display == 'none'){
		$('ctrldet').style.display = 'block';
		$('ulctrlButtonOk').style.display = 'block';
	}
	else if(val == "" && $('ctrldet').style.display == 'block'){
		$('ctrldet').style.display = 'none';
		$('ulctrlButtonOk').style.display = 'none';
	}
	var paramsend= "act=listedetail&valniveau="+val;
    new Ajax('ajax.inc.php',{
		method: 'post',
		postBody: paramsend,
		evalScripts: true
	}).request();
}
function goCadrage(){
	valniv = $('ctrlniv').value;
	valdet = $('ctrldet').value;
	if(valniv == 'com'){
		label = 'Communes'
		idchamp = 'INSEE';
		couche = 'communes';
	}else if(valniv == 'par'){
		label = 'parcs';
		idchamp = 'nom';
		couche = 'parc';
	}
	if(valdet == ''){
		alert('Vous devez choisir un détail');
		return;
	}
	var param = "couche="+couche+"&recherche="+valdet+"&idchamp="+idchamp+"&act=cadrepre"; 
	gMap.sendX_Load(param) ;
}

function ajoutPanier(){
	new Ajax("panierContent.php",{
	 	method:'get',
		evalScripts : true,		
		onComplete : function (request) {
			///
			try {
				$('corpsArret_panier').setHTML(request);
      }
      catch(e) {
      	return;
      }  
		}
	}).request();
	afficheFichePop("PANIER","Chargement ...",{id: "panier", divCenter: 'visualisation' ,style:{width:'400px',height:'200px'}}) ;
}

function successPanier(msg){
	var content = "<div class='mainContainer'>";
	content += "<div class='label' style='text-align:center'>"+msg+"</div>";
	content += "<div class='validate'>";
	content += "<input class='button' type='button' value='Ok' onclick='removeCadre(this)'></div>";
	content += "</div>";
	content += "</div>";
	//goOpenSimpleWindow({width: 400,height:230, top:50,left:410, title: "Ajout au panier"},content);
	openSimpleWin('Ajout au panier',content,'',350,150,200,420);
	
	
}

function afficherPanierContent(oObj, param1,param2){
	new Ajax("panierContent.php",{
	 	method:'post',
	 	postBody:"url="+param1+"?"+param2,
		evalScripts : false,		
		onComplete : function (request) {
			try {
      	oObj.innerHTML = request;
      }
      catch(e) {
      	return;
      }  
		}
	}).request();
}

function selectComArea(idCom){
    oComSelect = $('selCom');
    for(i = 0; i < oComSelect.options.length; i++){
        if(oComSelect.options[i].value == idCom && oComSelect.options[i].selected == false) {
             oComSelect.options[i].selected = true;
        } else {
            oComSelect.options[i].selected = false;
        }
        
    }

}
function twAller(_url,_cadre,_target){		
	if (_url){
		if (_cadre){
			parent._cadre.location.href = _url;
		} 
		else if (_target){
			_target = window.open(_url,_target);
		} 
		else{
			window.location.href = _url;
		}
	}
}
function getWindowHeight(){
	if (document.all) {
		return window.getHeight(); 
	} 
	else {
		return window.innerHeight; 
	}
}
function getWindowWidth(){
	if (document.all) { 
		return window.getWidth(); 
	} 
	else { 
		return window.innerWidth;
	}
} 
function setLayoutStyle(elt,attr,val){
	if(arguments[3])alert(arguments[3]);
	
	if($(elt)) {
		try {
			$(elt).setStyle(attr,val);
		}catch(e) {}
	}
}

var height_lgdContain = 0;

function getHeight_lgdContain(){
	if($("lgdContain_")) {
		height_lgdContain = $("lgdContain_").style.height;
	}	
	else height_lgdContain = 0;
}

function storeHeight_lgdContain(){
	if(height_lgdContain != 0) $("lgdContain_").style.height = height_lgdContain;
}
 
function initlayout(){
	x = getWindowWidth();
	y = getWindowHeight();
	oGobal = $('global');
	oDcarto = $('droitecarto');
	oDroitecarto = $('droitecarto');
	oContenudemo = $('contenudemo');
	oContenuhmc = $('contenuhmcarto');
	oContenthm = $('contenthm');
	oContenulog = $('contenulogin');
	oContenuls = $('contenuloisir');
	oContenuadm = $('contenuadmin');
	oControl = $('control');
	oCtrlctt = $('ctrlcontent');
	oLgdCtn = $('lgdContain');
	oLgdCtn_ = $('lgdContain_');
	oVisu = $('visualisation');
	oNavsub = $('navsub');
	oNavpath = $('navpath');
	oUlctrlThemes = $('ulctrlThemes');
	setLayoutStyle(oGobal,'width',x);
	setLayoutStyle(oGobal,'height',y);
	setLayoutStyle(oDcarto,'height',y);
	
	setLayoutStyle(oDroitecarto,'width',x);
	setLayoutStyle(oDroitecarto,'height',y);

	Cy = y - 110;
	Hy = Cy -40;
	setLayoutStyle(oContenudemo,'width',x);
	setLayoutStyle(oContenudemo,'height',Cy);
	setLayoutStyle(oContenuhmc,'height',Cy);
	//setLayoutStyle(oContenthm,'height',Hy);
	setLayoutStyle(oContenulog,'height',Cy);
	setLayoutStyle(oContenulog,'height',Cy);
	setLayoutStyle(oContenuls,'height',Cy);
	setLayoutStyle(oContenuadm,'height',Cy);
		
	Vx = x - 290;
	Vy = Cy - 140;
	setLayoutStyle(oVisu,'width',Vx);
	setLayoutStyle(oVisu,'height',Vy);

	Dy = Vy + 30;
	Ey = Dy - 70;
	Fy = Ey - 120;
	Ectry = Ey - 20;
	//alert(y);
	setLayoutStyle(oControl,'height',Dy);
	setLayoutStyle(oCtrlctt,'height',Ey);
	setLayoutStyle(oUlctrlThemes,'height',Ectry);
	
	setLayoutStyle(oLgdCtn,'height',Fy);
	setLayoutStyle(oLgdCtn_,'height',Ey);
}
function disconnect(){
    parurl = 'logout.php';
    new Ajax(parurl,{
		method: 'post',
		evalScripts: true
	}).request();
}

function download(){
	if(document.getElementById("expchoix1").checked) {
		param = "jpeg";
		twAller("export.pop.php?download="+param);
	}else if(document.getElementById("expchoix2").checked) {
		param = "jpeg1";
		twAller("export.pop.php?download="+param);
	}else if(document.getElementById("expchoix3").checked) {
		param = "png";
		twAller("export.pop.php?download="+param);
	}else if(document.getElementById("expchoix4").checked) {
		openCadre_('Exporté en Word','print.pop.php?type=word&scaleCur='+gMap.scale,'',{id: 'imprimCarto', width:400,height:310});
	}else if(document.getElementById("expchoix5").checked) {
		openCadre_('Exporté en Pdf','print.pop.php?type=pdf&scaleCur='+gMap.scale,'',{id: 'imprimCarto', width:400,height:310});
	}
}

function prudenceClose(){
	try{
		ds_hi();
	}catch(e){}
}

function affichedoc(valnomdoc,typedoc){
		twAller("download.php?param1="+valnomdoc+"&param2="+typedoc);
}

function displayDiv(strFooter,w,h){
    switch(strFooter){
        case 'contact':
            var url = 'contact.inc.php';
            var titre = 'Contacts';
        break; 
        case 'credit':
            var url = 'credit.inc.php';
            var titre = 'Crédits';
        break; 
        case 'lien':
            var url = 'liens.inc.php';
            var titre = 'Liens';
        break;		 
        case 'sitemap':
            var url = 'plan.php';
            var titre = 'Plan du site';
        break;
	}    
    var ileft = $('global').offsetLeft + ($('global').offsetWidth / 2) - w/2;
    var itop = $('global').offsetTop + ($('global').offsetHeight / 2 - h/2);
    openCadre_(titre,url,'',{id:strFooter,left:ileft,top:itop,width:w,height:h});
}


function displayInfo(){
	var url = "info.php" ;
	var ileft = $('global').offsetLeft + ($('global').offsetWidth / 2) - 100;
   var itop = $('global').offsetTop + ($('global').offsetHeight / 2 - 100) ;
	openCadre_('Info',url,'',{id:'info',left:ileft,top:itop,width:200,height:200});
}

function displayopenparcourir(){
	if(document.all)h = 350;
	else h = 340;
	var parurl = "ajaxloadmap.php"
	param ="act=loadmap";
	titre = "Ouvrir un fichier map";
	var url = parurl+'?'+param;
	openCadre_(titre,parurl,param,{id:'openfichdiv',left:310,top:200,width:440,height:h,resizable:false});
}

function verifcheckedchoix(val){
	if(val == 1){
		$('divchoixmap').style.display = 'block';
		$('divchoixdoc').style.display = 'none';
	}else if(val == 0){
		$('divchoixdoc').style.display = 'block';
		$('divchoixmap').style.display = 'none';
	}
}

function showNomParcour(param){
	$('pathCurParcour').value = param ;
}

function parcourRep(param){
	if(param == '')return ;
	$('pathTXT').value = $('pathTXT').value+param+'/' ;
	$('BLaunch').onclick() ;
}

function launchParc(path){
	typeFic = $('typeParc').value ;
	extension = typeFic ;
	if(path == '')return false ;
	paramsend = 'pathSend='+path+'&type='+typeFic+'&extension='+extension;
	var parurl = "ajaxloadmap.php" ;
	new Ajax(parurl, {
		method: 'post',
		postBody: paramsend,
		evalScripts: true
		
	}).request();
}

function parcourUpRep(param){
	$('pathCurParcour').value = '' ;
	if(param == '')return ;
	param = param.replace(/[^\/]{1,}\/{0,1}$/,'') ;
	$('pathTXT').value = param ;
	$('BLaunch').onclick() ;
}

function putValParc(){
	valParc = $('pathCurParcour').value;
	if(valParc == '')return ;
	$('putONParc').value = $('pathTXT').value+valParc ;
	window.parent.closewinpop_('openfichdiv') ;
}

function verifvalideadmincarte(){
	if($('text_resume').value==""){
		alert("Veuillez indiquer le résumé!") ;return ;
	}
	else{
		createMap() ;
	}
}

function supprMaCarte(idProjet){
    if(confirm("Voulez-vous supprimer cette carte?")){
        var parurl = 'listeCarte.php';
        var sRequest = 'act=supprmescartes&idProjet='+idProjet+'&type_acces='+TYPE_ACCES;
        new Ajax(parurl,{
    			method: 'get',
    			postBody: sRequest,
    			evalScripts: true
    		}).request();
    }
}

function fixPNG2_(img) { // correctly handle PNG transparency in Win IE 5.5 or higher.
	if(window.ie) {
		img = $(img);
		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 = "<div " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:"+img.offsetWidth+"px; height:"+img.offsetHeight+"px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></div>" 
			img.outerHTML = strNewHTML
		}			
	} 
}

function countnbrCarte(idDoc,acces){
  
  var parurl = 'nbrcarte.inc.php';
  var sRequest = 'action=refresh&idProjet='+idDoc+'&acces='+acces;
  new Ajax(parurl,{
		method: 'post',
		postBody: sRequest,
		evalScripts: true
	}).request();
	
}

function verifChoiceEcraser(formTag){
	var aInput = formTag.getElementsByTagName("input") ;
	var findChecked = false ;
  for(i = 0; i < aInput.length; i++){
  	if(aInput[i].checked){
  		findChecked = true ;
  		break;
  	}
  }
	if(!findChecked){
		alert('Vous devez choisir une carte à écraser ! ') ;	
	}
	return findChecked ;
}

function startPrint(){
	var reference = "";
	var legende = "";
	var landscape = "";
	var echelle = document.getElementById('echellePrint').value;
	var format = document.getElementById('format').value;
	var urlPrint = document.getElementById('urlPrint').value;
	var minx = $('minx').value;
	var maxx = $('maxx').value;
	var miny = $('miny').value;
	var maxy = $('maxy').value;
	var maxy = $('maxy').value;
	legende = "legende";
	var printHtml = $('html');
	var printWord = $('word');
	//var printExcel = document.getElementById('excel');
	var printPdf = $('pdf');
	if(echelle == ""){
		alert("Choisissez l'echelle d'impression !");
		return false;
	}
	else if(format == ""){
		alert("Choisissez un format de sortie !");
		return false;
	}
	
	if(typeof(referenceByRub) != 'undefined')$('locimages').value = referenceByRub.getImages() ;
	if(typeof(referenceByRub) != 'undefined')$('locextent').value = referenceByRub.getExtent() ;
	
	if(_Photo)_Photo.beforeSubmit('fichePrint');
	else $('fichePrint').submit();
}

function mesCartesAccs(){
	TYPE_ACCES='mes_cartes'	;
}

/* BUTTONS EFFECT */
function btover(oBtn) {
	//$(oBtn).style.color = '#761416';
	$(oBtn).style.backgroundPosition = "0 -"+oBtn.offsetHeight+"px";
}
function btout(oBtn) {
	//$(oBtn).style.color = '#706f27';
	$(oBtn).style.backgroundPosition = "0 0";
}
function refreshVisible(aNotVisible){
    if(aNotVisible.length > 0){
        var oDiv = $('lgdContain');
        if(oDiv){
            var aCheck = oDiv.getElementsByTagName("input");
            if(aCheck.length > 0){
                for(i = 0; i < aCheck.length; i++){
                    var oCheck = aCheck[i];
                    if(oCheck.type == 'checkbox'){
                        if(aNotVisible.arraySearch(oCheck.value)){
                            oCheck.title = "non visible à cette échelle" ;
                            oCheck.alt = "non visible à cette échelle" ;
                            oParent = oCheck.parentNode;
                            if(oParent.tagName == "li"){
                                aSpan = oParent.getElementsByName("span");
                                if(aSpan.length > 0){
                                    for(j = 0; j < aSpan.length; j++){
                                        oSpan = aSpan[j];
                                        if(oSpan.className == "dragbtn"){
                                            oSpan.style.color = "#cccccc";
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
function printFicheHtml(layerindex,iShapeIndex,iTileIndex){
	window.open('printfiche.php?code1='+layerindex+'&code2='+iShapeIndex+'&code3='+iTileIndex);
}
function ajoutPanier(layerindex,iShapeIndex,iTileIndex){
	urlBase = 'ajax.inc.php?act=ajoutPanier&code1='+layerindex+'&code2='+iShapeIndex+'&code3='+iTileIndex ;
	new Ajax(urlBase, {
		method: 'get',
		evalScripts: true
	}).request();
}
function viderPanier(obj){
	urlBase = 'ajax.inc.php?act=viderPanier' ;
	removeCadre(obj);
	new Ajax(urlBase, {
		method: 'get',
		evalScripts: true
	}).request();
}
function printPanier(){
	urlBase = 'panier.php?act=printPanier' ;
	window.open(urlBase);
}

var referenceByRub = {
	refCurent : 0 ,
	imagesListe : ['images/refbelge.gif' , 'images/reffrance.gif'] ,
	extentLiset : ['656537 1292458 701780 1321542' , '656537 1291348 695900 1316652'] ,
	builref : function(){
		if(this.refCurent > this.imagesListe.length)return false ;
		var extentRef = this.extentLiset[this.refCurent].split(' ') ;
  	refMooCarte.minx = extentRef[0] ;
  	refMooCarte.miny = extentRef[1] ;  
  	refMooCarte.maxx = extentRef[2] ; 
  	refMooCarte.maxy = extentRef[3] ;
  	$('imageref').src = this.imagesListe[this.refCurent] ;
	},
	getImages : function (){
		return 	this.imagesListe[this.refCurent] ;
	},
	getExtent : function (){
		return 	this.extentLiset[this.refCurent] ;
	},
	setRefCurent : function (ref){
	  this.refCurent = ref ;
  	$('imageref').src = this.imagesListe[this.refCurent] ;
	}
};

var Lien = {
	generateLien : function(){
		var alistdoc = new Array();
		for(var ill=0; ill < $('selListLien').options.length; ill++) {
			if($('selListLien').options[ill].selected) {
				alistdoc.push($('selListLien').options[ill].value);
			}
		}
		if(alistdoc.length == 0) {
			alert("Séléctionner une élément dans la liste");
		}else if(alistdoc.length == 1){
			openCadreAdm('Génération de lien','admin/lien.inc.php','lien='+alistdoc,{id: 'generatelien', divCenter: 'pnradmcontent',width:500,height:380});
		}else {
			alert("Séléctionner un seul élément dans la liste");
		}
	}
};

function getAide(){
	new Ajax("aide.php",{
		method: 'post',
		postBody: 'getAide=true',
		evalScripts: true
	}).request();
}

function retourtocontent(){
	$("divparlot").style.display = "none" ;
	$("divformassist").style.display = "none" ;
	$("containtrequestdiv").style.display = "block" ;
	$("rtrbottom").style.display = "none" ;
}

function go2modifpage(){
	var orad = $("radioparlot") ;
	if(orad.checked){
		$("divparlot").style.display = "block" ;
		$("divformassist").style.display = "none" ;
		$("containtrequestdiv").style.display = "none" ;
		$("csvparlot").src = "admin/importcsv/index.php?thmTable=commune";
	}
	else {
		$("divformassist").style.display = "block" ;
		$("divparlot").style.display = "none" ;
		$("containtrequestdiv").style.display = "none" ;
		$("iframeAdmin").src = "admin/Fiche_commune/formcom.php";
	}
	$("rtrbottom").style.display = "block";
}

function deleteDessin(){
	if(typeof(_Photo) != 'undefined'){
	    _Photo.removeAll();
	    _Photo.hibernateEvent();
	}
}

var getValueTimer;
function updateDate(el){
	if(getValueTimer)$clear(getValueTimer);
	if(!calendarClick){
		getValueTimer = (function(){
			updateDate(el);
		}).delay(500);
	}else {
		calendarClick = false;
		var dt = el.value.split("/");
		$('datevalsel').value = dt[2]+"-"+dt[1]+"-"+dt[0];
		$('validbutajo').disabled = false;
	}
}

function existMail(mail){
	var content = "<div class='mainContainer'>";
	content += "<div class='label' style='text-align:center'>Ce mail est d&eacute;j&agrave; enregistr&eacute; dans notre liste d'utilisateurs, voulez-vous recevoir un mail r&eacute;capitulant vos identifiants ?</div>";
	content += "<input type='hidden' id='mailInput' value='"+mail+"'>";
	content += "<div class='validate'>";
	content += "<input class='button' type='button' id='ok' value='Ok' onclick='sendConfirmMail(\"mailInput\")'><input type='button' class='button' id='nul' value='Annuler' onmouseover='btover(this)' onmouseout='btout(this)' onclick='removeCadre(this)'></div>";
	content += "</div>";
	openSimpleWin('Mail Existant',content,'',350,150,200,420);
}


function forgetPass(){
	var content = "<div class='mainContainer'>";
	content += "<div class='label'>Inscrivez ci-dessous l'adresse mail sous laquelle vous vous &ecirc;tes pr&eacute;c&eacute;demment enregistr&eacute; </div>";
	content += "<div class='inputMail'><input type='text' id='mailInput'></div>";
	content += "<div class='validate'><input class='button' type='button' id='ok' value='Valider' onmouseover='btover(this)' onmouseout='btout(this)' onclick='sendMail(\"mailInput\")'><input type='button' class='button' id='nul' value='Annuler' onmouseover='btover(this)' onmouseout='btout(this)' onclick='removeCadre(this)'></div>";
	content += "</div>";
	openSimpleWin('Mot de passe perdu',content,'Detail',400,150,140,410);
}

function goOpenSimpleWindow(options,content){
	if(!content)return;
	var _id = options.id ? options.id : "Box";
	var tabOptions;
	if($(_id))tabOptions = $(_id);
	else {
		tabOptions = new Element('div', {
			'styles': {
				'position': 'absolute',
				'font': '11px sans-serif',
				'z-index': (options.zIndex)? options.zIndex : 999,
				'padding': '2px',
				'width': (options.width)? options.width+10 : '300px',
				'top': (options.top)? options.top : '50px',
				'left': (options.left)? options.left: '120px',
				'overflow': 'hidden'
			},
			'id':  _id
		}).inject(document.body);
	}
	
	var box = openBox1(content,(options.title)? options.title : "&nbsp;",_id);
	tabOptions.setHTML(box);
	tabOptions.makeDraggable({handle: $('barreTitle_'+_id)});
	tabOptions.setStyles({
		'display':'block'
	});
	if(options.onComplete)options.onComplete;
}

function openBox1(content,title,param){
	if(!param)param = "Box";
	var box = "<div class='x-window-tc' id='barreTitle_"+param+"'>";
	box += "	<div class='x-window-tl'>";
	box += "		<div class='x-window-tr'>";
	box += "			<div class='x-window-header' style='-moz-user-select: none;'>";
	box += "				<div class='x-tool' onclick='$(\""+param+"\").parentNode.removeChild($(\""+param+"\"))'> </div>";
	box += "				<span class='x-window-header-text'>"+title+"</span>";
	box += "			</div>";
	box += "		</div>";
	box += "	</div>";
	box += "</div>";
	
	box += "<div class='x-window-bwrap'>";
	box += "	<div class='x-window-ml'>";
	box += "		<div class='x-window-mr'>";
	box += "			<div class='x-window-mc'>";
	box += "				<div class='x-window-body'>";
	box += content;
	box += "				</div>";
	box += "			</div>";
	box += "		</div>";
	box += "	</div>";
	box += "	<div class='x-window-bl'>";
	box += "		<div class='x-window-br'>";
	box += "			<div class='x-window-bc'>";
	box += "				<div class='x-window-footer'> </div>";
	box += "			</div>";
	box += "		</div>";
	box += "	</div>";
	box += "</div>";
	return box;
}

function sendMail(mailInput){
	var val = $(mailInput).value;
	if(!checkMail(val))return;
	var url = "mail.php";
	var param = "adresse="+val;
	new Ajax(url, {
		evalScripts: true,
		postBody: param,
  	onComplete: function(originalResponse){
  		confirmation(originalResponse);
  	}
	}).request();
}

function confirmation(reponse){
	var widthFrame = 300 ;
	var heightFrame = 100 ;
	var topFrame = 200 ;
	var leftFrame = 450 ;
	
	switch(reponse){
		case "success": 
			var content = "<div class='mainContainer'>";
			content += "<center><div class='label' style='text-align:center'>Votre mot de passe &agrave; &eacute;t&eacute; envoy&eacute; par mail</div>";
			content += "<div class='validate'><input type='button' id='ok' value='Fermer' onclick='removeCadre(this)'></div></center>";
			content += "</div>";
		break;
		case "fail":
			var content = "<div class='mainContainer'>";
			content += "<div class='label' style='text-align:center'>Echec durant l'envoi du mail, veuillez verifier votre adresse mail</div>";
			content += "<div class='validate'><input type='button' id='ok' value='Fermer' onclick='removeCadre(this)'></div>";
			content += "</div>";
			widthFrame = 345 ;
			leftFrame = 420 ;
		break;
		case "noExist":
			var content = "<div class='mainContainer'>";
			content += "<div class='label' style='text-align:center'>Votre adresse mail n'existe pas dans nos registres</div>";
			content += "<div class='validate'><input type='button' id='ok' value='Fermer' onclick='removeCadre(this)'></div>";
			content += "</div>";
		break;
	}
	openSimpleWin('Mot de passe perdu',content,'Detail',widthFrame,heightFrame,topFrame,leftFrame);
}

function sendConfirmMail(mailInput){
	var val = $(mailInput).value;
	if(!checkMail(val))return;
	var url = "mail.php";
	var param = "resendAdresse="+val;
	new Ajax(url, {
		evalScripts: true,
		postBody: param,
  	onComplete: function(originalResponse){
  		confirmation(originalResponse);
  	}
	}).request();
}

function checkMail(mail){
	//if(!mail)return true ;
	if(mail.length == 0){
     alert("Vous devez renseigner le champ eMail");
     return false;
	}else{
     if (!bSyntaxeEmail(mail)) {
	     alert("Votre mail est incorrect.\nVeuillez le vérifier.");
	     return false;
     }
     if (!bDomainTLD(mail)){
     		alert("Votre mail est incorrect.\nVeuillez vérifier le nom de domaine.");
     		return false;
     }
	}
	return true;
}

function bSyntaxeEmail(sMail){
	var re=/^[a-z\d]+((\.|-|_)[a-z\d]+)*@((?![-\d])[a-z\d-]{0,62}[a-z\d]\.){1,4}[a-z]{2,6}$/gi;
	return (sMail.match(re)==sMail)&&(sMail.substr(sMail.lastIndexOf("@")).length<=256);
}

function bDomainTLD(sMail){
	var re=/^(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|aero|arpa|biz|com|coop|edu|eu|gov|info|int|mil|museum|name|net|org|pro|jobs|travel)$/gi;
	return sMail.substr(sMail.lastIndexOf(".") + 1).match(re)!=null;
}

function refreshlegcouche(){
	var param = "act=refreshlegcouche";
	gMap.sendX_Load(param);
}

function verifSubmitLienAndSend(){
	if($('lien_description_val').value == ''){
		alert('Vous devez remplir le champ description ! ') ;
		return false ;	
	}
	$('formModifDoc').send({evalScripts:true});
	return true ;
}

function reloadLegendeInControl(scale, visibleStatus){
	  $("ulctrlCouche").innerHTML = 'Chargement ...' ;
		var sRequest = "scale="+scale ;
    new Ajax("ajax.legende.php",{
			method: 'post',
			postBody: sRequest,
			evalScripts: false,
			onComplete : function(response){
				showDiv("pnrtheme", "block");
				$("ulctrlCouche").innerHTML = response ;
				activerNested();
				ctrlClick("pnrtheme");
				navCurrent("ctrl",2,3);
				makeslider();
				checkVisibilityLayer(visibleStatus);
			}
   }).request();
}

/*********************ajout du 09 juin 2009****************************/
var timerglobaldisp;
function displayinformplus(resume,nomdoc,e){
		if (!e) var e = window.event;
		if (e.pageX || e.pageY){
			var xev = e.pageX;
			var yev = e.pageY;
		}else if (e.clientX || e.clientY){
			var xev = e.clientX  + document.body.scrollLeft ;
			var yev = e.clientY + document.body.scrollTop;
		}
	 timerglobaldisp = setTimeout(function(){
		$('divaffinfo').style.display = "block";
		$('divaffinfo').style.top = yev + 13+"px";
		$('divaffinfo').style.left = xev + 3 - $('global').offsetLeft+"px";
		// if(nomdoc != '')$('divaffinfo').innerHTML = "<b>Résumé :  </b>"+resume+"<br /><b>Nom du fichier :  </b>"+nomdoc;
		if(nomdoc != '')$('divaffinfo').innerHTML = "<b>Nom du fichier :  </b>"+nomdoc;
		else $('divaffinfo').innerHTML = "<b>Résumé :  </b>"+resume+"<br />";
	 }, 1000);
}

function hideinformplus(){
	clearTimeout(timerglobaldisp);
	$('divaffinfo').innerHTML = " ";
	$('divaffinfo').style.display = "none";
}

/**********************fin ajout**************************************/