//Conteneur de valeur de parametre
var parameterList = new Array();

// variable to handle expansion, so we can't skip steps!!
var isReady = 1;
var getPrice = 0;

function stepItemParameter( lmname, lmvalue )
{
this.paramName  = lmname;
this.paramValue = lmvalue;
}

/**
*
* Permet de gerer la liste des etapes. ( parametres collectes + depli / repli des etapes )
* 
**/
function StepList()
{
this.parameterList = new Array();
this.steps         = new Array();
this.steps[0]      = 'TpStepSearchPhoto';
this.steps[1]      = 'TpStepChoixFormat';
this.steps[2]      = 'TpStepChoixOptions';
this.steps[3]      = 'TpStepTableauPersoFin';
this.currentStep   = this.steps[0];

	//Ajoute un parametre lparamName avec pour valeur lparamValue a la liste 
	this.addParameter = function( lparamName, lparamValue ){
	
		var currentP    = new stepItemParameter( lparamName, lparamValue );
		var paramnumber = this.getParameterNumber( lparamName );
		
		if( paramnumber != -1 )
		{
		window['parameterList'][ paramnumber ] = currentP;
		}
		else
		{
		window['parameterList'].push( currentP );
		}
	}

	//Retourne vrai si la liste contient lpname
	this.hasParameter = function( lpname ){
	
		for( var i=0; i< window['parameterList'].length; i++ )
		{
			if( window['parameterList'][i].paramName == lpname )
			{
			return true;
			}
		}
		
		return false;
	}
	
	//Retourne la valeur d'un parametre lpname ou false si le parametre nexiste pas
	this.getParameter = function( lpname ){
		
		for( var i=0; i< window['parameterList'].length; i++ )
		{
			if( window['parameterList'][i].paramName == lpname )
			{
			return window['parameterList'][i].paramValue;
			}
		}
		
		return false;
	}
	
	//Retourne le numero d'un parametre paramname
	this.getParameterNumber = function( paramname ){
		
		for( var i=0; i< window['parameterList'].length; i++ )
		{
			if( window['parameterList'][i].paramName == paramname )
			{
			return i;
			}
		}
	
	return -1;
	}
	
	//Retourne la valeur d'un parametre pour le numero lNUMP
	this.getParameterValueForNo = function( lNUMP ){
		if( lNUMP < this.getNbParameter() )
		{
		return window['parameterList'][lNUMP].paramValue ;
		}
		else
		{
		return false;
		}
	}
	
	//Retourne le nombre de parametre de la liste
	this.getNbParameter= function()	{
	return window['parameterList'].length;
	}
	
	//Transforme la liste en URL
	this.makeAsUrl = function(){
	
	var lcurrentStr ="";
	
		for( var i=0; i< window['parameterList'].length; i++ )
		{
		var separator = ( i < ( window['parameterList'].length - 1 ) ) ? '&' : '';
		lcurrentStr += window['parameterList'][i].paramName+"="+escape( window['parameterList'][i].paramValue )+separator;
		
		}
		
	return lcurrentStr;
	}
	
	this.getCurrentStepNum = function()	{
	
		for( var d =0; d < this.steps.length; d++ )
		{
			if( this.currentStep == this.steps[d] )
			{
			return d;
			}
		}
		
		return -1;
	}
	
	this.gotoNextStep = function(){
  	if(isReady == 1) {
  	  isReady = 0;
  	  var nextStepName = this.getNextStepName();
  		if( nextStepName != false )
  		{
  		cl($(this.currentStep+'-content'));
  		cc($(this.currentStep+'-header'),'');
  	
  		ex($(nextStepName+'-content'));
  		n=$(nextStepName+'-header');
  		cc(n,'__');
  		n.className=n.className+' '+n.tc;
  		$(this.currentStep+"-statusIcon").className = "stepStatusIconOk";
  
  		// invalider ici si impacte sur la suite
      if( this.currentStep != "TpStepStyle") {
        this.invalidateNextSteps( this.currentStep );
      }
      		
  		this.currentStep = nextStepName;
      dspRightPanText(nextStepName);
  		  		

  		// adding status "in progress"
      if( $( this.currentStep+"-statusIcon").className != "stepStatusIconOk" ) {
        $( this.currentStep+"-statusIcon").className = "stepStatusIconEnCours";
  		}
  		
  		}
  	}
  	
    // Recharge le bouton sur la requete ajax de l'étape final pour l'aperçut du prix du
    // produit en cour de création 
    // recharge que quand arriv� � la fin  
		if( this.getCurrentStepNum() == (this.steps.length - 1) || getPrice == 1 ) {
      getCurrentProductPriceValue();
      getPrice = 1;
    }
    	ActualiseBuildedProduct();

  	}
	
	
	this.gotoPrevStep = function(){
	/*
	var prevStepName = this.currentStep;
	
		if( nextStepName != false )
		{
		cl($(this.currentStep+'-content'));
		cc($(this.currentStep+'-header'),'');
		
		ex($(prevStepName+'-content'));
		n=$(prevStepName+'-header');
		cc(n,'__');
		n.className=n.className+' '+n.tc;
		$(this.currentStep+"-statusIcon").className = "stepStatusIconOk";
		this.currentStep = nextStepName;
		}*/
	}
	
	this.getNextStepName = function(){
	
	var sNum = this.getCurrentStepNum();
		
		if( ( sNum + 1 ) < this.steps.length )
		{
		return this.steps[sNum + 1];
		}
		
	return false;
	}
	
	this.setCurrentStep  = function( lstepname ){
	this.currentStep = lstepname;
	}
	
	this.expandFirstStep = function(){
	
	var nextStepName = this.steps[0];
	
	cl($(this.currentStep+'-content'));
	cc($(this.currentStep+'-header'),'');
	
	ex($(nextStepName+'-content'));
	n=$(nextStepName+'-header');
	cc(n,'__');
	n.className=n.className+' '+n.tc;
	
	this.currentStep = nextStepName;
	dspRightPanText(nextStepName);
	
	$( this.currentStep+"-statusIcon").className = "stepStatusIconEnCours";
	}
	
	this.getStepPos = function( stepName ){
	
		for( var d =0; d < this.steps.length; d++ )
		{
			if( this.steps[d] == stepName )
			{
			return d;
			}
			//getStepPos
		}
		
	return false;
	}
	
  this.invalidateNextSteps = function( stepname ){

  var posOfStep = this.getStepPos( stepname );
  var nbOfParams = this.getNbParameter();
  var tempArray = new Array();
  var j = 0;

  if( nbOfParams > (posOfStep + 1) ) {
    for( var i= 0; i<= posOfStep; i++ )
    {
      tempArray[j] = window['parameterList'][i];
            j++;
    }
    window['parameterList'] = tempArray;
  }
  
    for( var de = (posOfStep + 1); de <= this.steps.length ; de++ )
    {
      if($( this.steps[de]+"-statusIcon")) $( this.steps[de]+"-statusIcon").className = "stepStatusIconNoOk";
    }
  }
  
	this.getCurrentStepName = function(){
	
	return this.currentStep;
	
	}
}


