// JavaScript Document

function MM_findObj(n, d) { //v4.01
  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_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  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_swapImage() { //v3.0
  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) { //v2.0
  window.open(theURL,winName,features);
}

function VS_changeImgSrc() { //v1.0
 var args=VS_changeImgSrc.arguments;
 if ((img = MM_findObj(args[0])) != null && !img.VS_init) {
   img.VS_init = true;
   if (args[2] == args[0]) {
     img.src = args[1];
   }
 }
}

function VS_showHideLayers() { //v6.0
	var i,p,v,obj,args=VS_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'':(v=='hide')?'none':v; }
    obj.display=v; }
}

// Soumission de formulaire
function VS_submitForm(frmName_P)
{
	if(document.forms[frmName_P]) document.forms[frmName_P].submit();
}

// Application d'une opération sur le panier
function VS_operationPanier(form_P,
														frmOperation_P,
														operation_P,
														frmRefProduit_P,
														refProduit_P,
														frmFormat_P,
														format_P)
{
	document.forms[form_P].elements[frmOperation_P].value = operation_P;
	if((frmRefProduit_P != null) && (refProduit_P != null)) document.forms[form_P].elements[frmRefProduit_P].value = refProduit_P;
	if((frmFormat_P != null) && (format_P != null)) document.forms[form_P].elements[frmFormat_P].value = format_P;
	VS_submitForm(form_P);		
}

function VS_loadPage() { //v1.0
	if(typeof(VS_boolInitPage) != "undefined") VS_initPage();
}

// Instanciation et récupration de l'objet XmlHttpRequest
function VS_getXHR()
{
    var objXHR = null;
    if(window.XMLHttpRequest) objXHR = new XMLHttpRequest();
		else if(window.ActiveXObject)
		{
        try
				{
            objXHR = new ActiveXObject('Msxml2.XMLHTTP');
				}
				catch(e)
				{
            objXHR = new ActiveXObject('Microsoft.XMLHTTP');
				}
    }
		else
		{
        alert('Votre navigateur ne supporte pas les objets XMLHttpRequest...');
        objXHR = false;
    }
		return objXHR;
}

// Gestion de l'affichage des infos clients (séparation coordonnées facturation et livraison)
function VS_changeInfosClient()
{
	var chkInfos = document.getElementById('chkAdresseLivraison');
	var divSimpleInfos = document.getElementById('simpleInfos');
	var divDoubleInfos = document.getElementById('doubleInfos');
	if(chkInfos.checked)
	{
		document.getElementById('frm_ref_civiliteFacturation2').selectedIndex = document.getElementById('frm_ref_civiliteFacturation').selectedIndex;
		document.getElementById('frm_nomFacturation2').value = document.getElementById('frm_nomFacturation').value;
		document.getElementById('frm_prenomFacturation2').value = document.getElementById('frm_prenomFacturation').value;
		document.getElementById('frm_raisonsocialeFacturation2').value = document.getElementById('frm_raisonsocialeFacturation').value;
		document.getElementById('frm_adresseFacturation2').value = document.getElementById('frm_adresseFacturation').value;
		document.getElementById('frm_codepostalFacturation2').value = document.getElementById('frm_codepostalFacturation').value;
		document.getElementById('frm_villeFacturation2').value = document.getElementById('frm_villeFacturation').value;
		document.getElementById('frm_telephoneFacturation2').value = document.getElementById('frm_telephoneFacturation').value;
		document.getElementById('frm_emailFacturation2').value = document.getElementById('frm_emailFacturation').value;
		document.getElementById('frm_loginClient2').value = document.getElementById('frm_loginClient').value;
		divDoubleInfos.style.display = '';
		divSimpleInfos.style.display = 'none';			
	}
	else
	{
		divDoubleInfos.style.display = 'none';
		divSimpleInfos.style.display = '';
	}
}

// Récupération d'une liste de vidéos
function VS_getListeVideos(refEntite_P,
													 codeLangue_P,
													 directory_P,
													 xmlScript_P,
													 frmRef_P)
{
	var videoDirectory = directory_P;
	var objXHR = VS_getXHR();
	// Gestion de l'événement de retour serveur
 	objXHR.onreadystatechange = function() 
															{ 
																//alert('readyState = "' + objXHR.readyState + '"\r\nstatus = "' + objXHR.status + '"');
																if(objXHR.readyState == 4 && objXHR.status == 200)
																{
																	//alert(objXHR.responseText);
																	var xml = objXHR.responseXML.documentElement;
																	VS_feedPlaylistVideos(xml,
																												videoDirectory);
																}
															};
	var xmlScriptPath = '../../xmldata/' + videoDirectory + '/' + xmlScript_P;	
	var paramUrlXML = frmRef_P + '=' + refEntite_P + '&codeLangue=' + codeLangue_P;
	objXHR.open('POST',
	   					xmlScriptPath,
							true);
	objXHR.setRequestHeader('Content-Type',
	     									  'application/x-www-form-urlencoded');
	objXHR.send(paramUrlXML);
}

