/*=================================================================
	Function: formatDate (javascript object Date(), format)
	Purpose:  Returns a date in the output format specified.
              The format string can use the following tags:
				 Field        | Tags
				 -------------+-------------------------------
				 Year         | yyyy (4 digits), yy (2 digits)
				 Month        | MM (2 digits)
				 Day of Month | dd (2 digits)
				 Hour (1-12)  | hh (2 digits)
				 Hour (0-23)  | HH (2 digits)
				 Minute       | mm (2 digits)
				 Second       | ss (2 digits)
	Author:   Laurent Destailleur
	Licence:  GPL
==================================================================*/
function formatDate(date,format)
{
	//alert('formatDate date='+date+' format='+format);
	
	// Force parametres en chaine
	format=format+"";
	
	var result="";

	var year=date.getYear()+""; if (year.length < 4) { year=""+(year-0+1900); }
	var month=date.getMonth()+1;
	var day=date.getDate();
	var hour=date.getHours();
	var min=date.getMinutes();
	var seconde=date.getSeconds();

	var i=0;
	while (i < format.length)
	{
		c=format.charAt(i);	// Recupere char du format
		substr="";
		j=i;
		while ((format.charAt(j)==c) && (j < format.length))	// Recupere char successif identiques
		{
			substr += format.charAt(j++);
		}

		//alert('substr='+substr);
		if (substr == 'yyyy')      { result=result+year; }
		else if (substr == 'yy')   { result=result+year.substring(2,4); }
		else if (substr == 'MM')   { result=result+(month<1||month>9?"":"0")+month; }
		else if (substr == 'd')    { result=result+day; }
		else if (substr == 'dd')   { result=result+(day<1||day>9?"":"0")+day; }
		else if (substr == 'hh')   { if (hour > 12) hour-=12; result=result+(hour<1||hour>9?"":"0")+hour; }
		else if (substr == 'HH')   { result=result+(hour<1||hour>9?"":"0")+hour; }
		else if (substr == 'mm')   { result=result+(minute<1||minute>9?"":"0")+minute; }
		else if (substr == 'ss')   { result=result+(seconde<1||seconde>9?"":"0")+seconde; }
		else { result=result+substr; }
		
		i+=substr.length;
	}

	//alert(result);
	return result;
}



/*=================================================================
	Function: getDateFromFormat(date_string, format_string)
	Purpose:  This function takes a date string and a format string.
			  It parses the date string with format and it returns
			  the date as a javascript Date() object.
			  If date does not match format, it returns 0.
              The format string can use the following tags:
				 Field        | Tags
				 -------------+-------------------------------
				 Year         | yyyy (4 digits), yy (2 digits)
				 Month        | MM (2 digits)
				 Day of Month | dd (2 digits)
				 Hour (1-12)  | hh (2 digits)
				 Hour (0-23)  | HH (2 digits)
				 Minute       | mm (2 digits)
				 Second       | ss (2 digits)
	Author:   Laurent Destailleur
	Licence:  GPL
==================================================================*/
function getDateFromFormat(val,format)
{
	//alert('getDateFromFormat val='+val+' format='+format);

	// Force parametres en chaine
	val=val+"";
	format=format+"";

	var now=new Date();
	var year=now.getYear(); if (year.length < 4) { year=""+(year-0+1900); }
	var month=now.getMonth()+1;
	var day=now.getDate();
	var hour=now.getHours();
	var minute=now.getMinutes();
	var seconde=now.getSeconds();

	var i=0;
	while (i < format.length)
	{
		c=format.charAt(i);	// Recupere char du format
		substr="";
		j=i;
		while ((format.charAt(j)==c) && (j < format.length))	// Recupere char successif identiques
		{
			substr += format.charAt(j++);
		}

		//alert('substr='+substr);
		if (substr == "yyyy") year=getIntegerInString(val,i,4,4);
		if (substr == "yy")   year=""+(getIntegerInString(val,i,2,2)-0+1900);
		if (substr == "MM")   month=getIntegerInString(val,i,2,2);
		if (substr == "M")    month=getIntegerInString(val,i,1,2);
		if (substr == "dd")   day=getIntegerInString(val,i,1,2);
		if (substr == "hh")   hour=getIntegerInString(val,i,1,2);
		if (substr == "HH")   hour=getIntegerInString(val,i,1,2);
		if (substr == "mm")   minute=getIntegerInString(val,i,1,2);
		if (substr == "ss")   seconde=getIntegerInString(val,i,1,2);
	
		i+=substr.length;
	}
	
	// Check if format param are ok
	if (year==null||year<1) { return 0; }
	if (month==null||(month<1)||(month>12)) { return 0; }
	if (day==null||(day<1)||(day>31)) { return 0; }
	if (hour==null||(hour<0)||(hour>24)) { return 0; }
	if (minute==null||(minute<0)||(minute>60)) { return 0; }
	if (seconde==null||(seconde<0)||(seconde>60)) { return 0; }
		
	//alert(year+' '+month+' '+day+' '+hour+' '+minute+' '+seconde);
	var newdate=new Date(year,month-1,day,hour,minute,seconde);

	return newdate;
}


