//- Copyright CADBow (c) 2007
//- Version 2007-09-29
//var bTest =true ;

function URLDecode (psEncodeString) {
	var lsRegExpEuro =/%80/g ;
	psEncodeString =String (psEncodeString).replace (lsRegExpEuro, "euro") ; //- "â‚¬"
	//psEncodeString =decodeURIComponent (psEncodeString) ;
	var lsRegExp =/\+/g ;
	return (unescape (String (psEncodeString).replace (lsRegExp, " "))) ; 
}

function FixNumbers (obj) {
	obj.value =obj.value.replace (/ /, '') ;
}

//- Class Pricer - Pricer
ExpPricer =new Class ({

	//- Core
	initialize: function () {
		this.currentStep =0 ;
		this.upStep =0 ;
		this.maxStep =iMaxStep - 1 ; //- because of step0
		this.waitPlz =new WaitPlz () ;
	},

	Go: function (step) {
		if ( step > this.currentStep ) {
			eval ('var bTest =step' + this.currentStep + '_validate();') ;
			if ( bTest == false )
				return ;
		}
		this.currentStep =step ;
		if ( this.currentStep > this.upStep )
			this.upStep =this.currentStep ;
		this._ShowWizardTab () ;
		this._ShowWizardStepNav () ;
		this._ShowWizardProgressBar () ;
		this._ShowNavButtons () ;
		eval ('step' + this.currentStep + '_initialize ();') ;
	},
	
	Step: function (step) {
		if ( step > 0 ) {
			eval ('var bTest =step' + this.currentStep + '_validate();') ;
			if ( bTest == false )
				return ;
		}
		this.currentStep +=step ;
		if ( this.currentStep > this.upStep )
			this.upStep =this.currentStep ;
		this._ShowWizardTab () ;
		this._ShowWizardStepNav () ;
		this._ShowWizardProgressBar () ;
		this._ShowNavButtons () ;
		eval ('step' + this.currentStep + '_initialize ();') ;
	},
	
	Done: function () {
		window.location.reload (false) ;
	},
	
	_Save: function (code) {
		var data =new Object () ;
		for ( var i =0 ; i <= this.maxStep ; i++ ) {
			eval ('data =step' + i + '_grabData(data);') ;
		}
		//alert (Json.toString (data)) ;
		AjaxRequest.post (
			{
				'url' : 'index.php',
				'cmd' : 'ExpPricer',
				'arg' : 'SaveX',
				'code': code,
				'data' : Json.toString (data),
				'onSuccess' : function (req) {},
				'onError' : function (ret) {}
			}
		) ;
		//window.location="index.php?cmd=ExpPricer&arg=SaveX&data=" + Json.toString (data) ;
	},

	Calculate: function () {
		var data =new Object () ;
		for ( var i =0 ; i <= this.maxStep ; i++ ) {
			eval ('data =step' + i + '_grabData(data);') ;
		}
		$('ResultsTab').addClass ('HideElement') ;
		$('ErrorTab').addClass ('HideElement') ;
		this.waitPlz.Display ('Merci de patienter...') ;
		AjaxRequest.post (
			{
				'url' : 'index.php',
				'cmd' : 'ExpPricer',
				'arg' : 'CalcX',
				'data' : Json.toString (data),
				'onSuccess' : function (req) {
					oPricer.waitPlz.Hide () ;
					//	alert (req.responseText) ; return ;
					//	alert (req.responseText) ;
					var val ='' ;
					var data =Json.evaluate (req.responseText) ;
					if ( typeof (data) == 'string' ) {
						alert (URLDecode (data)) ;
						return ;
					}
					
					var nbc =(3 - parseInt (data ['counter']) + 1) + ' / 3' ;
					if ( parseInt (data ['counter']) > 3 )
						nbc ='1 / ' + data ['counter'] ;
					$('szCounter').setText (nbc) ;
					$('sz_left').setText (data ['counter']) ;
					if ( $defined (data ['expire']) )
						$('szTimeLimit').setText (' jusqu\'au ' + data ['expire']) ;
					else
						$('szTimeLimit').setText (' sans limitation dans le temps') ;

					$('res_nbtete').setText (data ['study'] == 'c' ? 2 : 1) ;
					if ( data ['study'] == 'c' ) {
						$('tete2').removeClass ('HideElement') ;
						$('tete2_rever').removeClass ('HideElement') ;
						$('res_sex1').setText (data ['sex_1'] == 0 ? 'Homme' : 'Femme') ;
						$('res_birthday1').setText (data ['birthday_1']) ;
						$('res_sex2').setText (data ['sex_2'] == 0 ? 'Homme' : 'Femme') ;
						$('res_birthday2').setText (data ['birthday_2']) ;
						val =parseFloat (data ['reversion']) ;
						$('res_reversion').setText (val <= 0 ? 'non' : 'oui à ' + val.toFixed (0)) ;
					} else {
						$('tete2').addClass ('HideElement') ;
						$('tete2_rever').addClass ('HideElement') ;
						$('res_sex1').setText (data ['sex'] == 0 ? 'Homme' : 'Femme') ;
						$('res_birthday1').setText (data ['birthday']) ;
					}
					switch ( parseInt (data ['regime']) ) {
						case 0: val ='Marié(e)' ; break ;
						case 1: val ='Pacsé(e)' ; break ;
						case 2: val ='Célibataire' ; break ;
						case 3: val ='Veuf(ve)' ; break ;
						case 4: val ='Divorcé(e)' ; break ;
					}
					$('res_email').setText (data ['email']) ;
					$('myID').value =data ['myID'] ;
					$('szMyID').setText (data ['myID']) ;
					$('new_email').value =data ['email'] ;
					$('res_regime').setText (val) ;					
					$('res_amount').setText (data ['sz_amount']) ;		//- parseInt (data ['amount'])
					$('res_bouquet').setText (data ['sz_bouquet']) ;	//- parseInt (data ['bouquet'])
					$('res_renteSt').setText (data ['cadre'] == 'a' ? 'Versements périodiques' : 'Rente') ;
					$('res_renteSt').setStyle ('font-weight', 'normal') ;
					$('res_rente').setText (data ['sz_rente']) ;		//- parseFloat (data ['rente']).toFixed (0)
					$('bouquetsubs').addClass ('HideElement') ;
					$('rentesubs').addClass ('HideElement') ;
					if ( data ['cadre'] == 'a' ) {
						$('res_bouquetsub1').setText (data ['sz_bouquetsub1']) ;
						$('res_bouquetsub2').setText (data ['sz_bouquetsub2']) ;
						$('bouquetsubs').removeClass ('HideElement') ;
						$('res_rentesub1').setText (data ['sz_rentesub1']) ;
						$('res_rentesub2').setText (data ['sz_rentesub2']) ;
						$('rentesubs').removeClass ('HideElement') ;
					}
					$('res_renteperiode').setText (data ['sz_periode']) ;
					$('res_yearrente').setText (data ['sz_yearrente']) ;//- parseFloat (data ['yearrente']).toFixed (0)
					$('res_tri').setText (parseFloat (data ['tri']).toFixed (2)) ;
					val =parseInt (data ['location']) ;					
					if ( !isNaN (val) )
						$('res_location').setHTML (val.toFixed (0) + '&nbsp;&euro; / mois') ;
					else
						$('res_location').setText ('non communiquée.') ;

					$('ResultsTab').removeClass ('HideElement') ;
					$('ErrorTab').addClass ('HideElement') ;
				},
				'onError' : function (ret) {
					alert (ret) ;
				}
			}
		) ;
			
	},
	
	ShowHelp: function (event) {
		CancelDelayHideContextMenu () ;
		var obj =$('hStep' + this.currentStep) ;
		obj.style.left =event.clientX - 620 + 15 ;
		obj.style.top =event.clientY - 15 ;
		obj.removeClass ('HideElement') ;
		
	},
	HideHelp: function () {
		$('hStep' + this.currentStep).addClass ('HideElement') ;
	},
	
	_ShowNavButtons: function () {
		if ( this.currentStep == 0 )
			$('StartButton').removeClass ('HideElement') ;
		else
			$('StartButton').addClass ('HideElement') ;
		if ( this.currentStep == this.maxStep )
			$('FinishButton').removeClass ('HideElement') ;
		else
			$('FinishButton').addClass ('HideElement') ;
		if ( this.currentStep == 0 || this.currentStep == 1 )
			$('PreviousButton').addClass ('HideElement') ;
		else
			$('PreviousButton').removeClass ('HideElement') ;
		if ( this.currentStep == 0 || this.currentStep >= this.maxStep )
			$('NextButton').addClass ('HideElement') ;
		else
			$('NextButton').removeClass ('HideElement') ;
	},
	
	_ShowWizardTab: function () {
		list =$('WizardsTabs').getElements ('div[id^=tStep]') ;
		for ( i =0 ; i < list.length ; i++ )
			list [i].addClass ('HideElement') ;
		if ( $('tStep' + this.currentStep) )
			$('tStep' + this.currentStep).removeClass ('HideElement') ;
	},
	
	_ShowWizardStepNav: function () {
		list =$('WizardsSteps').getElements ('img[id^=iStep]') ;
		for ( i =0 ; i < list.length && i <= this.upStep ; i++ ) {
			if ( list [i].style.cursor == 'pointer' )
				continue ;
			list [i].style.cursor ='pointer' ;
			list [i].src =szSite + 'pricers/images/exppricer/step' + i + '.gif' ;
			list [i].addEvent ('click', this._InternalGo.bind (this)) ;
		}
		//for ( ; i < list.length ; i++ )
		//	list [i].src =szSite + 'pricers/images/exppricer/step' + i + 'ro.gif' ;
	},
	
	_ShowWizardProgressBar: function () {
		var pct =100.0 * this.currentStep / this.maxStep ;
		$('PropertyDialogProgressBar').style.width =pct.toFixed (0) + '%' ;
		//if ( this.currentStep > this.maxStep - 2 )
			msg =pct.toFixed (0) + ' %' ;
		//else
		//	msg =  'Page ' + this.currentStep + ' sur ' + (this.maxStep - 2)
		//		 + ' (' + pct.toFixed (0) + ' %)' ;
		$('PropertyDialogProgressMeter').setText (msg) ;
	},
	
	_InternalGo: function (e) {
		//var re =new RegExp ('\\biStep([0-9]{1,2})\\b') ;
		//var m =re.exec (e.srcElement.id) ;
		if ( e.srcElement == undefined )
			this.Go (parseInt (e.target.id.substr (5))) ;
		else
			this.Go (parseInt (e.srcElement.id.substr (5))) ;
	}
	
});

