function initPage(){
	if(navigator.userAgent.indexOf('Mobile')!=-1 || navigator.userAgent.indexOf('MIDP')!=-1){
		isMobile=true;
		popOpen=false;
		popup_ami='popup_ami';
		popup_contact='popup_contact';
		popup_mentions='popup_mentions';
	}else{
		isMobile=false;
		popup_ami=initPopup('popup_ami', 280, 50, 500, true, false);
		popup_contact=initPopup('popup_contact', 280, 50, 600, true, false);
		popup_mentions=initPopup('popup_mentions', 57, 10, 810, true, false);
	}

	preload2=new Image();
	//preload2.src='media/article_on.png';
	document.originalTitle=document.title;
	
	if(typeof document.body.style.maxHeight=="undefined"){
		animDiv=document.getElementById('counter');
		window.onscroll=trackUnderIE5;
		//correctPNGIE();
	}
	firstBeat();
	updWebCam();
	getMeteo();
}

function initPopup(id, x, y, h, fade, usePhp){
	if(fade)
		var baseOpac=0;
	else
		var baseOpac=100;
	var popObj = new Box(id,'popup',x, 0-h, null, null, 20, baseOpac, null, null);
	if(usePhp)
		popObj.loadContent('xml/'+id+'.xml.php');
	else
		popObj.loadContent('xml/'+id+'.xml');
	popObj.divObj.style.visibility='visible';
	popObj.closed=true;
	popObj.fromLeft=x;
	popObj.fromTop=y;
	popObj.approxHeight=h;
	popObj.withFade=fade;
	return popObj;
}

function togglePopup(popObj){
	if(isMobile){
		if(popOpen)
			window.close();
		else
			window.open('popup.php?content='+popObj);
		return;
	}
	
	if(popObj.closed){
		scroll(0,0);
		popObj.closed=false;
		popObj.move(popObj.fromLeft,popObj.fromTop,1000,10);
		if(popObj.withFade)
			popObj.fadeMe(100,1000,2);
	}else{
		popObj.closed=true;
		popObj.move(popObj.fromLeft,0-popObj.approxHeight,1000,10);
		if(popObj.withFade)
			popObj.fadeMe(0,1000,5);
	}
}

//var so = new SWFObject("media/pub.swf", "mymovie", "320", "180", "8", "#ffffff");
function toggleVid(popObj){
	if(popObj.closed)
		so.write('flashcontent');
	else
		document.getElementById('flashcontent').innerHTML='';
	togglePopup(popObj);
}
function replayVid(){
	document.getElementById('flashcontent').innerHTML='';
	so.write('flashcontent');
}

var galSelectedId='first-vignette';
function showMe(me){
	if(me.id==galSelectedId)
		return;
	me.className='gal-vignette-activ';
	document.getElementById(galSelectedId).className='gal-vignette';
	galSelectedId=me.id;
	document.getElementById('galerie-frame').src=me.src;
	if(me.alt=='webcam')
		document.getElementById('galerie-link').href='http://webcam.hahd.fr';
	else
		document.getElementById('galerie-link').href=me.src.substring(0, me.src.length-4)+'_big.jpg';
}

preloadCam=new Image();
//preloadCam.src='http://83.173.72.77/jpg/image.jpg?'+Math.random();
preloadCam.src='http://83.173.72.77/axis-cgi/jpg/image.cgi?resolution=320x240&compression=10&date=0&'+Math.random();
function updWebCam(){
	if(!preloadCam.complete){
		preloadCam.src='http://83.173.72.77/axis-cgi/jpg/image.cgi?resolution=320x240&compression=10&date=0&'+Math.random();
		return;
	}
		
	window.status='';
	document.getElementById('first-vignette').src=preloadCam.src;

	if(galSelectedId=='first-vignette')
		document.getElementById('galerie-frame').src=preloadCam.src;
	
	//preloadCam.src='http://83.173.72.77/jpg/image.jpg?'+Math.random();
	//alert("cam Updated !!!");
	preloadCam.src='http://83.173.72.77/axis-cgi/jpg/image.cgi?resolution=320x240&compression=10&date=0&'+Math.random();
	setTimeout(updWebCam, 3000);
}
/*function updWebCamImg(){
	document.getElementById('first-vignette').src=preloadCam.src;
	if(galSelectedId=='first-vignette')
		document.getElementById('galerie-frame').src=preloadCam.src;
}


preloadCam=document.createElement('img');
if(window.addEventListener){ // Standard
    preloadCam.addEventListener('load', updWebCamImg, false);
}else if(window.attachEvent) { // IE
    preloadCam.attachEvent('onload', updWebCamImg);
}

function updWebCam(){	
	preloadCam.src='http://83.173.72.77/jpg/image.jpg?'+Math.random();
	setTimeout(updWebCam, 2000);
}*/