// Récupération de la valeur de buffer
function VS_getBuffer()
{
	var frmBuffer = document.frmBuffer;
	var bufferHaut = document.frmBuffer.rdbtnBuffer[0];
	var bufferNormal = document.frmBuffer.rdbtnBuffer[1];
	var bufferFaible = document.frmBuffer.rdbtnBuffer[2];
	var bufferValue;
	if(bufferHaut.checked) bufferValue = bufferHaut.value;
	if(bufferNormal.checked) bufferValue = bufferNormal.value;
	if(bufferFaible.checked) bufferValue = bufferFaible.value;
	return bufferValue;
}

// Alimentation de la liste déroulante de playlist
function VS_feedPlaylistVideos(xml_P,
															 directory_P)
{
	var selectInnerHTML;
	var firstVideo = '../videos/' + directory_P + '/';
	var lignes = xml_P.getElementsByTagName('video'); 
	var nbLignes = lignes.length;
	var lstVideos = document.getElementById('lstVideos');
	lstVideos.options.length = nbLignes;
	if(nbLignes != 0)
	{
		for(var i = 0; i < nbLignes; i++)
		{
			var intitule = lignes[i].getElementsByTagName('intitule')[0].firstChild.nodeValue;
			var videoServeur = '';
			if(lignes[i].getElementsByTagName('videoserveur')[0].firstChild != null) videoServeur = lignes[i].getElementsByTagName('videoserveur')[0].firstChild.nodeValue;
			lstVideos.options[i].value = videoServeur;
      lstVideos.options[i].text = intitule;
			if(i == 0) firstVideo += videoServeur;
		}
		var bufferValue = VS_getBuffer();
		VS_getFLVPlayer(firstVideo,
										bufferValue);
	}
}



// Affichage de la vidéo sélectionné dans la playlist
function VS_getVideoFromList(directory_P,
														 index_P)
{
	var listVideos = document.getElementById('lstVideos');
	var videoSelected = '../videos/' + directory_P + '/' + listVideos.options[index_P].value;
	var bufferValue = VS_getBuffer();
	VS_getFLVPlayer(videoSelected,
									bufferValue);
}

// Affectation du débit pour la vidéo
function VS_changeBuffer(directory_P,
												 value_P)
{
	var listVideos = document.getElementById('lstVideos');
	var videoSelected = '../videos/' + directory_P + '/' + listVideos.options[listVideos.selectedIndex].value;
	VS_getFLVPlayer(videoSelected,
									value_P);
}

// Affichage du player FLV
function VS_getFLVPlayer(video_P,
												 bufferValue_P)
{
	
	// width of video:460, height of the video+20(for controlbar):380,
	// 9 for Flash Player 9 (for ON2 Codec and FullScreen)
	var objFLVPlayer = new SWFObject("../../flash/flvplayer.swf","iwflash","450","380","9", "#FFFFFF"); /* chemin relatif à la page d'affichage*/
	// for ExpressInstall
	objFLVPlayer.useExpressInstall("../../flash/playerProductInstall.swf"); /* chemin relatif à la page d'affichage */
	objFLVPlayer.setAttribute("xiRedirectUrl", window.location.href);
	// the video file or the playlist file
	objFLVPlayer.addVariable("file",video_P); /* chemin relatif au fichier flvprovider.php */
	// the PHP script
	objFLVPlayer.addVariable("streamscript","../php/flvprovider.php"); /* chemin relatif au fichier flvplayer.swf */
	objFLVPlayer.addVariable("bufferlength",bufferValue_P);
	// the width and the height of the video
	objFLVPlayer.addVariable("displaywidth","450");
	objFLVPlayer.addVariable("displayheight","360");
	objFLVPlayer.addVariable("autostart","false");
	objFLVPlayer.addVariable("showdigits","true");
	// for fullscreen
	objFLVPlayer.addParam("allowfullscreen","true");
	objFLVPlayer.addVariable("showfsbutton","true");
								
	objFLVPlayer.write("divVideoPlayer");
}