var stepListObject = new StepList();

function changeSearchPhotoPopupContentBy( lotherpath )
{
	$('previewMainPicFile').src=lotherpath;
}

function agrandirEspaceAccordian( lagrandi )
{
	var currentHeight = $('TpStepSearchPhoto-content').style.height.replace('px', '');
	var newsize       = parseFloat( currentHeight ) + parseFloat( lagrandi );
	
	/*$('infos').innerHTML += 'Taille actuelle :'+currentHeight;
	$('infos').innerHTML += 'demande agrandissement de :'+lagrandi;
	$('infos').innerHTML += 'nouvelle taille  :'+newsize;
	*/
	//$('infos').innerHTML = 'Taille actuelle :'+currentHeight;
	
	$('TpStepSearchPhoto-content').style.height = newsize;
	
	//Permet d'informer l'accorion pour ce qui est de la taille a afficher.
	$('TpStepSearchPhoto-content').maxh         = newsize;
}

function clickOnPieceOfHouse( lwichid, lcatname, lpage )
{
	$('critere_piece_of_house').innerHTML = lcatname;
	if(lpage == null) lpage = 1;
	new Ajax.Updater(
	    'creation_tablo_droite',
	    '/TpStepManagement/AjaxGetPicturesForCat',
	    {
	        method: 'get',
	        parameters: {cat_id:lwichid,page:lpage}
	    }
	); 	
}


