/*************************************** VARIABLES GLOBALES *******************************************************/
// Messages/Errors DivID
var msgBarID = "MessageBar";
// Classes Info/Error pour Message Bar
var infoBarClass = "InfoBar";
var errorBarClass = "ErrorBar";
// Flags réponse Ajax
var ajaxErrorFlag = "X";
var ajaxUrlFlag = "/";
var ajaxResultRegEx = /^(\[(X|\/)\])?(.+)/;
var loadingDefaultID = "AjaxLoadingLayer";
var ajaxLoadingStateID = "AjaxStatus";

// Main Page DivID
var pageTplID = "HackIE";
// Flash Player DivID
var flashPlayerID = "JWFlashPlayer";
// Démo save Title
var demoPageTitle = document.title;
// Gallery DivID
var galleryID = "PhotoGallery";
// PopUp DivID
var popupBaseID = "PopUp-";
var JTpopupID = 1;
var interviewPopupID = 3;




/************************************** FONCTIONS GENERIQUES ******************************************************/
// getElementByID
function getElt (id)
{	return document.getElementById(id);	};

// Masquage d'un élément
//function hide (id)
//{	getElt(id).style.display = "none"; return;	}

// Affichage d'un élément masqué
//function show (id)
//{	getElt(id).style.display = "block"; return;	}

// Show / Hide (inverse)
function swapDisplay (id)
{
	var elt = getElt(id);
	if (elt)
		elt.style.display = (elt.style.display == 'block') ? 'none' : 'block';
};

// Ouverture d'un lien dans une nouvelle page / un nouvel onglet
function newTab (link)
{	window.open(link.href); return false;	};

function isArray (array)
{	return (typeof array == "object" && array.constructor.toString().indexOf("Array") != -1);	};

// Function de gestion des accents Ajax (UTF-8)
//function toAjaxStr (str)
//{	return str.replace(/é/g, "\u00e9").replace(/è/g, "\u00e8");	}
//function toAjaxStr (str)
//{	return str.replace(new RegExp("é","g"), "\u00e9").replace(new RegExp("è","g"), "\u00e8");	}

// Récupération de la résolution (pour champs login et info encadré)
function getScreen()
{
	var us, sw, sh;
	if (us = getElt("UserScreen"))
		us.innerHTML = screen.width + "x" + screen.height;

	if (sw = getElt("ScreenWidth"))
		sw.value = screen.width;
	if (sh = getElt("ScreenHeight"))
		sh.value = screen.height;
};

// Récupération de la largeur de l'écran selon navigateur
function getBodyWidth ()
{
	var width = 800;
	if (window.innerWidth)
		width = window.innerWidth;
	else if (document.documentElement.clientWidth)
		width = document.documentElement.clientWidth;
	else if (document.documentElement.offsetWidth)
		width = document.documentElement.offsetWidth;
	return width;
};

// Récupération de la hauteur de l'écran selon navigateur
function getBodyHeight ()
{
	var height = 600;
	if (window.innerHeight)
		height = window.innerHeight;
	else if (document.documentElement.clientHeight)
		height = document.documentElement.clientHeight;
	else if (document.documentElement.offsetHeight)
		height = document.documentElement.offsetHeight;
	return height;
};

// Redimensionnement du cadre principal selon hauteur de l'écran
function setBodyHeight ()
{
	if (getElt(pageTplID))
	{
		var height = getBodyHeight() - 102 - 30;	/* body - header - footer - margin footer (?) */
		height = Math.max(height, document.body.offsetHeight);
		getElt(pageTplID).style.height = height + "px";
	}
};

function maximize (id, link, back)
{
	var elt, dom = $(link.domID), label = dom.innerHTML;
	if (back == undefined)
		back = false;
	if (elt = $(id))
	{
		dom.update(link.label);
		link.label = label;
		if (back)
		{
			elt.relativize();
			elt.setStyle({top:0,left:0,width:"100%",height:"auto",backgroundColor:"transparent",zIndex:10});
			$$("Col.ColHidden").each(function(elt){elt.setStyle({display:"none"});});
			dom.onclick = function () { maximize(id, link); };
		}
		else
		{
			elt.absolutize();
			var h = (document.viewport.getHeight() - 102 - 30) + "px";
			elt.setStyle({top:"102px",left:0,width:"100%",height:h,backgroundColor:"white",zIndex:150,overflow:"auto"});
			$$("Col.ColHidden").each(function(elt){elt.setStyle({display:"block"});});
			dom.onclick = function () { minimize(id, link); };
		}
	}
}