function VS_showGaleriePhoto()
{
	document.getElementById('frmfichierVideo').style.display = 'none';
	document.getElementById('lstVideos').style.display = 'none';
	document.getElementById('frmBuffer').style.display = 'none';
	document.getElementById('divVideoPlayer').style.display = 'none';
	
	document.getElementById('divPhotosBrowser').style.display = '';
}

function VS_showGalerieVideo()
{
	var styleDisplay = '';
	if(document.getElementById('lstVideos').options.length == 0) styleDisplay = 'none'; 
	document.getElementById('lstVideos').style.display = styleDisplay;
	document.getElementById('frmfichierVideo').style.display = styleDisplay;
	document.getElementById('frmBuffer').style.display = styleDisplay;
	document.getElementById('divVideoPlayer').style.display = styleDisplay;
		
	document.getElementById('divPhotosBrowser').style.display = 'none';
}

// Fonctions liées aux uploads de photo
// Fonction d'ouverture de la page de visualisation des photos
	function VS_openPhoto(strNom_P,
												strNomPhoto_P,
												intHauteurPhoto_P,
												intLargeurPhoto_P)
{
	// Constante de taille et de position
	var strTop  = '150';
	var strLeft = '150';
	var strHauteur = intHauteurPhoto_P;
	var strLargeur = intLargeurPhoto_P;
	var newWindow=window.open('','newWindow','width='+strLargeur+',height='+strHauteur+',left='+strLeft+',top='+strTop);
	newWindow.document.open();
	newWindow.document.write('<html><title>'+strNom_P+'<\/title><body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" onBlur="self.close()">'); 
	newWindow.document.write('<table width="100%" heigh="100%"><tr><td align="center" valign="middle">');
	newWindow.document.write('<img src="'+ strNomPhoto_P +'" width="'+intLargeurPhoto_P+'" height="'+intHauteurPhoto_P+'" alt="">'); 
	newWindow.document.write('<\/td><\/tr><\/table>');
	newWindow.document.write('<\/body><\/html>');
	newWindow.document.close();
	newWindow.focus();
}

// Fonction de coche pour suppression de l'image
function VS_deletePhoto(frm_delete_photo_P)
{
	document.getElementById(frm_delete_photo_P).checked = true;
}

// Fonction de click sur un encart publicitaire
function VS_clickOnPub(refCampagne_P,
					   url_P,
					   typeUrl_P,
					   baseUrl_P)
{
	var objXHR = VS_getXHR();
	var completeUrl = 'http://' + url_P;
	// Gestion de l'événement de retour serveur
 	objXHR.onreadystatechange = function() 
															{ 
																//alert('readyState = "' + objXHR.readyState + '"\r\nstatus = "' + objXHR.status + '"');
																if(objXHR.readyState == 4 && objXHR.status == 200) 
																{
																	if(objXHR.responseText == '') 
																	{
																		if(typeUrl_P == 'interne') window.location = completeUrl;
																		if(typeUrl_P == 'externe') window.open(completeUrl);
																	}
																	else alert(objXHR.responseText);
																	objXHR.abort();
																}
															};
	var scriptPath = baseUrl_P + 'ajaxscript/set-click-campagne.php';
	objXHR.open('POST',
	   					scriptPath,
							true);
	objXHR.setRequestHeader('Content-Type',
	     									  'application/x-www-form-urlencoded');
	objXHR.send('frm_ref_campagne_publicitaire=' + refCampagne_P);
}

function VS_imageDefautEncartPub(baseUrl_P,
																 langue_P,
																 chemin_Photo_Defaut_P,
																 largeur_Photo_Defaut_P,
																 hauteur_Photo_Defaut_P)
{
	var encartPub = document.getElementById('divZoneEncartPubCentrale');
	var innerHtml;
	(chemin_Photo_Defaut_P != '' && langue_P != '') ? innerHtml = '<a href="' + baseUrl_P +  langue_P + '/contacts/insertion-publicitaire.php"><img src="' + chemin_Photo_Defaut_P + '" alt="publicité par défaut" width="' + largeur_Photo_Defaut_P + '" height="' + hauteur_Photo_Defaut_P + '"></a>' : innerHtml = '<p align="center" style="color:#000000">Votre publicité ici</p>';
	encartPub.innerHTML = innerHtml;
}

// Fonction de gestion de la transparence des PNG sous Win IE 5.5 & 6.
function handlePNG()
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         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 = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}