//- Class WaitPlz - Wait Message
function WaitPlz () {

	//-Methods
	this.Display =Display ;
	this.Hide =Hide ;
	this.Error =Error ;

	//- Core
	function Display (msg) {
		$('AjaxWaitMsg').setText (msg) ;
		var obj =$('AjaxWaitPlz') ;
		obj.style.width =document.body.clientWidth ;
		obj.style.height =document.body.clientHeight ;
		obj.removeClass ('HideElement') ;
	}
	
	function Hide () {
		var obj =$('AjaxWaitPlz') ;
		obj.addClass ('HideElement') ;
	}
	
	function Error (ret) {
		alert (ret.responseText) ;
		this.Hide () ;
	}
}

function VerifyFreeCode () {
	var email =$('email').value ;
	var code =$('mycodeSt').value ;
	AjaxRequest.post (
		{
			'url' : 'index.php',
			'cmd' : 'ExpPricer',
			'arg' : 'VerifyFreeCode',
			'email' : email,
			'code' : code,
			'onSuccess' : function (req) {
				//alert (req.responseText) ; //return ;
				var bOk =( req.responseText.substr (0, 2) == 'ok' ) ;
				$('NextButton').disabled =!bOk ;
				if ( !bOk ) {
					alert ('Désolé votre code n\'est pas valide, veuillez contacter nos services.') ;
					$('NextMsg').addClass ('HideElement') ;
				} else {
					$('NextMsgCounter').setText (req.responseText.substr (3)) ;
					$('NextMsg').removeClass ('HideElement') ;
				}					
			},
			'onError' : function (ret) {
				alert (ret) ;
			}
		}
	) ;
}