function sendFriend(){
	if(!formChecked())
		return;
	togglePopup(popup_ami);
	sendEmail(false);
}

function formChecked(){
	if(!isEmail('amiMail')){
		alert('Vous n\'avez pas correctement entré l\'email de votre ami !');
		return false;
	}
	if(!isEmail('votreMail')){
		alert('Vous n\'avez pas correctement entré votre email !');
		return false;
	}
	return true;
}

function sendContact(){
    alerte = '';
    if(document.getElementById('Question').value.length==0) alerte += '\t- votre question\n';
    if(!isEmail('Email')) alerte += '\t- votre adresse mail\n';
    
    if (alerte!='')
        alert('Veuillez vérifier les informations obligatoires suivantes :\n'+alerte);
    else{
		togglePopup(popup_contact);
		sendEmail(true);
	}
}
	
function isEmail(fieldToCheck){
	var textBox=document.getElementById(fieldToCheck);
	var email=textBox.value;
	if(email.match(new RegExp('^[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\.[A-Za-z]{2,4}$')))
		return true;
	return false;
}

function trackUnderIE5(){
	animDiv.className='counterTrack';
}
// PNG under IE 5.5+
/*function correctPNGIE(){
	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 -=1;
		}
	}
}*/

function sendThisArticle(){
	document.getElementById('msgBox').innerHTML='';
	document.getElementById('btnSend').href='#';
	document.getElementById('btnSend').innerHTML='Veuillez patienter...';
	setTimeout(sendArticle,100);
}

commentsUpdInProgress=false;
commentSendingInProgress=false;
var lastCommentId;

function sendThisComment(){
	commentSendingInProgress=true;
	document.getElementById('btnPost').onClick='#';
	document.getElementById('btnPost').value='Veuillez patienter...';
	if(commentsUpdInProgress)
		setTimeout(sendThisComment,100);
	else
		sendComment();
}

function commentsWatcher(){
	if(!commentsUpdInProgress && !commentSendingInProgress)
		checkComments();
	setTimeout(commentsWatcher,30000);
}

function checkComments(){
	commentsUpdInProgress=true;
	mainReq.abort();	
	mainReq.onreadystatechange=updComments;
	mainReq.open("POST", 'xml/send_comment.xml.php');
	mainReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	mainReq.send('noPost=1'+'&lastComId='+lastCommentId+'&article='+articleId);
}

function updComments(){
    if(mainReq.readyState==4)
        if(mainReq.status==200){
			var i=0;
			while(i<mainReq.responseXML.getElementsByTagName('comment').length){
				document.getElementById('commentsBox').innerHTML+=mainReq.responseXML.getElementsByTagName('comment')[i].firstChild.data;
				i++;
			}
			lastCommentId=mainReq.responseXML.getElementsByTagName('lastid')[0].firstChild.data;
			commentsUpdInProgress=false;
		}
}

function uploadImg(){
	var imgUpd=document.getElementById('imgFile').value.toLowerCase();
	if(imgUpd.length==0){
		return;
	}
	if((imgUpd.lastIndexOf('.jpg')!=imgUpd.length-4) && (imgUpd.lastIndexOf('.jpeg')!=imgUpd.length-5)){
		document.getElementById('msgBox').innerHTML='Votre image doit être au format jpeg !';
		return;
	}
	document.getElementById('btnSend').href='#';
	document.getElementById('btnSend').innerHTML='Veuillez patienter...';
	document.getElementById('loader').src='media/process.gif';
	document.getElementById('loader').style.display='';
	document.getElementById('img_upload_form').target='upload_target';
	document.getElementById('img_upload_form').submit();
}

var imgTmpName='';
function imgUploaded(imgName){
	document.getElementById('loader').alt='';
	document.getElementById('loader').src='media/usrTmp/'+imgName+'.jpg';
	imgTmpName=imgName;
	document.getElementById('btnSend').href='javascript:sendThisArticle()';
	document.getElementById('btnSend').innerHTML='Envoyer';
}

function uploadFile(){
	var fileUpd=document.getElementById('fileFile').value;
	if(fileUpd.length==0){
		return;
	}
	document.getElementById('fileName').value=fileUpd;
	document.getElementById('btnSend').href='#';
	document.getElementById('btnSend').innerHTML='Veuillez patienter...';
	document.getElementById('fileLoader').src='media/process.gif';
	document.getElementById('fileLoader').style.display='';
	document.getElementById('file_upload_form').target='uploadFile_target';
	document.getElementById('file_upload_form').submit();
}