/*=================================================================
	Function: stringIsInteger(string)
	Purpose:  Return true if string is an integer
==================================================================*/
function stringIsInteger(str)
{
	var digits="1234567890";
	for (var i=0; i < str.length; i++)
	{
		if (digits.indexOf(str.charAt(i))==-1)
		{
			return false;
		}
	}
	return true;
}


/*=================================================================
	Function: getIntegerInString(string,pos,minlength,maxlength)
	Purpose:  Return part of string from position i that is integer
==================================================================*/
function getIntegerInString(str,i,minlength,maxlength)
{
	for (var x=maxlength; x>=minlength; x--)
	{
		var substr=str.substring(i,i+x);
		if (substr.length < minlength) { return null; }
		if (stringIsInteger(substr)) { return substr; }
	}
	return null;
}


/*=================================================================
	Purpose:  crypte email en javascript pour eviter aspirateur mail
	Input:    url,title
==================================================================*/
function openm_OnClick(part0,part1) {
    s1='mail'; s4='Contact%20petite%20annonce';
	s5=s1+'to:'+part0+'@'+part1+'?subject='+s4;
	fen=window.open(s5,'mailwindow',0);
    //fen=window.open('mailto:ee@ee.com?subject=eee','mailwindow',0);
	return false;
}
function showm(part0,part1) {
	document.write(part0+'@'+part1);
}


/*=================================================================
	Purpose:  affiche popup aide
	Input:    url,title
==================================================================*/
function newhelp(url,title) {
	var argv = newhelp.arguments;
	var argc = newhelp.arguments.length;
	tmp=url;
	var l = (argc > 2) ? argv[2] : 600;
	var h = (argc > 3) ? argv[3] : 400;
	var wfeatures="directories=0,menubar=0,status=0,resizable=0,scrollbars=1,toolbar=0,width="+l+",height="+h+",left=" + eval("(screen.width - l)/2") + ",top=" + eval("(screen.height - h)/2");
	fen=window.open(tmp,title,wfeatures);
	return false;
}


/*=================================================================
	Purpose:  position, draw, and display tooltip element 
	Input:    fArg - indexes text array to display
	Comment:  Use onmouseover="ShowTooltip(x);" as control properties to use this
==================================================================*/
function ShowTooltip(fArg,extracond) {
	var tooltipOBJ = (document.getElementById) ? document.getElementById('tt' + fArg) : eval("document.all['tt" + fArg + "']");
	var tooltipOffsetTop = tooltipOBJ.scrollHeight + 20;
	var testTop = (document.body.scrollTop + event.clientY) - tooltipOffsetTop;
/*	var testTop = (document.body.scrollTop + event.clientY) + 20; */
/*	var testLeft = event.clientX - 300; */
	var testLeft = event.clientX + 20;
	var tooltipAbsLft = (testLeft < 0) ? 4 : testLeft;
	var tooltipAbsTop = (testTop < document.body.scrollTop) ? document.body.scrollTop + 10 : testTop;
	if (extracond == "") {
		tooltipOBJ.style.posLeft = tooltipAbsLft;
		tooltipOBJ.style.posTop = tooltipAbsTop;
		tooltipOBJ.style.visibility = "visible";
	}
}