function minimize (id, link)
{	maximize(id, link, true);	}


// TEMP HACK BODY HEIGHT >> qd AJAX + JAVASCRIPT modifient le bodyHeight
//function updateBodyHeight (x)
//{	getElt('HackIE').style.height = (parseInt(getElt('HackIE').style.height) + x) + "px";	}

// Initialisation (Body + Screen)
function init ()
{
//	setBodyHeight();
//	if (getElt("JSTests"))
//	{
//		getElt("JSTests").innerHTML =
//			"navName : "+user.navName+"<br/>"+
//			"navVersion : "+user.navVersion+"<br/>"+
//			"navLang : "+user.navLang+"<br/>"+
//			"UserAgent : "+user.userAgent+"<br/>"+
//			"regex : "+(user.isIE()?"yes":"no")+"<br/>";
//	}
//	alert(arguments.length);
//	var output = "";
//	for (var i=0 ; i < arguments.length ; i++)
//		output += arguments[i] + "\n";
//	if (output.length > 0)
//		alert(output);
//	getScreen();
};

// Type de class pour Message / Error
function setMessageBarClass (error)
{
	var msgDiv;
	if (msgDiv = getElt(msgBarID))
		if (Prototype.Browser.IE)
			msgDiv.className = error ? errorBarClass : infoBarClass
		else
			msgDiv.setAttribute("class", error ? errorBarClass : infoBarClass);
};

// Analyse en-tête du message. Sépare type du message (type => message | erreur | URL) (Ajax ou recup session PHP).
function checkMessageType (msg)
{
	var res = new Object();
	var m = ajaxResultRegEx.exec(msg);
	res.type = m[2];
	res.msg = m[3];
	return res;
};

// Cross-browser HTML Table
function createTable (table)
{	return user.isIE() ? createIETable(table) : createDomTable(table);	};

function setTable (table)
{	return createIETable(table);	};

// Création d'une "Table HTML via DOM" (div.Table div.Tr...) à partir d'un array JS
function createDomTable (table)
{
	var domTable = document.createElement("div");
	if (isArray(table))
	{
		domTable.setAttribute("class", "Table");
		table.each( function(line)
		{
			// Création de la ligne
			domTable.appendChild(document.createElement("div"));
			domTable.lastChild.setAttribute("class", "Tr");
			if (isArray(line))
			{
				line.each( function(item)
				{
					domTable.lastChild.appendChild(document.createElement("div"));
					domTable.lastChild.lastChild.setAttribute("class", "Td");
					if (typeof item == "object" && item.nodeType)
						domTable.lastChild.lastChild.appendChild(item);
					else
						domTable.lastChild.lastChild.appendChild(document.createTextNode(item));
				});
			}
			else
			{
				domTable.lastChild.appendChild(document.createElement("div"));
				domTable.lastChild.lastChild.setAttribute("class", "Td");
				if (typeof line == "object" && line.nodeType)
					domTable.lastChild.lastChild.appendChild(line);
				else
					domTable.lastChild.lastChild.appendChild(document.createTextNode(line));
			}
		});
	}
	else
		domTable.appendChild(document.createTextNode("Erreur, impossible de construire le tableau"));

	return domTable;
};

// Création d'un Table HTML (Hack IE) à partir d'un tab JS
function createIETable (table)
{
	var domTable = "";
	if (isArray(table))
	{
		// Hack IE - Gestion DOM (création Table)
		domTable += "<table>";

		table.each(function(line)
		{
			// Création de la ligne
			domTable += "<tr>";
			if (isArray(line))
			{
				line.each( function(item)
				{
					domTable += "<td>";
					if (typeof item == "object" && item.nodeType)
						domTable += item.innerHTML;
					else
						domTable += item;
					domTable += "</td>";
				});
			}
			else
			{
				domTable += "<td>";
				if (typeof line == "object" && line.nodeType)
					domTable += line.innerHTML;
				else
					domTable += line;
				domTable += "</td>";
			}
			domTable += "</tr>";
		});

		domTable += "</table>";
	}
	else
		domTable = "Erreur, impossible de construire le tableau";

	return domTable;
};