function loadPieceOfHouseForCat( lcatid )
{
	new Ajax.Updater(
	    'roomOfHouseContent',
	    '/TpStepManagement/AjaxGetRoomOfHouseForCat',
	    {
	        method: 'get',
	        evalScripts: true,
	        parameters: {cat_id:lcatid}
	    }
	);
}

function clickChangePage( lwichid, lcatname, lpage )
{
	$('critere_piece_of_house').innerHTML = lcatname;
	if(lpage == null) lpage = 1;
	new Ajax.Updater(
	    'creation_tablo_droite',
	    '/TpStepManagement/AjaxGetPicturesForCat',
	    {
	        method: 'get',
	        parameters: {cat_id:lwichid,page:lpage}
	    }
	); 	
}

function click_sur_cat(catid, lcatname, lpage, total)
{
	// $('roomOfHouseContent').innerHTML =' pi&egrave;ce de la maison de '+catid;
  
	if(lpage == null) lpage = 1;
	
	if( $('imgcat'+catid).className == 'plus' )
	{
	
	expander = $$(".nom_criteres img");
	for(i=0;i<expander.length;i++)
	{
	  if( expander[i].className = "moins" ) 
	    change_img( expander[i].identify().substr(6) );
	}

	$('critere_category').innerHTML = lcatname;
	$('critere_piece_of_house').innerHTML = 'Aucune';
	
		loadPieceOfHouseForCat( catid );
		new Ajax.Updater(
		    'creation_tablo_droite',
		    '/TpStepManagement/AjaxGetPicturesForCat',
		    {
		        method: 'get',
		        parameters: {cat_id:catid,page:lpage}
		    }
		);
	}

	change_img(catid);
	deroul_etap(catid);

}


function click_sur_sous_cat(catid, lcatname)
{
	if( $('imgcat'+catid).className == 'plus' )
	{
	$('critere_category').innerHTML = lcatname;
	$('critere_piece_of_house').innerHTML = 'Aucune';
	loadPieceOfHouseForCat( catid );
	new Ajax.Updater(
	    'creation_tablo_droite',
	    '/TpStepManagement/AjaxGetPicturesForCat',
	    {
	        method: 'get',
	        parameters: {cat_id:catid}
	    }
	); 	
	}

change_img_souscat(catid);

}



function change_img(seid)
{
	var idLigne = seid;

	if($('imgcat'+idLigne).className == 'plus' )
	{
	
		$('imgcat'+idLigne).className = "moins";
		$( 'imgcat'+idLigne ).src	  = '/images/tablo/tablo_deco/tablo_croix.gif';

	}
	else if( $('imgcat'+idLigne).className == 'moins' )
	{
		$( 'imgcat'+idLigne ).src	  = '/images/tablo/tablo_deco/tablo_plus.gif';
		$('imgcat'+idLigne).className = 'plus';
	
	}
}

function change_img_souscat(seid)
{
	var idLigne = seid;

	if($('imgcat'+idLigne).className == 'plus' )
	{
	
		$('imgcat'+idLigne).className = "moins"
		$( 'imgcat'+idLigne ).src	  = '/images/tablo/tablo_deco/tablo_croix.gif';

	}
	else if( $('imgcat'+idLigne).className == 'moins' )
	{
		$( 'imgcat'+idLigne ).src	  = '/images/tablo/tablo_deco/tablo_blanc.gif';
		$('imgcat'+idLigne).className = 'plus' 
	
	}
}
	
function deroul_etap(seid)
{
	var idLigne = seid;
	//compter nombre de cat, agrandirEspaceAccordian
	var lNbOfItems = $('souscatrow'+idLigne).getElementsByClassName('critere_detail').length;
	
	if($('souscatrow'+idLigne).style.display	=='block')
	{
		$('souscatrow'+idLigne).style.display	='none';
		agrandirEspaceAccordian( parseInt( -lNbOfItems ) * 15 );
	}
	else
	{
		$('souscatrow'+idLigne).style.display	='block';
		agrandirEspaceAccordian( parseInt( lNbOfItems ) * 15 );
	}
}
	