/*=================================================================
	Purpose:  set visibility attribute of tooltip to hidden
	Comment:  Use onmouseout="HideTooltip(x);" as control properties to use this
==================================================================*/
function HideTooltip(fArg) {
	var tooltipOBJ = (document.getElementById) ? document.getElementById('tt' + fArg) : eval("document.all['tt" + fArg + "']");
	tooltipOBJ.style.visibility = "hidden";
}


function ShowTip(fArg)
{
	var tooltipOBJ = (document.getElementById) ? document.getElementById('tt' + fArg) : eval("document.all['tt" + fArg + "']");
	if (tooltipOBJ != null)
	{
		var tooltipLft = (document.body.offsetWidth?document.body.offsetWidth:document.body.style.pixelWidth) - (tooltipOBJ.offsetWidth?tooltipOBJ.offsetWidth:(tooltipOBJ.style.pixelWidth?tooltipOBJ.style.pixelWidth:350)) - 30;
		var tooltipTop = 10;
		if (navigator.appName == 'Netscape')
		{
			tooltipTop = (document.body.scrollTop>=0?document.body.scrollTop+10:event.clientY+10);
 			tooltipOBJ.style.top = tooltipTop+"px";
			tooltipOBJ.style.left = tooltipLft+"px";
		}
		else
		{
			tooltipTop = (document.body.scrollTop>=0?document.body.scrollTop+10:event.clientY+10);
			if ((event.clientX > tooltipLft) && (event.clientY < (tooltipOBJ.scrollHeight?tooltipOBJ.scrollHeight:tooltipOBJ.style.pixelHeight) + 10))
			{
				tooltipTop = (document.body.scrollTop?document.body.scrollTop:document.body.offsetTop) + event.clientY + 20;
			}
			tooltipOBJ.style.left = tooltipLft;
			tooltipOBJ.style.top = tooltipTop;
		}
		tooltipOBJ.style.visibility = "visible";
	}
}

function HideTip(fArg)
{
	var tooltipOBJ = (document.getElementById) ? document.getElementById('tt' + fArg) : eval("document.all['tt" + fArg + "']");
	if (tooltipOBJ != null) {
		tooltipOBJ.style.visibility = "hidden";
	}
}



/*=================================================================
	Purpose: Print last revision access
==================================================================*/
function LastRevision() {
	var lastmod = new Date(document.lastModified);
	if (lastmod.getDate() > 0) {
		if (lastmod.getDate()<10) zerod="0"
		else zerod="";
		if (lastmod.getMonth()<9) zerom="0"
		else zerom=""
		year2kok=lastmod.getYear();
		if (year2kok<100) year2kok+=2000;
		if ((year2kok>=100) && (year2kok < 1970)) year2kok+=1900;
		document.writeln("Derni&egrave;re r&eacute;vision: "+zerod+lastmod.getDate()+"/"+zerom+(lastmod.getMonth()+1)+"/"+year2kok);
	}
}

/*=================================================================
	Purpose: Return Browser name and version
	Output:  UA = "Microsoft Internet Explorer" or "Netscape" or "..."
	         UAversion = version of browser
==================================================================*/
var UA;
var UAversion;
function checkUA() {
	UA = (navigator.appName);							// the navigator
	UAversion = parseFloat(navigator.appVersion);		// The version
	var isIE = (UA == "Microsoft Internet Explorer");
	var isNetscape = (UA == "Netscape");
	var other = false;
	// Add the latest builds of IE & Netscape Here
	var curIEbuild = parseFloat("5.5");
	var curNSbuild = parseFloat("4.74");
	if (isIE && UAversion >= 4) { UAok = true; }
	if (isNetscape && UAversion >= 4.08) { UAok = true; }
	if (isIE) {
		// IE Returns 4, even if it's 5 so we have to snoop the real version from the headers.
	  	if (navigator.appVersion.indexOf("MSIE") != -1) {
	   		IEmajorStart = navigator.appVersion.indexOf("MSIE") + 4;
	   		IEmajorEnd = (IEmajorStart + 5);
	   		theMajor = navigator.appVersion.substring(IEmajorStart, IEmajorEnd);
	   		UAversion = theMajor;
	  	}
	  	if (isNaN(UAversion)) {
	  		UAversion = (UAversion.substring(0, (UAversion.length - 1)));
		}
	}
}


/*=================================================================
	Purpose: Used to limit length for textarea
	Output:  NA
==================================================================*/

