var scrollTopFactor = 0;
var theSlider = null;

var scrollTopFactor_popDiv = 0;
var theSlider_popDiv = null;

var scrollTopFactor_popNews = 0;
var theSlider_popNew = null;

var currentNews   = null;
var newsArray     = null;
var newsArraySize = 0;
var currentNewsImages = null;


var currentHiddenLeft = null;

var lastSelectedReference = null;

function dnf(){ // deafult null function
	var toto = null;
}

function getElt(sName){
	return $(sName);	
}

function customer_connect(){
	alert('Erreur de login');
	//todo
}

function makeNewsSlider(){
	var h = $('allNews').getDimensions().height;
	var containerH = $('allNews').up().getDimensions().height;
	
	scrollTopFactor = h - containerH;
	
	var fullH = h;
	if(fullH < containerH){fullH = containerH};
	
	var handleSize = containerH/fullH * $('theSlider').getDimensions().height;
	
	
	if( handleSize < $('theSlider').getDimensions().height)
	{
		$('theHandle').setStyle({height:handleSize+"px"});
		
		theSlider = new Control.Slider('theHandle', 'theSlider', {
			  axis:'vertical',
			  range: $R(0, 1),
			  sliderValue: 0,
			  onSlide: function(value) {
				$('allNewsContainer').scrollTop = value*scrollTopFactor;//slideIt(value,'allNewsContainer');
			  },
			  onChange: function(value) {
				$('allNewsContainer').scrollTop = value*scrollTopFactor;//slideIt(value,'allNewsContainer');
			  }
		 });
	}
	else{
		$('theHandle').hide();	
	}
}

function checkHandlePopDivNeeded(){
	var h = $("pop_div_content").down().getDimensions().height;
	var containerH = $("pop_div_content").getDimensions().height;
	
	scrollTopFactor_popDiv = h - containerH;
	
	var fullH = h;
	if(fullH < containerH){fullH = containerH};
	
	var handleSize = containerH/fullH * $('theSlider_popDiv').getDimensions().height;
	
	if( handleSize < $('theSlider_popDiv').getDimensions().height)
	{
		$('theHandle_popDiv').setStyle({height:handleSize+"px"});
		
		$("theSlider_popDiv").show();
		
		if(theSlider_popDiv != null) theSlider_popDiv.dispose();
		theSlider_popDiv = new Control.Slider('theHandle_popDiv', 'theSlider_popDiv', {
			  axis:'vertical',
			  range: $R(0, 1),
			  sliderValue: 0,
			  onSlide: function(value) {
				$('pop_div_content').scrollTop = value*scrollTopFactor_popDiv;
			  },
			  onChange: function(value) {
				$('pop_div_content').scrollTop = value*scrollTopFactor_popDiv;
			  }
		 });
		
	}
	else{
		$("theSlider_popDiv").hide();	
	}
}

function checkHandlePopNewsNeeded(){
	$('news_content').scrollTop = 0;
	var ieCorrection = 0;
	if(Prototype.Browser.IE){ieCorrection = 5;}
	
	var h = $("news_content").down().getDimensions().height + ieCorrection;
	var containerH = $("news_content").getDimensions().height;
	
	scrollTopFactor_popNews = h - containerH;
	
	var fullH = h;
	if(fullH < containerH){fullH = containerH};
	
	var handleSize = containerH/fullH * $('theSlider_pop_news').getDimensions().height;
	
	if( handleSize < $('theSlider_pop_news').getDimensions().height)
	{
		$('theHandle_pop_news').setStyle({height:handleSize+"px"});
		
		$("theSlider_pop_news").show();
		
		if(theSlider_popNew != null) theSlider_popNew.dispose();
		theSlider_popNew = new Control.Slider('theHandle_pop_news', 'theSlider_pop_news', {
			  axis:'vertical',
			  range: $R(0, 1),
			  sliderValue: 0,
			  onSlide: function(value) {
				$('news_content').scrollTop = value*scrollTopFactor_popNews;
			  },
			  onChange: function(value) {
				$('news_content').scrollTop = value*scrollTopFactor_popNews;
			  }
		 });
		
	}
	else{
		$("theSlider_pop_news").hide();	
	}
}

function registerNewsImagesToLoad(){
	currentNewsImages = $('news_content').getElementsBySelector('img');
	currentNewsImages.each(function(o){
									o.onload = newsImageLoaded;
									});
}