function hidePopupSearchPhoto()
{
   $('TpPopupImg').style.display = 'none';
   currentGenericPopup.hideAllItems();
   
}
	
function showPopupSearchPhoto()
{
   $('TpPopupImg').style.display = 'block';
}

function searchPopupIsVisible()
{
return  $('TpPopupImg').style.display == 'block';
}
	
	
function open_popup_img(name_img)
{
	var popupManager = new TpGenericPopupManager();
	popupManager.startPlacingPopup( 730, 540 );
	
	popupManager.addPopupItemHorizontal( $('TpPopupImg'), 715, 530 );
	popupManager.endPlacingPopup();
	//popupManager.setCloseBehavior( true );
	popupManager.customDisplayItemMethod = function( elt ){
				$(elt).style.display = 'block';
	}
	popupManager.customHideItemMethod = function( elt ){
					$(elt).style.display = 'none';
	}
	
	new Ajax.Updater(
	    'TpPopupImg',
	    '/TpStepManagement/AjaxPopupImg',
	    {
	        method: 'get',
	        parameters: {id_img:name_img},
	        onComplete: function( xhr ){
	        	popupManager.showItems();
	        }
	    }
	); 

//showPopupSearchPhoto();
}


function searchChoosePhoto( lphid )
{
	if( searchPopupIsVisible() )
	{
	currentGenericPopup.hideAllItems();
	//hidePopupSearchPhoto();
	}

$('creation_tablo_droite').innerHTML = ' ';
parameterChoosed( 'search_photo_id', lphid );
stepListObject.gotoNextStep();


}

//This function try to hide the popup when the user click somewhere else
function tryToHideSearchPhotoPopup(e)
{
	if( searchPopupIsVisible() )
	{
		var popupH     = $('TpPopupImg').offsetHeight,
		    popupW     = $('TpPopupImg').offsetWidth,
		    popupY     = $('TpPopupImg').style.top.replace( 'px', ''),
		    popupX     = $('TpPopupImg').style.left.replace( 'px', '');
		
		var element    = Event.element(e);
		var mouseX     = Event.pointerX(e),
		    mouseY     = Event.pointerY(e);

		var popupendX  = parseInt( popupX ) + parseInt( popupW ) ; 
		var popupendY  = parseInt( popupY ) + parseInt( popupH ) ; 
		
		//If mouse is not in the popup, this is a ask for hiding it
		if( 
			!(
			 ( mouseY > popupY && mouseY < popupendY )
			&&
			 ( mouseX > popupX && mouseX < popupendX )
			 )
			&&
			( ( popupendX != popupX ) && ( popupendY != popupY ) )
		)
		{
			hidePopupSearchPhoto();
		}
	}
}

function getTopPhotoToRightPan(){
	new Ajax.Updater(
		    'creation_tablo_droite',
		    '/TpStepManagement/AjaxGetTopPicturesForCat',
		    {
		        method: 'get',
		       parameters: {idConcept:returnConceptId()}
		    }
		);
	
}



function Timer() {
       //var dt=new Date()
       //window.status=dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds();
      getTopPhotoToRightPan();
       //alert('oli');
   }
window.setTimeout(Timer,1000);
Event.observe( window.document.body, 'click', tryToHideSearchPhotoPopup, false );//consthtml : HtmlTpStepSearchPhoto
//consthtml : HtmlTpStepChoixFormat
function optVueChezVousClick(status)
{
//vueChezVousDetail
//lOptVueChezVous
	if( status == 'yes' )
	{
	window.open( '/TpStepManagement/ShowPopupOptVueChezVous',"nom_popup","menubar=no, status=no, scrollbars=no, menubar=no, width=400, height=400");
	}
	else
	{
		parameterChoosed( 'opt_vue_chez_vous_checked', 0 );
	}
}


function optRetirageClick(status)
{
	if( status == "yes" )
	{
		parameterChoosed( 'opt_retirage_choosed', 1 );
	}
	else
	{
		parameterChoosed( 'opt_retirage_choosed', 0 );
	}
}