function PreCreateCICPaiement (id, code, email) {
	AjaxRequest.post (
		{
			'url' : 'index.php',
			'cmd' : 'ExpPricer',
			'arg' : 'PreCreateCIC',
			'id' : id,
			'code' : code,
			'email' : email,
			'onSuccess' : function (req) {
				//alert (req.responseText) ; return ;
			},
			'onError' : function (ret) {
				alert (ret) ;
			}
		}
	) ;
}

function DetectCICPaiement (code) {
	AjaxRequest.post (
		{
			'url' : 'index.php',
			'cmd' : 'ExpPricer',
			'arg' : 'VerifyCIC',
			'code' : code,
			'onSuccess' : function (req) {
				//alert (req.responseText) ; return ;
				if ( req.responseText == 'ok' ) {
					$('NextButton').disabled =false ;
					$('paiementtab').removeClass ('HideElement') ;
					$('paypalwait').addClass ('HideElement') ;
					var custom =$('paypal_custom').value ;
					alert (
						  'Votre paiement nous est parvenu. Votre code d\'accès est : ' + custom
						+ ' (celui-ci est lié à votre compte email,\n'
						+ 'alors veuillez utiliser l\'email de votre compte email lors de votre prochaine visite.\n' 
						+ 'Pressez \'Suivant\' pour continuer.'
					) ;
				} else if ( oPricer.currentStep == 8 ) {
					var custom =$('paypal_custom').value ;
					setTimeout ('DetectCICPaiement ("' + custom + '")', 5000) ; //- Every 5 seconds
				}
			},
			'onError' : function (ret) {
				alert (ret) ;
			}
		}
	) ;
}