function newsImageLoaded(e){

	var theObj = Event.element(e);
	
	var imgLeftToLoad = currentNewsImages.size();
	var theObjSrc = "";
	try{
		theObjSrc = theObj.src;
		//alert(theObj.src+" : IS LOADED !");
	}
	catch(err){/*nothing*/ }
	
	if((imgLeftToLoad > 0) && (theObjSrc != "")){
		var new_currentNewsImages = currentNewsImages.without(theObj);
		
		if(new_currentNewsImages.size()<imgLeftToLoad){
			checkHandlePopNewsNeeded();
		}		
	}
}

/*
function makeNewsPopupSlider(){
	var h = $('news_content').getDimensions().height;
	var fullHeight = $('news_content').scrollHeight;
	
	scrollTopFactor_pop = fullHeight - h;
	
	var handleSize = 20; //h>fullHeight?h:containerH*(containerH/h);
	
	if( handleSize < $('theSlider_pop').getDimensions().height)
	{
		$('theHandle_pop').setStyle({height:handleSize+"px"});
		
		theSlider_popNew = new Control.Slider('theHandle_pop', 'theSlider_pop', {
			  axis:'vertical',
			  range: $R(0, 1),
			  sliderValue: 0,
			  onSlide: function(value) {
				$('news_content').scrollTop = value*scrollTopFactor_pop;
			  },
			  onChange: function(value) {
				$('news_content').scrollTop = value*scrollTopFactor_pop;
			  }
		 });
	}
	else{
		$('theHandle_pop').hide();	
	}
}
*/

function slideIt(value,eltId){
	$(eltId).scrollTop = value*scrollTopFactor;
	//$(eltId).scrollTop = value*scrollTopFactor;
}

function newsStep(e,dir){
	var step = dir*200; //was 250
	
	var maxScrollTop = $('allNewsContainer').down().getDimensions().height - $('allNewsContainer').getDimensions().height;
	if(($('allNewsContainer').scrollTop+step)<scrollTopFactor){
		$('allNewsContainer').scrollTop+=step;
	}
	else{
		$('allNewsContainer').scrollTop = scrollTopFactor;
	}
	
	theSlider.setValue($('allNewsContainer').scrollTop/maxScrollTop);
}

function grabNews(_label){
	$("theSlider_pop_news").hide();
	
	var url = 'scripts/php/responder.php';
	//var params = {action:'saveContent', label:_label, fieldsList:{text_fr:$('fr_content').value,text_en:$('en_content').value}}
	var params = {action:'grabNews', label:_label};
	
	$('news_content').update("<center width='100%'><img src='img/blank.gif' width='640px' height='1px;'/><br /><br /><img src='img/loading_03.gif' /></center>");
	$('news_title').update('...');
	
	new Ajax.Request(url, {
	  method: 'post',
	  
	  onSuccess: grabNewsSuccess,
	  parameters : params
	});
	
	currentNews   = newsArray.indexOf(_label);
	newsArraySize = newsArray.size();
}

function grabNewsSuccess(answer){
			
		var newsObj = answer.responseText.evalJSON();
		
		$('news_title').update(newsObj.title);
		$('news_content').update('<div>'+newsObj.content+'</div>');
		$('news_popup').show();	
		
		checkHandlePopNewsNeeded();
		registerNewsImagesToLoad();
		
		//if we want to hide arrows when no news on left of right//
		//alert(currentNews);
		if(currentNews >= (newsArraySize-1)){$('popup_news_left_arrow').hide();}
		else{$('popup_news_left_arrow').show();}
		
		if(currentNews <= 0){$('popup_news_right_arrow').hide();}
		else{$('popup_news_right_arrow').show();}
		//alert('News Indisponibles / News Unavailable');	
		
		//alert($('news_content').getDimensions().height);
		
		//checkHandlePopNeed('news_content',theSlider_popNew); //rr404 make it work !
}

function changeNews(change_step){
	currentNews = (currentNews + change_step)%newsArraySize;
	
	while(currentNews < 0){
		currentNews = newsArraySize + currentNews;
	}
	
	grabNews(newsArray[currentNews]);
}

