/**
 * Cette partie recentre tous les élements de la page.
 * */
var getWindowWidth = function () {
	if (window.innerWidth)
		return window.innerWidth;
	return document.documentElement.clientWidth;
};

var getOffset = function() {
	/*BROWSER DEPENDANT*/
	var winW = 0;
	if (winW = window.innerWidth) {
		winW = window.innerWidth;
		winW = ((winW - 1050) / 2);
	}
	else {
		winW = document.documentElement.clientWidth;
		winW = (winW - 1050);
	}
	if (winW < 0)
		winW = 0;
	
	curOffset = function () {
		return winW;
	};
};

var curOffset = function () {
	return 0;
};

var marginLeft = function (obj) {
	if (obj == null || obj.style == null || (obj.tagName != 'DIV' && obj.tagName != 'FORM'))
		return false;
	
	var left = obj.style.left;
	var index = (left + "").indexOf("px"); 
	if (index != -1)
		left = new Number(left.substring(0, index));

	obj.style.marginLeft = left + curOffset() + "px";
	
	return true;
};


var getParent = function (obj) {
	var father;
	if (obj.parentElement)
		father = obj.parentElement;
	else 
		father = obj.parentNode;
	return father;
};

var reposi = function (obj) {
	if (obj == null || obj.style == null ||  (obj.tagName != 'DIV' && obj.tagName != 'FORM'))
		return false;
	
	var tab = recurs(getParent(obj));
	
	obj.style.marginTop = (0 - tab[0]) + "px";
	obj.style.marginLeft = (0 - tab[1] + curOffset()) + "px";
	
	if (obj.id=="titre_titre"){
		obj.style.marginLeft =  (0 - tab[1]) + "px";
		var width =  (parseInt(getWindowWidth()) - 17);
		obj.style.width = width + "px";
	}
	
	return true;
};

var recurs = function (obj) {
	if (obj == null)// || obj.style == null || (obj.tagName != 'DIV' && obj.tagName != 'FORM') || obj.id == 'titre_titre')
		return [0, 0];
	
	var top = obj.offsetTop;
	var left = obj.offsetLeft;
	
	if (top == null && left == null)
		return [0, 0];
	if (top == null || left == null)
		alert("pb!!");
	
	var tab = recurs(getParent(obj));
	
	return [top + tab[0], left + tab[1]]; 
};

var repositionneFixed = function () {
	getOffset();
	iter(getObjConcerne(), reposi, new Array());
};

/** FIN DE LA PARTIE REPOSITIONNANTE */

var getObjConcerne = function () {
	return document.getElementById('general').children;
};

var iter = function (elts, fct, res) {
	if (elts == null)
		return res;
	for (var i = 0; i < elts.length; i++){
		if (fct(elts[i])){
			if (!(res instanceof Array))
				alert("res null " + res);
			res.push(elts[i]);
			res = iter(elts[i].children, fct, res);
		}
	}
	return res;
};

var ajouterEvt = function (obj, type, fct, bool) {
	if (obj.addEventListener)
		obj.addEventListener(type,fct,bool);
	else
		obj.attachEvent('on' + type, fct);
};

var getOnglet = function() {
	return [
	        {ident:"menu_accueil", fichier:"accueil"},
	        {ident:"menu_annuaire_agences", fichier:"annuaire_agences"},
        	{ident:"menu_depot_annonce", fichier:"depot_annonce"},
        	{ident:"menu_alerte", fichier:"alerte_mail_sms"},
    		{ident:"menu_groupe", fichier:"groupe"},
	];
};

var majActivated = function () {
	var menu = getOnglet();
	
	var tabTmp = (document.location + "").split("/");
	var cur = tabTmp[tabTmp.length - 1];
	var allInactif = true;
	
	for (var i = 0; i < menu.length; i++){
		if (menu[i] == null)
			continue;
		setOngletInactif(menu[i].ident);
		if (cur.indexOf(menu[i].fichier) >= 0){
			setOngletActif(menu[i].ident);
			allInactif = false;
		}
	}
	
	// Petite gruge pour rattraper le coup lorsque l'on arrive sur l'accueil d'une agence
	if (allInactif){
		var loc = window.location + "";
		var str = makeValidURL(loc);
		if (loc != str)
			window.location = str;
	}
};

var setOngletInactif = function (name) {
	document.getElementById("img_" + name).className = "menu_inactif";
	document.getElementById("font_" + name).className = "menu_police";
};