function optNumeriqueClick(status)
{
  if( status == 'yes' )
	{
		parameterChoosed( 'opt_numerique_choosed', 1 );
		alert('numerique choisit ');
	}
	else
	{
		parameterChoosed( 'opt_numerique_choosed', 0 );
	}
}

//Fonction appele lorsque la popup vue chez vous se ferme
function confirmVueChezVousImageReception()
{
	parameterChoosed( 'opt_vue_chez_vous_checked', 1 );
	//alert('confirmVueChezVousImageReception');
}//consthtml : HtmlTpStepChoixOptions
function getCurrentProductPriceValue()
{
	new Ajax.Updater(
	'lproduct_price',
	'/TpStepManagement/GetProductPriceValue',
	 {
	 	method: 'get',
	 	onComplete: function(xhr){
	 		$('montableau').style.display='none';
	 		$('resultatPrice').style.display='block';
	 		$('resultatPrice').innerHTML= xhr.responseText;
	 	}
	 }
	
	);

}//consthtml : HtmlTpStepTableauPersoFin
//Fin code aditionel

	function choixSearchPhotoParameterChanged()
	{
	alert('open choix style');
	}
	function choixFormatParameterChanged()
	{
	alert('open choix format');
	}
	function nofunction()
	{
	stepListObject.addParameter( 'options_choosed', '1' );
parameterChoosed( 'options_choosed', '1' );
	}
	function choixOptionParameterChanged()
	{
	
new Ajax.Updater(
	'ChoixFaceDiv',
	'/TpStepManagement/AjaxGetHtmlChoixFace',
	{
		method: 'get',
		parameters: {support_format_id:stepListObject.getParameter( 'support_format_id' )}
		//insertion: Insertion.Bottom
	}
);

	}

function liveUpdateParameter( pname, pv )
{
new Ajax.Request(
	'/TpStepManagement/UpdateParameterValue',
	{
		method: 'post',
		parameters: {pname: pname, pvalue: pv}
	}
);

}

function parameterChoosed( lparamName, lparamValue )
{
	//Pour eviter de prevenir les etapes d'un "non changement de valeur"
	if( !stepListObject.hasParameter( lparamName ) || ( lparamValue != stepListObject.getParameter( lparamName ) ))
	{
	stepListObject.addParameter( lparamName, lparamValue );
	parameterHasBeenModified( lparamName, lparamValue );
		liveUpdateParameter( lparamName, lparamValue );
		}
}

function parameterHasBeenModified( lparamName, lparamValue )
{

			if( lparamName == 'search_photo_id' ){
				//step : Recherche is not interested by search_photo_id 
				//step : Sélection du format avec recherche is not interested by search_photo_id 
				//step : Options avec format is not interested by search_photo_id 
				//step : Finalisation avec option is not interested by search_photo_id 
				}
				if( lparamName == 'support_format_id' ){
				//step : Recherche is not interested by support_format_id 
				//step : Sélection du format avec recherche is not interested by support_format_id 
				//step : Options avec format is not interested by support_format_id 
				//step : Finalisation avec option is not interested by support_format_id 
				}
				if( lparamName == 'product_bat' ){
				//step : Recherche is not interested by product_bat 
				//step : Sélection du format avec recherche is not interested by product_bat 
				//step : Options avec format is not interested by product_bat 
				//step : Finalisation avec option is not interested by product_bat 
				}
				if( lparamName == 'options_choosed' ){
				//step : Recherche is not interested by options_choosed 
				//step : Sélection du format avec recherche is not interested by options_choosed 
				//step : Options avec format is not interested by options_choosed 
				//step : Finalisation avec option is not interested by options_choosed 
				}
				if( lparamName == 'vue_chez_vous_f1' ){
				//step : Recherche is not interested by vue_chez_vous_f1 
				//step : Sélection du format avec recherche is not interested by vue_chez_vous_f1 
				//step : Options avec format is not interested by vue_chez_vous_f1 
				//step : Finalisation avec option is not interested by vue_chez_vous_f1 
				}
				if( lparamName == 'vue_chez_vous_f2' ){
				//step : Recherche is not interested by vue_chez_vous_f2 
				//step : Sélection du format avec recherche is not interested by vue_chez_vous_f2 
				//step : Options avec format is not interested by vue_chez_vous_f2 
				//step : Finalisation avec option is not interested by vue_chez_vous_f2 
				}
				if( lparamName == 'opt_vue_chez_vous_checked' ){
				//step : Recherche is not interested by opt_vue_chez_vous_checked 
				//step : Sélection du format avec recherche is not interested by opt_vue_chez_vous_checked 
				//step : Options avec format is not interested by opt_vue_chez_vous_checked 
				//step : Finalisation avec option is not interested by opt_vue_chez_vous_checked 
				}
				if( lparamName == 'opt_numerique_choosed' ){
				//step : Recherche is not interested by opt_numerique_choosed 
				//step : Sélection du format avec recherche is not interested by opt_numerique_choosed 
				//step : Options avec format is not interested by opt_numerique_choosed 
				//step : Finalisation avec option is not interested by opt_numerique_choosed 
				}
		}