/*
popDivRequest(_title,_content)
possible params :
("this is a title","this si a content")
("this is a title",{url:"http://urlOfContent"})
*/
function popDivRequest(_title,_content){
	var contentObj = _content.evalJSON();
	if(contentObj != null) _content = contentObj;
	
	if(_content.url != null){
		
		new Ajax.Request(_content.url, {
		  method: 'post',
		  onSuccess: function(answer){popDiv(_title,answer.responseText);}
		});
	}
	else{
		popDiv(_title,_content);	
	}
}

function popDiv(_title,_content){
	if((_title != null) && (_content != null)){
		$('pop_div_title').update(_title);
		$('pop_div_content').update(_content);
		$('pop_div').show();
		checkHandlePopDivNeeded();
	}
}

/* for detail display in right section */

function showDetails(e){
	var thisElt = Event.element(e);
	//alert(thisElt.innerHTML);
	var detailsContainer = thisElt.next('.v5hidden_left');
	//alert(detailsContainer);
	//alert('got details:'+detailsContainer);
	currentHiddenLeft = detailsContainer;
	
	$('right_content').update(detailsContainer.innerHTML);
	//alert('updated');
}

function grabClientComment(clientLabel){
	var url = 'scripts/php/responder.php';
	//var params = {action:'saveContent', label:_label, fieldsList:{text_fr:$('fr_content').value,text_en:$('en_content').value}}
	var params = {action:'grabClientComment', label:clientLabel};
		
	new Ajax.Request(url, {
	  method: 'post',
	  
	  onSuccess: grabClientCommentSuccess,
	  parameters : params
	});
}

function grabClientCommentSuccess(answer){
		$('ref_details').update(answer.responseText);
}

function setSelected(e){
	var theElt = Event.element(e);
	if(lastSelectedReference != null){
		try{
			lastSelectedReference.removeClassName("v5reference_cell_selected");
			lastSelectedReference.addClassName("v5reference_cell");
		}
		catch(err){
			
		}
	};
	
	try{
		theElt.removeClassName("v5reference_cell");
		theElt.addClassName("v5reference_cell_selected");
	}
	catch(err)
	{
		
	}
	
	lastSelectedReference = theElt;
}


/*contact form functions */
function toggle_devis(_visible){
		var display_devis;
		
		if(_visible == undefined) display_devis = $('c_isdevis').checked;
		else display_devis = _visible;
		
		if(display_devis){
			$('proj_title_row').show();
			$('proj_type_row').show();
			$('proj_files_row').show();
		}
		else{
			$('proj_title_row').hide();
			$('proj_type_row').hide();
			$('proj_files_row').hide();
		}
}

function addFileInput(){
	var divNameRoot = "proj_file_";

	var d = new Date();
	var newDivName = divNameRoot+d.getTime();
	
	var newDivHTML = "";
	
	
	newDivHTML +='<div id="'+newDivName+'">';
	newDivHTML +='<table><tr><td width="220px"><div class="fileinputs" width="250px">';
	newDivHTML +='<input type="file" class="file" onchange="$(\'fake_'+newDivName+'\').value = this.value" name="c_files[]"/>';
	//newDivHTML +='<input type="file" class="file" onchange="$(\'fake_'+newDivName+'\').value = this.value" name="c_files" />';
	newDivHTML +='<div class="fakefile" style="width:250px;">';
	newDivHTML +='<input id="fake_'+newDivName+'" style="border:1px solid #111111;width:152px;" />';
	newDivHTML +='</div></div></td>';
	newDivHTML +='<td valign="middle"><div style="cursor:pointer;" onclick="fRemove(\''+newDivName+'\')">(-) suppr</div></td>';
	newDivHTML +='</tr></table></div>';
	
	$('theFiles').insert(newDivHTML);
}

function fRemove(_fName){
	var toRem = $(_fName);
	$('theFiles').removeChild(toRem);	
}


/**/
function echeck(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   //alert("Invalid E-mail ID")
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   //alert("Invalid E-mail ID")
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		//alert("Invalid E-mail ID")
		return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		//alert("Invalid E-mail ID")
		return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		//alert("Invalid E-mail ID")
		return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		//alert("Invalid E-mail ID")
		return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
		//alert("Invalid E-mail ID")
		return false;
	 }

	 return true;					
}

/*************
***************************
Fonction de défilement des CP
*****************************
*******************/

var refPresseArray = new Array();
var currentPressIndex = 0;
var nbPressRefToDisplay = 6;
var refTableSize = "610";
var cellSize = refTableSize/nbPressRefToDisplay;