var fileTmpName='';
var fileNameJS='';
function fileUploaded(FileName, hasIcon){
	var fileUpd=document.getElementById('fileFile').value;
	fileUpd=fileUpd.substring(fileUpd.lastIndexOf('/')+1);
	fileUpd=fileUpd.substring(fileUpd.lastIndexOf('\\')+1);
	fileNameJS=fileUpd;
	document.getElementById('fileNameBox').innerHTML=fileUpd;
	document.getElementById('lockSpan').style.display='';
	//document.getElementById('loader').alt=fileUpd;
	if(hasIcon)
		document.getElementById('fileLoaderTd').style.backgroundImage='url(/media/fileIcons/'+fileUpd.substring(fileUpd.length-3)+'.png)';
	else
		document.getElementById('fileLoaderTd').style.backgroundImage='url(/media/fileIcons/file.png)';
	fileTmpName=FileName;
	document.getElementById('btnSend').href='javascript:sendThisArticle()';
	document.getElementById('btnSend').innerHTML='Envoyer';
}

function toggleLoginBox(artId){
	if(document.getElementById('loginBox'+artId).style.display=='none')
		document.getElementById('loginBox'+artId).style.display='';
	else
		document.getElementById('loginBox'+artId).style.display='none';
}

function toggleLock(){
	//document.getElementById('lockImg').style.behavior='';
	if(document.getElementById('lockImg').style.visibility=='hidden')
		document.getElementById('lockImg').style.visibility='visible';
	else
		document.getElementById('lockImg').style.visibility='hidden';
}

function openThis(toOpen){
	window.open(toOpen,'_blank');
}

/***************** Heartbeat *****************/

function runPhp(urlToRun){
	xmlhttp.open("GET", urlToRun);
	xmlhttp.send(null);
	//xmlhttp.send(args[]);
}

var hbRequest=httpRequest();

var pnlTopX=0;
var pnlTopY=0;
var pnlBottomX=0;
var pnlBottomY=0;
var nbDisplayed=0;
var sprites=new Array();
var spriteImgs=new Array('ms3-invader.gif','ms3-invader2.gif');

function firstBeat(){
	pnlTopX=0;
	pnlTopY=0;
	//pnlTopY=document.getElementById('counter').offsetTop;
	//pnlBottomX=document.body.clientWidth-pnlBottomX;
	pnlBottomX=210-32;
	pnlBottomY=260-30;
	heartBeat();
}

function heartBeat(){
	hbRequest.abort();
	hbRequest.onreadystatechange=mainUpdate;
	hbRequest.open("GET", 'xml/heartbeat.xml.php?'+Math.random());
	hbRequest.setRequestHeader("Cache-Control", "no-cache");
	hbRequest.send(null);
	setTimeout(heartBeat, 5000);
}

function mainUpdate(){
    if(hbRequest.readyState==4)
        if(hbRequest.status==200)
        	updateNbUsers(hbRequest.responseXML.getElementsByTagName('rez')[0].firstChild.data);
        //else
            //alert("There was a problem retrieving the XML data:\n" + hbRequest.statusText);
}

function updateNbUsers(newNbUsers){
	//alert('nbConnected : '+nbConnected+' / newNbUsers :'+newNbUsers);
	if(nbConnected!=newNbUsers){
		var txt='connecté';
		if(newNbUsers>1)
			txt+='s';
		document.getElementById('counterTxt').innerHTML=newNbUsers+' '+txt;
	}
	nbConnected=newNbUsers;
	if(nbConnected>nbDisplayed){
		while(nbConnected!=nbDisplayed)
			addSprite();
	}
	
	if(nbConnected<nbDisplayed){
		while(nbConnected!=nbDisplayed)
			delSprite();
	}
}

function rand(max){
	 return Math.round(Math.random()*max);
}

function addSprite(){
	//var sprt=new Box('usr'+(nbDisplayed), rand(pnlBottomX-pnlTopX)+pnlTopX, rand(pnlBottomY-pnlTopY)+pnlTopY, null, null, 30, 0, '<img src="media/'+spriteImgs[rand(spriteImgs.length)]+'"/>', 'counter');
	var sprt=new Box('usr'+(nbDisplayed), null, rand(pnlBottomX-pnlTopX)+pnlTopX, rand(pnlBottomY-pnlTopY)+pnlTopY, null, null, 2, 0, '<img src="media/'+spriteImgs[rand(spriteImgs.length-1)]+'"/>', 'counter');
	nbDisplayed++;
	sprites[nbDisplayed]=sprt;
	sprt.fadeMe(100,100,1);
}

function delSprite(){
	sprites[nbDisplayed].fadeMe(0,100,1);
	nbDisplayed--;
}