function VS_getListeDureesTarifs(codeLangue_P,
																 refDuree_P)
{
	var tdDurees = document.getElementById('tdDurees');
	tdDurees.innerHTML = '';
	var linkValidation = document.getElementById('aValidation');
	linkValidation.style.display = 'none';
	var selectCategorie = document.getElementById('frm_ref_categorie_annonce');
	var indexCategorie = selectCategorie.selectedIndex;
	if(indexCategorie != 0) 
	{
		var refCategorie = selectCategorie.options[indexCategorie].value;
		var objXHR = VS_getXHR();
		objXHR.onreadystatechange = function() 
																{ 
																	//alert('readyState = "' + objXHR.readyState + '"\r\nstatus = "' + objXHR.status + '"');
																	if(objXHR.readyState == 4 && objXHR.status == 200) 
																	{
																		var xml = objXHR.responseXML.documentElement;
																		objXHR.abort();
																		var durees = xml.getElementsByTagName('duree');
																		var nbDurees = durees.length;
																		var html = '<table>';
																		for(var i = 0; i < nbDurees; i++)
																		{
																			var ref = durees[i].getElementsByTagName('ref')[0].firstChild.nodeValue;
																			var intitule = durees[i].getElementsByTagName('intitule')[0].firstChild.nodeValue;
																			var prixTTC = durees[i].getElementsByTagName('prixttc')[0].firstChild.nodeValue;
																			var prixPromoTTC = durees[i].getElementsByTagName('prixpromottc')[0].firstChild.nodeValue;
																			var promo = durees[i].getElementsByTagName('promo')[0].firstChild.nodeValue;
																			var prix;
																			(promo == 0) ? prix = prixTTC : prix = prixPromoTTC; 
																			var checked = '';
																			if(refDuree_P == ref) checked = 'CHECKED';
																			var texte = ' ' + intitule + ' - ' + prix + ' €';
																			html += '<tr>';
																			html += '<td>';
																			html += '<input type="radio" name="frm_ref_duree_annonce" id="frm_ref_duree_annonce" value="' + ref + '"' + checked + ' class="case">';
																			html += '<label>' +  texte + '</label>';
																			html += '</td>';
																			html += '</tr>';
																		}
																		html += '</table>';
																		tdDurees.innerHTML = html;
																		linkValidation.style.display = '';
																	}
																};
		objXHR.open('POST',
	  	 					'../../xmldata/petites-annonces/liste-durees-tarifs.xml.php',
								true);
		objXHR.setRequestHeader('Content-Type',
	  	   									  'application/x-www-form-urlencoded');
		var toSend = 'refCategorie=' + refCategorie + '&codeLangue=' + codeLangue_P;
		objXHR.send(toSend);
	}
}

// Affichage ou non du bouton de validation d'un panier
function VS_displayValidationPanier(checked_P)
{
	var linkValidation = MM_findObj('linkValidation'); 
	(checked_P) ? linkValidation.style.display = '' : linkValidation.style.display = 'none'; 
}

//Retourne le bon caractère pour un complément d'URL
function VS_getCharURL(url_P)
{
	var isSimpleURL = (url_P.lastIndexOf('?') == -1);
	var ponctuationUrl;
	if(isSimpleURL) ponctuationUrl = '?';
	else ponctuationUrl = '&';
	return ponctuationUrl;
}

function VS_seekVideoFormat(url_P)
{
	var lstVideoFormats = MM_findObj('lstVideoFormats');
	var indexSelected = lstVideoFormats.selectedIndex;
	if(indexSelected != 0)
	{
		var typeMime = lstVideoFormats.options[indexSelected].value;
		var ponctuationUrl = VS_getCharURL(url_P);
		url_P += ponctuationUrl + 'format=' + typeMime;
	}
	//alert(url_P);
	window.location.href = url_P;
}


function VS_clientVideoDownload(refPC_P,
																refVideo_P,
																categorie_P,
																debug_P)
{
	var objXHR = VS_getXHR();
	objXHR.onreadystatechange = function() 
															{ 
																//alert('readyState = "' + objXHR.readyState + '"\r\nstatus = "' + objXHR.status + '"');
																if(objXHR.readyState == 4 && objXHR.status == 200) 
																{
																	if(objXHR.responseText == '')
																	{
																		var urlDownload = 'telechargement.php?' + toSend + '&' + debug_P;
																		window.location.href = urlDownload;	
																	}
																	else 
																	{
																		alert(objXHR.responseText);
																		window.location.href = 'videos.php?' + debug_P;
																	}
																}
															};
	objXHR.open('POST',
	 	 					'../../ajaxscript/check-video-download.php',
							true);
	objXHR.setRequestHeader('Content-Type',
	 	   									  'application/x-www-form-urlencoded');
	var toSend = 'refPC=' + refPC_P + '&refVideo=' + refVideo_P + '&categorie=' + categorie_P;
	objXHR.send(toSend);
}