//TODO pour chaque etape, tester si collecte lpname, etendre etape et afficher message
function expandParameterStepForP( lpname )
{

$('infos').innerHTML += " <br /> detetection de letape qui possede : "+lpname;


$('infos').innerHTML += " <br /> aucune etape collecte : "+lpname;

}


//Retourne vrai si litem peut etre etendu
function AccordionItemExpandHandler( litem )
{
var lstepExpandId = litem.id;
var lstepName 	  = lstepExpandId.substring( 0, lstepExpandId.indexOf( "-", 0 ) );
// dspRightPanText(lstepName);
//$('infos').innerHTML += "<br />Expansion de "+litem.id;
//$('infos').innerHTML += " <br /> Step expanded = "+lstepName;

		if( lstepName == 'TpStepSearchPhoto' )
		{
					}
		if( lstepName == 'TpStepChoixFormat' )
		{
						
			//$param
			if( stepListObject.getParameter( 'search_photo_id' ) === false )
			{
			//$('infos').innerHTML += " <br /> Step non expanded : search_photo_id";
			
			alert('Parametre Recherche non rempli' );
			/*
			alert(stepListObject.getNbParameter());
			alert( stepListObject.getParameter( 'encadrement_id' )
             );
      alert( stepListObject.makeAsUrl()
             );
      */
			
			//expandParameterStepForP( 'search_photo_id' );
			return false;
			}
			else {
			  dspRightPanText(lstepName);
			}
					}
		if( lstepName == 'TpStepChoixOptions' )
		{
						
			//$param
			if( stepListObject.getParameter( 'support_format_id' ) === false )
			{
			//$('infos').innerHTML += " <br /> Step non expanded : support_format_id";
			
			alert('Parametre Format non rempli' );
			/*
			alert(stepListObject.getNbParameter());
			alert( stepListObject.getParameter( 'encadrement_id' )
             );
      alert( stepListObject.makeAsUrl()
             );
      */
			
			//expandParameterStepForP( 'support_format_id' );
			return false;
			}
			else {
			  dspRightPanText(lstepName);
			}
					}
		if( lstepName == 'TpStepTableauPersoFin' )
		{
						
			//$param
			if( stepListObject.getParameter( 'options_choosed' ) === false )
			{
			//$('infos').innerHTML += " <br /> Step non expanded : options_choosed";
			
			alert('Parametre Options non rempli' );
			/*
			alert(stepListObject.getNbParameter());
			alert( stepListObject.getParameter( 'encadrement_id' )
             );
      alert( stepListObject.makeAsUrl()
             );
      */
			
			//expandParameterStepForP( 'options_choosed' );
			return false;
			}
			else {
			  dspRightPanText(lstepName);
			}
					}
// appel ici de la fonction qui invalide les �tapes suivante (obsol�te?)
// stepListObject.invalidateStepUntil( lstepName );

return true;
}

function makeStepListAsUrlTest(){
alert( stepListObject.makeAsUrl() );
}

function returnConceptId(){
return (15);	
}


function ActualiseBuildedProduct(){
		new Ajax.Request(
			'/TpStepManagement/AjaxActualiseBuildedProduct',
			{
				method: 'post',
				parameters: {BuildId: $('buildInConstruct').value}
			}
		);
}