function isNotEmptyString (str)
{	return /[^\s]/.test(str);	};


function ajaxLoading (wait, ajaxStatus, lang)
{
	var loadStatus = new Object();
	loadStatus.states = new Object();
	loadStatus.states.fr = "Veuillez patienter";//["Connexion...", "Envoi des informations", "Attente de la réponse"];
	loadStatus.states.en = "Please Wait";//["Connecting...", "Sending informations", "Waiting for response"];
	// Arrêt du chargement
	if (ajaxStatus === null)
	{
		if (wait && wait.id == loadingDefaultID)
			wait.remove();
		else
			wait.update("");
	}
	// Création du Div d'attente
	else if (!(loadStatus.dom = $(ajaxLoadingStateID)))
		wait.update("<div class=\"Loading\">" +
						"<img src=\"/images/ajaxLoading.gif\" /> " +
						"<span id=\""+ajaxLoadingStateID+"\">" + loadStatus.states[lang] + "</span>" +
					"</div>").show();
	else	// Mise à jour du texte (connexion, envoi infos, attente réponse....)
		loadStatus.dom.update(loadStatus.states[lang]);
};


// DEBUG
function showDebug (settings)
{
	return confirm("Ajax Vars :\n"
						+ "Vars : " + $A($H(settings.params.toQueryParams())).inspect() + "\n"
						+ "Script PHP : " + settings.url + "\n"
						+ "Parser JS : " + settings.parser + "\n"
						+ "ResultTag : " + settings.dom + "\n"
						+ "ErrorTag : " + msgBarID + "\n"
						+ "\nExécuter la requête ?");
};

function setUpload (elt, key) {
	var html =
		'<tr id="UPW_Form_Line_'+key+'">' +
			'<td colspan="100">' +
				'<form action="/admin/ajax/sendUPW.php5" class="Upload_UPW" method="post" ' +
						'enctype="multipart/form-data" target="iFrame_'+key+'">' +
					'<input type="file" id="UPW_File_'+key+'" name="upw" onchange="sendUPW(this, \''+key+'\');" style="height:25px;" />' +
					'<input type="submit" value="submit" style="display:none;"/>' +
					'<input type="hidden" name="key" value="'+key+'" />' +
				'</form>' +
			'</td>' +
		'</tr>';
	$(elt).up().insert({after:html});
}
function uploadResult (key, msg) {
	
	if (msg.length > 0)
		alert(msg);
	else
		alert(key);
	// getClientInfos(update.uid);
	// setTimeout(function(){selectTab('ClientDetails_'+update.uid, 'AccountBox_'+update.uid);}, 1000);
};