/**
 * Scripts v1.0: Flash Player detection
 *
 * (c) 2007 Versus Studio
 * http://www.versus-studio.com/
 */

	var VSversionTropAncienne = "";
	VSversionTropAncienne += '<div id="divAlternate">';
	VSversionTropAncienne += '<h1>Vous ne possèdez pas la dernière version de Macromedia Flash player</h1>';
	VSversionTropAncienne += '<p>Ce site web fait usage du lecteur Macromedia Flash. Vous avez une version ancienne de ce lecteur, vous ne pouvez pas lire le contenu de ce site sans faire la mise à jour adéquate.</p>';
	VSversionTropAncienne += '<p>Pour procéder à cette mise à jour, veuillez suivre les instructions sur le site de Macromedia en cliquant sur l\'image suivante : <a href="http://www.macromedia.com/go/getflashplayer" title="mise à jour du lecteur flash">http://www.macromedia.com/</A></p>';
	VSversionTropAncienne += "";
	VSversionTropAncienne += "";
	VSversionTropAncienne += "</div>";

	var VScancelMAJContent = "";
	VScancelMAJContent += '<div id="divAlternate">';
	VScancelMAJContent += '<h1>Vous avez choisi d\'annuler la mise à jour du lecteur Macromedia Flash Player</h1>';
	VScancelMAJContent += '<p>Ce site web fait usage du lecteur Macromedia Flash. Vous avez une version ancienne de ce lecteur, vous ne pouvez pas lire le contenu de ce site sans faire la mise à jour adéquate. Nous vous invitons à procéder à cette mise à jour en suivant les instructions sur le site de Macromedia en cliquant sur l\'image suivante : <a href="http://www.macromedia.com/go/getflashplayer" title="mise à jour du lecteur flash">http://www.macromedia.com/</A></p>';
	VScancelMAJContent += "</div>";

	var VSechecMAJContent = "";
	VSechecMAJContent += '<div id="divAlternate">';
	VSechecMAJContent += '<h1>La mise à jour du lecteur Macromedia Flash Player a échouée !</h1>';
	VSechecMAJContent += '<p>Ce site web fait usage du lecteur Macromedia Flash. Vous avez une version ancienne de ce lecteur, vous ne pouvez pas lire le contenu de ce site sans faire la mise à jour adéquate. Nous vous invitons à procéder à cette mise à jour en suivant les instructions sur le site de Macromedia en cliquant sur l\'image suivante : <a href="http://www.macromedia.com/go/getflashplayer" title="mise à jour du lecteur flash">http://www.macromedia.com/</A></p>';
	VSechecMAJContent += "</div>";

	var lienFlashAsDetection = 'flash/ActionScriptDetection/flash_AS_detection.swf';

	function VS_expressInstall(message) {// on affiche le flash d'ExpressInstall qui va proposer la mise  jour
		//alert(message);
		document.getElementById('divContent').innerHTML = so.getPlayerProductInstallHTML('flash/ActionScriptDetection/playerProductInstall.swf');
	}
	
	function VS_versionSuffisante(message) { // on affiche le site flash car la version du player est suffisante
		//alert(message);
		document.getElementById('divContent').innerHTML = so.getSiteSansTestSWFHTML();
	}
	
	function VS_versionTropAncienne(message) {// on affiche un texte expliquant qu'il faut tlcharger flash player manuellement, valable pour les versions antrieures   6.0.65
		//alert(message);
		document.getElementById('divContent').innerHTML = VSversionTropAncienne;
	}
	
	function VS_cancelMiseAjour(message) { // on explique que la personne a annul la MAJ et on invite  recommencer, valable pour les versions suprieures  6.0.65
		//alert(message);
		document.getElementById('divContent').innerHTML = VScancelMAJContent;
	}
	
	function VS_echecMiseAjour(message) { // on explique que la MAJ via ExpressInstall a choue et on invite  recommencer, valable pour les versions suprieures  6.0.65
		//alert(message);
		document.getElementById('divContent').innerHTML = VSechecMAJContent;
	}