// This Function returns the Left position of an object
function checkLength(field, len) {
	if(field.value.length > len)   field.value = field.value.substr(0, len);
}


/*=================================================================
	Purpose: Function for popup
	Output:  NA
==================================================================*/

// This Function returns the Left position of an object
function getLeft(theitem){
	var offsetTrail = theitem;
	var offsetLeft = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
		offsetLeft += document.body.leftMargin;
	return offsetLeft;
}

// This Function returns the Top position of an object
function getTop(theitem){
	var offsetTrail = theitem;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
		offsetLeft += document.body.TopMargin;
	return offsetTop;
}


if (document.getElementById||document.all){
	document.write("<div id='popmenu'  STYLE='z-index:1; left: 200px; visibility: hidden; position: absolute; top: 10px'>");
	document.write("</div>");
}else {
	document.write("<layer position='absolute' name='popmenu' left='200' top='10' visibility='hide'>")
	document.write("</layer>");
}




/*=================================================================
	Purpose:  Pour la saisie des dates par calendrier
	Input:    base			   "/theme/eldy"
					  dateFieldID  "dateo"			  Nom du champ
				    format			 "dd/MM/yyyy"   Format issu de Dolibarr de SimpleDateFormat à utiliser pour retour
==================================================================*/

function showDP(base,dateFieldID,format)
{
	//check to see if another box is already showing
	var alreadybox=getObjectFromID("DPCancel");
	if (alreadybox) closeDPBox();	// This erase value of showDP.datefieldID

	//alert("showDP "+dateFieldID);
	showDP.datefieldID=dateFieldID;	// Must be after the close

	var dateField=getObjectFromID(dateFieldID);

	//get positioning
	var thetop=getTop(dateField)+dateField.offsetHeight;

//	var xxx=getObjectFromID('bottompage');
//alert(xxx.style.pixelTop);
//alert(document.body.clientHeight);
//alert(document.body.style.offsetTop);
//alert(thetop);
//alert(window.innerHeight);
	if (thetop+160 > window.innerHeight)
		thetop=thetop-160-20;
	var theleft=getLeft(dateField);
	if (theleft+140 > window.innerWidth)
		theleft= theleft-140+dateField.offsetWidth-15;

	showDP.box=document.createElement("div");
	showDP.box.className="bodyline";
	showDP.box.style.siplay="block";
	showDP.box.style.position="absolute";
	showDP.box.style.top=thetop + "px";
	showDP.box.style.left=theleft + "px";
	
	if (dateField.value)	// Si il y avait valeur initiale dans champ
	{
		selDate=getDateFromFormat(dateField.value,format);
		if (selDate)
		{
			// Success to parse value in field according to format
			year=selDate.getFullYear();
			month=selDate.getMonth()+1;
			day=selDate.getDate();
			datetime=selDate.getTime();
			ymd=formatDate(selDate,'yyyyMMdd');
		}
		else
		{
			// Failed to parse value in field according to format
			selDate=new Date();
			year=selDate.getFullYear();
			month=selDate.getUTCMonth()+1;
			day=selDate.getDate();
			datetime=selDate.getTime();
			ymd=formatDate(selDate,'yyyyMMdd');
		}
	}
	else
	{
		selDate=new Date();
		year=selDate.getFullYear();
		month=selDate.getUTCMonth()+1;
		day=selDate.getDate();
		datetime=selDate.getTime();
		ymd=formatDate(selDate,'yyyyMMdd');
	}
	loadMonth(base,month,year,ymd);
	hideSelectBoxes();
	document.body.appendChild(showDP.box);
}

function loadMonth(base,month,year,ymd)
{
	showDP.box.innerHTML="Loading...";
	var theURL=base+"datepicker.php?cm=shw";
	theURL+="&m="+encodeURIComponent(month);
	theURL+="&y="+encodeURIComponent(year);
	if (selDate)
	{
		theURL+="&sd="+ymd;
	}

	loadXMLDoc(theURL,null,false);
	showDP.box.innerHTML=req.responseText;	
}

function closeDPBox()
{
	document.body.removeChild(showDP.box);
	displaySelectBoxes();
	showDP.box=null;	
	showDP.datefieldID=null;	
	//alert("closeBox");
}