function DetectPaypalPaiement (code) {
	AjaxRequest.post (
		{
			'url' : 'index.php',
			'cmd' : 'ExpPricer',
			'arg' : 'VerifyPaypal',
			'code' : code,
			'onSuccess' : function (req) {
				//alert (req.responseText) ; return ;
				if ( req.responseText == 'ok' ) {
					$('NextButton').disabled =false ;
					$('paiementtab').removeClass ('HideElement') ;
					$('paypalwait').addClass ('HideElement') ;
					var custom =$('paypal_custom').value ;
					alert (
						  'Votre paiement nous est parvenu. Votre code d\'accès est : ' + custom
						+ ' (celui-ci est lié à votre compte paypal,\n'
						+ 'alors veuillez utiliser l\'email de votre compte paypal lors de votre prochaine visite.\n' 
						+ 'Pressez \'Suivant\' pour continuer.'
					) ;
				} else if ( oPricer.currentStep == 8 ) {
					var custom =$('paypal_custom').value ;
					setTimeout ('DetectPaypalPaiement ("' + custom + '")', 5000) ; //- Every 5 seconds
				}
			},
			'onError' : function (ret) {
				alert (ret) ;
			}
		}
	) ;
}

// ---------------------------------------------------------------------------|
// qryHowOld                                                                  |
// Description: How old someone is in the format:                             |
// XXX Years XX Months X Weeks X Days                                         |
// Birth Date could be specified like Date.UTC(2002,8,16,17,42,0)             |
//                                                                            |
// Arguments:                                                                 |
//    varAsOfDate: as of date                                                 |
//    varBirthDate: birth date                                                |
//                                                                            |
function qryHowOld(varAsOfDate, varBirthDate)
   {
   var dtAsOfDate;
   var dtBirth;
   var dtAnniversary;
   var intSpan;
   var intYears;
   var intMonths;
   var intWeeks;
   var intDays;
   var intHours;
   var intMinutes;
   var intSeconds;
   var strHowOld;

   // get born date
   dtBirth = new Date(varBirthDate);
   
   // get as of date
   dtAsOfDate = new Date(varAsOfDate);

   // if as of date is on or after born date
   if ( dtAsOfDate >= dtBirth )
      {

      // get time span between as of time and birth time
      intSpan = ( dtAsOfDate.getUTCHours() * 3600000 +
                  dtAsOfDate.getUTCMinutes() * 60000 +
                  dtAsOfDate.getUTCSeconds() * 1000    ) -
                ( dtBirth.getUTCHours() * 3600000 +
                  dtBirth.getUTCMinutes() * 60000 +
                  dtBirth.getUTCSeconds() * 1000       )

      // start at as of date and look backwards for anniversary 

      // if as of day (date) is after birth day (date) or
      //    as of day (date) is birth day (date) and
      //    as of time is on or after birth time
      if ( dtAsOfDate.getUTCDate() > dtBirth.getUTCDate() ||
           ( dtAsOfDate.getUTCDate() == dtBirth.getUTCDate() && intSpan >= 0 ) )
         {

         // most recent day (date) anniversary is in as of month
         dtAnniversary = 
            new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                dtAsOfDate.getUTCMonth(),
                                dtBirth.getUTCDate(),
                                dtBirth.getUTCHours(),
                                dtBirth.getUTCMinutes(),
                                dtBirth.getUTCSeconds() ) );

         }

      // if as of day (date) is before birth day (date) or
      //    as of day (date) is birth day (date) and
      //    as of time is before birth time
      else
         {

         // most recent day (date) anniversary is in month before as of month
         dtAnniversary = 
            new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                dtAsOfDate.getUTCMonth() - 1,
                                dtBirth.getUTCDate(),
                                dtBirth.getUTCHours(),
                                dtBirth.getUTCMinutes(),
                                dtBirth.getUTCSeconds() ) );

         // get previous month
         intMonths = dtAsOfDate.getUTCMonth() - 1;
         if ( intMonths == -1 )
            intMonths = 11;

         // while month is not what it is supposed to be (it will be higher)
         while ( dtAnniversary.getUTCMonth() != intMonths )

            // move back one day
            dtAnniversary.setUTCDate( dtAnniversary.getUTCDate() - 1 );

         }

      // if anniversary month is on or after birth month
      if ( dtAnniversary.getUTCMonth() >= dtBirth.getUTCMonth() )
         {

         // months elapsed is anniversary month - birth month
         intMonths = dtAnniversary.getUTCMonth() - dtBirth.getUTCMonth();

         // years elapsed is anniversary year - birth year
         intYears = dtAnniversary.getUTCFullYear() - dtBirth.getUTCFullYear();

         }

      // if birth month is after anniversary month
      else
         {

         // months elapsed is months left in birth year + anniversary month
         intMonths = (11 - dtBirth.getUTCMonth()) + dtAnniversary.getUTCMonth() + 1;

         // years elapsed is year before anniversary year - birth year
         intYears = (dtAnniversary.getUTCFullYear() - 1) - dtBirth.getUTCFullYear();

         }

      // to calculate weeks, days, hours, minutes and seconds
      // we can take the difference from anniversary date and as of date

      // get time span between two dates in milliseconds
      intSpan = dtAsOfDate - dtAnniversary;

      // get number of weeks
      intWeeks = Math.floor(intSpan / 604800000);

      // subtract weeks from time span
      intSpan = intSpan - (intWeeks * 604800000);
      
      // get number of days
      intDays = Math.floor(intSpan / 86400000);

      // subtract days from time span
      intSpan = intSpan - (intDays * 86400000);

      // get number of hours
      intHours = Math.floor(intSpan / 3600000);
    
      // subtract hours from time span
      intSpan = intSpan - (intHours * 3600000);

      // get number of minutes
      intMinutes = Math.floor(intSpan / 60000);

      // subtract minutes from time span
      intSpan = intSpan - (intMinutes * 60000);

      // get number of seconds
      intSeconds = Math.floor(intSpan / 1000);

      // create output string 
      strHowOld = intYears.toString() ;
      
      
      /*    
      if ( intYears > 0 )
         if ( intYears > 1 )
            strHowOld = intYears.toString() + ' Years';
         else
            strHowOld = intYears.toString() + ' Year';
      else
         strHowOld = '';

      if ( intMonths > 0 )
         if ( intMonths > 1 )
            strHowOld = strHowOld + ' ' + intMonths.toString() + ' Months';
         else
            strHowOld = strHowOld + ' ' + intMonths.toString() + ' Month';
           
      if ( intWeeks > 0 )
         if ( intWeeks > 1 )
            strHowOld = strHowOld + ' ' + intWeeks.toString() + ' Weeks';
         else
            strHowOld = strHowOld + ' ' + intWeeks.toString() + ' Week';

      if ( intDays > 0 )
         if ( intDays > 1 )
            strHowOld = strHowOld + ' ' + intDays.toString() + ' Days';
         else
            strHowOld = strHowOld + ' ' + intDays.toString() + ' Day';

      if ( intHours > 0 )
         if ( intHours > 1 )
            strHowOld = strHowOld + ' ' + intHours.toString() + ' Hours';
         else
            strHowOld = strHowOld + ' ' + intHours.toString() + ' Hour';
 
      if ( intMinutes > 0 )
         if ( intMinutes > 1 )
            strHowOld = strHowOld + ' ' + intMinutes.toString() + ' Minutes';
         else
            strHowOld = strHowOld + ' ' + intMinutes.toString() + ' Minute';

      if ( intSeconds > 0 )
         if ( intSeconds > 1 )
            strHowOld = strHowOld + ' ' + intSeconds.toString() + ' Seconds';
         else
            strHowOld = strHowOld + ' ' + intSeconds.toString() + ' Second';
*/
      }
   else
      strHowOld = 0 ;

   // return string representation
   return strHowOld
   } 


//- Initialization
var oPricer =new ExpPricer () ;
/*
window.addEvent ('load', Test) ;
var bTest ;
function Test () {
	bTest =true ;
	$('email').value ='cyrillef@free.fr' ;
	oPricer.Go (8) ;
	bTest =false ;
}
*/