function initAjaxRequest (settings)
{
	// Langue du message d'attente
	var lang = "fr";//$("CurrentFlag");

	// Identifiant de l'élément résultat => MessageBar sinon
	var dom = $(settings.dom !== undefined ? settings.dom : msgBarID);
	// Nom du parser si résultat/données attendu(es)
	var parser = settings.parser !== undefined ? settings.parser : null;

	// Debug éventuel
	if (settings.debug === undefined || showDebug(settings))
	{
		// Méthode (GET / POST)
		var method = settings.method !== undefined ? settings.method : "post";
		// Paramètres supplémentaires éventuels
		var params = settings.params !== undefined ? settings.params : "";
		// Elément pour l'image d'attente (loading)
		var wait;
		if (settings.wait === undefined)
		{
			document.body.appendChild(document.createElement("div"));
			document.body.lastChild.setAttribute("id", loadingDefaultID);
			wait = $(loadingDefaultID);
		}
		else if (!(wait = $(settings.wait)))
			wait = $(loadingDefaultID);

		if (dom)
			while (dom.hasChildNodes())
				dom.removeChild(dom.firstChild);

		if (settings.url !== undefined && settings.url.length > 0)
		{
			new Ajax.Request (	settings.url,
								{	method: method,	parameters: params,
									requestHeaders: {Accept: "application/json"},
									onCreate :	function (transport) { ajaxLoading(wait, transport.readyState, lang); },
//									onLoading :	function (transport) { ajaxLoading(wait, transport.readyState, lang); },
//									onLoaded :	function (transport) { ajaxLoading(wait, transport.readyState, lang); },
									onInteractive :	function (transport) {
																	if (settings.sync !== undefined && settings.sync)
																	{
																		var res = checkMessageType(transport.responseText);
																		if (res.type === undefined || res.type.length == 0 || res.type == ajaxErrorFlag)
																		{
																			//ajaxLoading(wait, null, lang);
																			dom.innerHTML = res.msg;
																			// A priori jamais différent
																			if (dom.id == msgBarID)
																				setMessageBarClass(res.type == ajaxErrorFlag);
																				dom.show();
																		}
																		else if (res.type == ajaxUrlFlag)
																			document.location.href = res.msg;
																	}
															},
									onSuccess :	function (transport)
												{
													if (parser === null)
													{
														var res = checkMessageType(transport.responseText);
														if (res.type === undefined || res.type.length == 0 || res.type == ajaxErrorFlag)
														{
															ajaxLoading(wait, null, lang);
															dom.innerHTML = res.msg;
															// A priori jamais différent
															if (dom.id == msgBarID)
																setMessageBarClass(res.type == ajaxErrorFlag);
															if (Prototype.Browser.IE)
																dom.style.display='block';
															else
																dom.show();
														}
														else if (res.type == ajaxUrlFlag)
															document.location.href = res.msg;
													}
													else
													{
														ajaxLoading(wait, null, lang);
														var jp = new JsonParsers();
														if (jp[parser] !== undefined)
														{
															var jsonRes = transport.responseText.isJSON()
																				? transport.responseText.evalJSON(true)
																				: transport.responseText.toJSON().evalJSON(true)
															jp[parser](dom, jsonRes);
														}
													}
												},
									onFailure : function () { ajaxLoading(wait, null, lang); alert("Ajax Error"); }
								}
			);
		}
	}
	return false;
};



function print_r (array, nb)
{
	nb = nb ? nb : 0;
	var nbsp = "";

	var str = "";
	for (var sp=0 ; sp<nb ; sp++)
		nbsp += "\t";
	for (var i in array)
		if (isArray(array[i]))
			str += nbsp + i + "\t=>\n" + print_r(array[i], nb+1);
		else// if (typeof array[i] != "function")
			str += nbsp + i + "\t=>\t"+array[i]+"\n";
	return str;
};


// IE Object Fix (vire le cadre, les marges, etc...) => Bug IE
function fixObject (id)
{
	var elt;
	if (elt = getElt(id))
	{
		elt.body.style.border = "none";
		elt.body.style.margin = "0 auto";
		elt.body.style.padding = 0;
		elt.body.style.overflow = "hidden";
		elt.body.style.backgroundColor = "transparent";
//		elt.focus();
	}
};


/*****************************************************************************************************************/



/************************************ FONCTIONS MEASURIX **********************************************************/
// Affichage d'un Popup
function displayPopup (id)
{
	var popup = $(popupBaseID+id);
	popup.setStyle({	marginTop : (-popup.getHeight()/2) + "px",
						marginLeft : (-popup.getWidth()/2) + "px"	});
	popup.show();
}

// Gestion de l'affichage des infobulles (fichier ToolTip.js)
function toolTip (tag, tooltipID)
{
	if (showToolTip)
	{
		tag.onmouseout = function () { hideToolTip("ToolTip_"+tooltipID); };
		showToolTip("ToolTip_"+tooltipID);
	}
}