var setOngletActif = function (name) {
	document.getElementById("img_" + name).className = "menu_actif";
	document.getElementById("font_" + name).className = "menu_police_actif";
};

var mouseOnMenu = function (name) {
	setOngletActif(name);
};

var mouseOutMenu = function (name) {
	majActivated();
};

var mouseOnBien = function (bien) {
	var mem = bien.className;
	bien.className = "bien_actif";
	if (!bien.onmouseout) {
		bien.onmouseout = function () {
			bien.className = mem;
			bien.onmouseout = null;
		};
	}
};

//ATTENTION ATTENTION: Parce qu'IE6 c'est pas qu'une grosse M****, la fonction getElementById est buggée
// redéfinition :
if (/msie/i.test (navigator.userAgent)) {
	document.nativeGetElementById = document.getElementById;
	document.getElementById = function(id) {
		// Get element using native method
		var elem = document.nativeGetElementById(id);
		if (elem) {
			// If id match, return element
			if (elem.attributes['id'].value == id) {
				return elem;
			}
			// Otherwise look for the right one
			else {
				for (var i = 1; i < document.all[id].length; i++) {
					if (document.all[id][i].attributes['id'].value == id) {
						return document.all[id][i];
					}
				}
			}
		}
		return null;
    };
}

var makeValidURL = function (str) {
	if (str == null || str == "")
		return "";
	
	var withHttp = str.indexOf("http://") >= 0;
	str = str.replace("http://", "");
	
	var idxLastSlash = str.lastIndexOf("/");
	var lastPart = str.substring(idxLastSlash + 1);
	if (lastPart.indexOf(".php") < 0){
		lastPart = "accueil.php" + lastPart;
		str = str.substring(0, idxLastSlash + 1) + lastPart;
	}
	
	str = (withHttp ? "http://" : "") + 
	((str.replace(new RegExp("(///)", "g"), "/"))
			.replace(new RegExp("(//)", "g"), "/"));

	return str;
};

// Dans le cas des agences, certaines variables CSS définies pour la présentation sont à overrider
var inclusAgentCSS = function () {
	
	var agce_id_agce = document.getElementById("agce_id_agce").value;
	var tagc_code = document.getElementById("tagc_code").value;
	
	var isAgent = agce_id_agce != null && agce_id_agce != "";
	var isPortail = !isAgent && tagc_code != null && tagc_code != "";
	var isIdimmo = false;

	var fichier = "/css/portail.css";
	if (tagc_code == "EMD")
		fichier = isPortail ? "/css/portailEmd.css" : "/css/emdstyle.css";
	else if (tagc_code == "IDIMMO"){
		fichier = isPortail ? "/css/portailIdimmo.css" : "/css/idimmostyle.css";
		isIdimmo = true;
	}
	else if (tagc_code == "LETUC")
		fichier = isPortail ? "/css/portailLetuc.css" : "/css/letucstyle.css";
	
	majColDroite(isAgent, isPortail);
	
	majPrevisite();
	
	document.getElementById("href_accueil").href = "/accueil.php";
	document.getElementById("href_annuaire").href = "/annuaire_agences.php";
	document.getElementById("href_depot").href = "/depot_annonce.php";
	document.getElementById("href_alerte").href = "/alerte_mail_sms.php";

	var hrefRetourAccueil = document.getElementById("href_retour_accueil");
	if (hrefRetourAccueil != null)
		hrefRetourAccueil.href = "/accueil.php";
	
	hrefRetourAccueil = document.getElementsByName("href_retour_accueil");
	if (hrefRetourAccueil != null) {
		for (var i = 0; i < hrefRetourAccueil.length; i++)
			hrefRetourAccueil[i].href = "/accueil.php";
	}
	
	var bttAgce = document.getElementById("bas_recrute_bouton_agence");
	var bttEmpl = document.getElementById("bas_recrute_bouton_emploi");
	if (bttAgce != null) {
		if (isIdimmo)
			bttAgce.onclick = function () {window.location = "/devenir_vdi.php"; };
		else
			bttAgce.onclick = function () {window.location = "/creez_votre_agence.php"; };
	}
	if (bttEmpl != null) {
		if (isIdimmo)
			bttEmpl.onclick = function () {window.location = "/offre_emploi_idimmo.php"; };
		else
			bttEmpl.onclick = function () {window.location = "/offre_emploi.php"; };
	}
	
	var bttSendMsgToAgent = document.getElementById('send_msg_agent');
	if (bttAgce != null && bttSendMsgToAgent != null)
		bttSendMsgToAgent.onclick = function () {window.location = "/alerte_mail_sms.php"; };
	
	if (isPortail) {
		var bttVendre = document.getElementById("corps_accueil_col_droite_vendre");
		if (bttVendre != null) {
			bttVendre.onclick =
				function () {
					window.location = "/depot_annonce.php";
				};
		}
		var bttAchat = document.getElementById("corps_accueil_col_droite_achat");
		if (bttAchat != null) {
			bttAchat.onclick = 
				function () {
					window.location = "/alerte_mail_sms.php";
				};
		}
	}
		
	var css_style = document.createElement("link");
	css_style.setAttribute("rel", "stylesheet");
    css_style.setAttribute("type", "text/css");
    css_style.setAttribute("href", fichier);
    css_style.setAttribute("media", "screen");
    document.getElementsByTagName("head")[0].appendChild(css_style);

    var isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") != -1;
    var isSafari = navigator.userAgent.toLowerCase().indexOf("safari") != -1;
    if (isChrome || isSafari){
    	css_style = document.createElement("link");
		css_style.setAttribute("rel", "stylesheet");
	    css_style.setAttribute("type", "text/css");
	    css_style.setAttribute("href", "/css/chromeSafari.css");
	    css_style.setAttribute("media", "screen");
	    document.getElementsByTagName("head")[0].appendChild(css_style);
    }
};