function getPresseRef(){
	var url = 'scripts/php/responder.php';
	var params = {action:'browsePresseClient'};
		
	new Ajax.Request(url, {
	  method: 'post',	  
	  onSuccess: browseSuccess,
	  parameters : params
	});
	
}

function browseSuccess(answer){
	var r = answer.responseText.evalJSON();
	refPresseArray = r.tabArray;	
	
	if(refPresseArray.length<nbPressRefToDisplay){
		cellSize = refTableSize/refPresseArray.length;
		nbPressRefToDisplay = refPresseArray.length;
	}
	
	displayPressRef(null)
}

function displayPressRef(_sens){
	if((_sens != null) && (currentPressIndex + _sens + nbPressRefToDisplay <= refPresseArray.length) && (currentPressIndex >=0)) currentPressIndex += _sens;
		
	//alert(currentPressIndex);
	//var _max = 0;
	var _min = currentPressIndex;
	var displayCode = '';
	
	var isFirstCellArrow = new Boolean(false);
	var isLastCellArrow = new Boolean(false);
	var nbImgCell = nbPressRefToDisplay;
	
	if(currentPressIndex>0) {
		isFirstCellArrow = true;
		_min += (1*_sens);
		nbImgCell--;
	}
	if(_min + nbImgCell < refPresseArray.length){
		isLastCellArrow = true;
		nbImgCell--;
	}
	 
	displayCode = '<table cellpadding="0" border="0" width="100%"><tr align="center">';
	
	if(isFirstCellArrow==true) displayCode += '<td width="'+cellSize+'" align="center"><img src="./img/ref_content/minus_arrow.png" onclick="javascript:displayPressRef(-1);" style="cursor:pointer"/></td>';
	
	for(var i=_min; i<_min+nbImgCell;i++){
		displayCode += ('<td width="'+cellSize+'" align="center">');
		if(refPresseArray[i]['type']=="web"){
			displayCode += ('<a href="'+refPresseArray[i]["link"]+'" target="_blank">');
		}
		else if(refPresseArray[i]['type']=="img"){
			displayCode += ('<a href="./img/ref_content/'+refPresseArray[i]["link"]+'" rel="lightbox" title="'+refPresseArray[i]["nom"]+'">');
		}
		else if(refPresseArray[i]['type']=="pdf"){
			displayCode += ('<a href="./img/ref_content/'+refPresseArray[i]["link"]+'" target="_blank">');
		}
		displayCode += ('<img src="./img/ref_logo/'+refPresseArray[i]["img_thb"]+'" width="80px" height="100px"/></a>');
		displayCode += ('</td>');
	}
	
	if(isLastCellArrow==true) displayCode += '<td width="'+cellSize+'" align="center"><img src="./img/ref_content/plus_arrow.png" onclick="javascript:displayPressRef(1);" style="cursor:pointer"/>';
	
	displayCode += '</td></tr></table>';
	
	
	$('presseRef').update(displayCode);
	initLightbox();
	

}

/*********************/


/************************************************************
* Fonction d'appel d'ouverture d'une fenetre depuis FLASH
*************************************************************/

function openExemple(_url,_w,_h){
	//alert("url : "+_url+", width : "+_w+", Height : "+_h);
	var _params = "menubar=no, status=no, scrollbars=no, menubar=no";
	if(_w!=0) _params+=", width="+_w;
	if(_h!=0) _params+=", height="+_h;
	window.open(_url,'TEST', _params);
}

/* Image Swap functions */
function preload_header_tabs(){
	MM_preloadImages('img/buttons/accueil_over_fr.png','img/buttons/immobilier_over_fr.png','img/buttons/communication_over_fr.png','img/buttons/solutions_over_fr.png','img/buttons/references_over_fr.png','img/buttons/contact_over_fr.png','img/buttons/accueil_over_en.png','img/buttons/immobilier_over_en.png','img/buttons/communication_over_en.png','img/buttons/solutions_over_en.png','img/buttons/references_over_en.png','img/buttons/contact_over_en.png','img/buttons/newspop_fermer_over_fr.gif','img/buttons/newspop_fermer_over_en.gif','img/buttons/newspop_left_over.gif','img/buttons/newspop_right_over.gif','img/buttons/bo_add_news_over.gif');
}

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_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_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_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];}
}