function dpChangeDay(dateFieldID,format)
{
	//alert("dpChangeDay "+dateFieldID);
	showDP.datefieldID=dateFieldID;
}

function dpClickDay(year,month,day,format)
{
	//alert("dpClickDay "+showDP.datefieldID);
	var thefield=getObjectFromID(showDP.datefieldID);

	var dt = new Date();
	dt.setMonth(month-1);
	dt.setYear(year);
	dt.setDate(day);

	thefield.value=formatDate(dt,format);
	if(thefield.onchange) thefield.onchange.call(thefield);

	closeDPBox();
}

function dpHighlightDay(year,month,day,tradMonths){
	var displayinfo=getObjectFromID("dpExp");
	var months = tradMonths;
	displayinfo.innerHTML=months[month-1]+" "+day+", "+year;
}

//Returns an object given an id
function getObjectFromID(id){
	var theObject;
	if(document.getElementById)
		theObject=document.getElementById(id);
	else
		theObject=document.all[id];
	return theObject;
}

// This Function returns the top position of an object
function getTop(theitem){
	var offsetTrail = theitem;
	var offsetTop = 0;
	while (offsetTrail) {
		offsetTop += offsetTrail.offsetTop;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
		offsetLeft += document.body.TopMargin;
	return offsetTop;
}

// This Function returns the left position of an object
function getLeft(theitem){
	var offsetTrail = theitem;
	var offsetLeft = 0;
	while (offsetTrail) {
		offsetLeft += offsetTrail.offsetLeft;
		offsetTrail = offsetTrail.offsetParent;
	}
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
		offsetLeft += document.body.leftMargin;
	return offsetLeft;
}

function loadXMLDoc(url,readyStateFunction,async) 
{
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.onreadystatechange = readyStateFunction;
		req.open("GET", url, async);
		req.send(null);
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			if(readyStateFunction) req.onreadystatechange = readyStateFunction;
			req.open("GET", url, async);
			req.send();
		}
	}
}

function hideSelectBoxes() {
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {		
		for(var i = 0; i < document.all.length; i++) {
			if(document.all[i].tagName)
				if(document.all[i].tagName == "SELECT") 
					document.all[i].style.visibility="hidden";
		}
	}
}

function displaySelectBoxes() {
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {		
        for(var i = 0; i < document.all.length; i++) {
                if(document.all[i].tagName)
                        if(document.all[i].tagName == "SELECT")
                                document.all[i].style.visibility="visible";
        }
	}
}


// Afficher/cacher les champs d'un formulaire
function formDisplayHideId(baliseId,numField) 
  {
  //if (document.getElementById && document.getElementById(baliseId) != null) 
    //{
    	//var balise = document.getElementById(baliseId);

    	var numDiv = 1
    	
      if (document.formsoc.typent_id.value == 8)
    	  {

    	  	while ( document.getElementById( baliseId + numDiv) ) {
    	  	
    	  	var balise = document.getElementById( baliseId + numDiv);
   	  	
    	  	if (balise && balise.className == "hidden") 
              balise.className = "visible";
              
          if (balise && balise.className == "visible") 
              balise.className = "hidden";
              numDiv++

            }
    	  }
      else
    	  {

    	  	while ( document.getElementById( baliseId + numDiv) ) {
    	    
    	    var balise = document.getElementById( baliseId + numDiv);

    		  if (balise && balise.className == "visible") 
              balise.className = "hidden";
              
          if (balise && balise.className == "hidden") 
              balise.className = "visible";
              numDiv++

            }
    	  }
     //}
  }



function newannonce(id_an)
{
	var argv = newannonce.arguments;
	var argc = newannonce.arguments.length;
	tmp="/detail_an.php?id_annon="+id_an;
	var l = (argc > 2) ? argv[2] : 740;var h = (argc > 3) ? argv[3] : 520;
	//var l=768; var h=520;
	var wfeatures="directories=0,menubar=1,status=0,resizable=1,scrollbars=1,toolbar=0,width="+l+",height="+h+",left=" + eval("(screen.width - l)/2") + ",top=" + eval("(screen.height - h)/2");
	//alert("l"+l+" h"+h+" wfeatures"+wfeatures);
	fen=window.open(tmp,'detail',wfeatures);
}