//Insert le lecteur Flash dans Div tagID
function createFlashPlayer (file, width, height, domID)
{
	var player = domID === undefined ? $(flashPlayerID) : $(domID);
	height = height === undefined ? 240 : height;
	if (player)
	{
		player.innerHTML = "";
		flashPlayer =	{	url: "http://www.measurix.com/videos/flvplayer.swf", width: width, height:	height	}
		
		var flashVars = "displayheight=" + flashPlayer.height + "&file=http://www.measurix.com/videos/" + file +
						"&overstretch=true&width=" + flashPlayer.width + "&height=" + flashPlayer.height +
						"&showdigits=false&showicons=false&showvolume=false&autostart=true&repeat=list&shuffle=false";
		if (user.isIE())
			player.innerHTML = 
				"<embed src=\"" + flashPlayer.url + "\" type=\"application/x-shockwave-flash\" width=\"" + flashPlayer.width + "\" height=\"" + flashPlayer.height + "\"" +
					" allowfullscreen=\"false\" allowscriptaccess=\"always\" flashvars=\"" + flashVars + "\" />";
		else
		{
			player.appendChild(document.createElement("object"));
			// Paramètre de l'Object
			player.firstChild.setAttribute("type", "application/x-shockwave-flash");
			player.firstChild.setAttribute("data", flashPlayer.url);
			player.firstChild.setAttribute("width", width);
			player.firstChild.setAttribute("height", height);
			player.firstChild.setAttribute("allowfullscreen", "false");
			player.firstChild.setAttribute("allowscriptaccess", "always");
			// Param => Player Flash
			player.firstChild.appendChild(document.createElement("param"));
			player.firstChild.lastChild.setAttribute("name", "movie");
			player.firstChild.lastChild.setAttribute("value", flashPlayer.url);
			// Param => Flash Vars
			player.firstChild.appendChild(document.createElement("param"));
			player.firstChild.lastChild.setAttribute("name", "flashvars");
			player.firstChild.lastChild.setAttribute("value", flashVars);
		}
		player.show();
	}
	// Débug Demo !!! marche pas sur IE6
	if ($("InfosBox") && $("InfosBox").select("a[href='/login.php5?killsys']").first().innerHTML == "217.128.123.113")	alert(file);
};

// Lancement JT dans Popup
function watchJT ()
{
	createFlashPlayer("jtfrance2.flv", 320, 240, "PopUpContent-"+JTpopupID);
	displayPopup(JTpopupID);
};

// Lancement JT dans Popup
function interview ()
{
	createFlashPlayer("interview.flv", 400, 300, "PopUpContent-"+interviewPopupID);
	displayPopup(interviewPopupID);
};

function playDemo (idv, w)
{
	var next_idv = idv + 1 + (idv==7 ? 1 : 0)					// ID de la prochaine vidéo
	var str_idv = idv < 10 ? "0"+idv : idv;						// ID de la vidéo formaté sur deux chiffres
	var title = $("VideoTitle");								// Elt Titre de la démo
	var video = $("Video"+str_idv);								// Lien de la vidéo
	var next = $("NextVideo");									// Lien vers la prochaine vidéo
	var pocketRightImg = $("RightImg");							// Img de droite selon video
	var is180 = function (id) { return (id == 2 || id == 7 || id == 10); }
	var getVideoWidth = function (id) { return is180(id) ? 180 : 324; }
//if (mx) alert("");
	if (pocketRightImg)
		pocketRightImg.innerHTML = is180(idv) ? "<img src=\"/images/demos/tripod.jpg\" alt=\"\" />" : "";
	if (title && video)
	{
		document.title = demoPageTitle + " - " + video.innerHTML;//video.firstChild.nodeValue
		title.innerHTML = video.innerHTML;

//		title.replaceData(0, title.firstChild.nodeValue.length, video.firstChild.nodeValue);
		if (idv+1 > 10)
			next.hide();
		else
			next.show().setAttribute("onclick", "playDemo("+next_idv+", "+getVideoWidth(next_idv)+");");
//if (user.isIE6())
//	alert("Démo temporairement indisponible");
		var str_video;
		if (idv == 7)
			str_video = "demo.xml";
		else
			str_video = "tripod"+str_idv+".flv";
		createFlashPlayer(str_video, w);
	}
	$("DemoVideos").show();
};

// Affiche le champ de saisie du nouveau mail pour activation
function setNewActivationMail ()
{
	var newMailDiv = $("NewActivationMail");
	if (newMailDiv)
	{
		if ($("setnewmail").checked)
			newMailDiv.show();
		else
			newMailDiv.hide();
	}
};

/***************************************************************************************************************/