// Dans le cas des agents, sur la page d'accueil la colonne de droite est differente.
var majColDroite = function(isAgent, isPortail) {
	var colDroitePortail = document.getElementById("colonne_droite_portail");
	var colDroiteAgent = document.getElementById("colonne_droite_agent");
	var recrutement = document.getElementById("recrutement");
	var basPub = document.getElementById("bas_pub");
	var corpsSite = document.getElementById("corps_site");
	
	var carte = document.getElementById("img_carte_fr");
	var lienCarte = document.getElementById("lien_carte_fr");
	var codePostal = document.getElementById("code_postal_loc");
	
	var titreAgent = document.getElementById("titre_agent");
	
	if (colDroitePortail != null && colDroiteAgent != null){
		colDroiteAgent.style.display = isAgent ? "" : "none";
		colDroitePortail.style.display = isAgent ? "none" : "";
		recrutement.style.display = isAgent ? "none" : "";
		basPub.style.display = isAgent ? "" : "";
	}
	
	var ongletAnnuaire = document.getElementById("onglet_annuaire");
	if (ongletAnnuaire != null){
		ongletAnnuaire.style.display = isAgent ? "none" : "";
	}
	
	if (isAgent && carte != null && lienCarte != null) {
		carte.innerHTML = "";
		lienCarte.innerHTML = "";
		lienCarte.innerHTML = "";
		lienCarte.onclick = function() {};
		codePostal.size = 36;
	}
	
	if (titreAgent != null) {
		titreAgent.style.display = isAgent ? "" : "none";
	}
	
	var googleMap = document.getElementById("cadre_google_map");
	if (googleMap != null){
		googleMap.style.display = "none";
	}
	
	// Icônes des réseaux sociaux : uniquement pour les sites portails
	var tabIcones = document.getElementById('icones_reseaux_sociaux');
	// Donc, si les icones sont sur la page est que l'on est pas sur un portail => on masque.
	if (tabIcones != null && isAgent){
		tabIcones.style.display = "none";
	}
};

var majPrevisite = function() {
	var divPrevisite = document.getElementById("div_previsite");
	if (divPrevisite == null)
		return;
	
	var hauteur = divPrevisite.offsetHeight;
	
	if (hauteur <= 100)
		return;
	
	// Si la hauteur n'est pas zéro, c'est que le lien vers prévisite existe
	// On masque le système d'image mis en place originellement
	var grdPhotos = document.getElementById("grandePhoto");
	if (grdPhotos != null)
		grdPhotos.style.display = "none";
	var cptPhoto = document.getElementById("cptPhoto");
	if (cptPhoto != null)
		cptPhoto.style.display = "none";
	var vignettes = document.getElementById("vignettes");
	if (vignettes != null)
		vignettes.style.display = "none";
};

