// JavaScript Document



var baseUrl = "reservation/";

/**
 * Load sejours reservation select lists
 */
function loadCombo(fieldId, targetId, comboName)
{
    $(targetId).update("<img src='"+baseUrl+"ajax-loader.gif' border='0' >");
    objectId = $(fieldId).value;

   // new Ajax.Request(baseUrl+'comboList.php',{
   new Ajax.Request(root + 'index2.php?option=com_content&view=article&id=21&Itemid=4&ajax=comboList',{
        method: 'post',
        parameters: 'combo='+comboName+'&objectId='+objectId,
        onComplete: function(transport){
            var response = cleanText(transport.responseText);
            $(targetId).update(response);
        }
    });
}

function cleanText(s)
{
	var start = s.indexOf('##START##');
	var end   = s.indexOf('##END##');
	
	return s.substr(start + 9, end-start - 9);
}



/**
 * Load forms list
 */
function loadForms(fieldId, targetId)
{
 	
    $(targetId).update("<img src='"+baseUrl+"ajax-loader.gif' border='0' >");

    objectId = $(fieldId).value;
    
 

    //new Ajax.Request(baseUrl+'reservationForms.php',{
    new Ajax.Request(root+'index2.php?option=com_content&view=article&id=21&Itemid=4&ajax=reservationForms',{
        method: 'post',
        parameters: 'objectId='+objectId,
        onComplete: function(transport){
		    
            var response = cleanText(transport.responseText);
            $(targetId).update(response);
        }
    });
    
}

/**
 * Set transport price
 */
function setTransport(idPers)
{
    var transport_price = $('transport_'+idPers).value;
    transport_price = transport_price.split('-');
    transport_price = transport_price[0];
    $('prix_transport_'+idPers).value = transport_price;

    //Re calcul le montant total pour la personne
    calculMontantPers(idPers);
}

function serializeTransport(idPers)
{
	var s = $('transport_'+idPers).value;
    s = s.split('-');
    s = s[1];
	
	return s;
}

function serializeHebergement()
{
	var s = $('hebergement').value;
   	
	return s;
}

/**
 * Détection des cas particuliers assurance
 */
function checkAssurance(idPers,id)
{
    if(id==0)
    {
        var nbAssurance = $('nbAssurance').value;

        if($('assurance_'+idPers+'_0').checked == true)
        {
            for (var i = 1; i < nbAssurance; i++)
            {
                $('assurance_'+idPers+'_'+i).checked = false;
            }
        }
    }else{
        $('assurance_'+idPers+'_0').checked = false;
    }

    calculAssurance(idPers);
}

/**
 * Calcul du montant des assurances
 */
function calculAssurance(idPers)
{
    var assurancePrice = 0;
    var nbAssurance = $('nbAssurance').value;

    for (var i = 0; i < nbAssurance; i++)
    {
        if($('assurance_'+idPers+'_'+i).checked == true)
        {
            var assuranceValue = $('assurance_'+idPers+'_'+i).value;
            assuranceValue = assuranceValue.split('-');
            assuranceValue = assuranceValue[0];
            assurancePrice = parseInt(assurancePrice)+parseInt(assuranceValue);
        }
    }

    $('prix_assurance_'+idPers).value = assurancePrice;

    //Re calcul le montant total pour la personne
    calculMontantPers(idPers);
}

/**
 * Vérification du code promo
 */
function codePromo(idPers, func)
{
    var sejour = $('dates').value;
    var sexe = $('sexe_'+idPers).value;
    var code = $('promo_'+idPers).value;
    
    var myparams  = "&options="+serializeOptions(idPers);
        myparams += "&hebergement="+serializeHebergement();
        myparams += "&transport="+serializeTransport(idPers);

    if(code)
    {
    	ajaxCalls ++;
        new Ajax.Request(root+'index2.php?option=com_content&view=article&id=21&Itemid=4&ajax=promo',{
            method: 'post',
            parameters: 'sej='+sejour+'&sexe='+sexe+'&code='+code + myparams,
            onComplete: function (transport){
	            ajaxCalls --;
                var response = cleanText(transport.responseText);
                var params = response.toQueryParams();
                
                if(params.error == 1)
                {
                    $('code_valide_'+idPers).update("");
                    $('code_error_'+idPers).update(params.value);
                    $('pourcentagepromo_'+idPers).value = 0;
                    $('prixpromo_'+idPers).value = 0;
                    $('promo_'+idPers).value = "";
                    $('promoconcerne_'+idPers).value = "";
                }else{
                    $('code_error_'+idPers).update("");
                    $('code_valide_'+idPers).update("Code promos ajout&eacute;.");
                    $('pourcentagepromo_'+idPers).value = params.value;
                    $('prixpromo_'+idPers).value = params.price;
                    $('promoconcerne_'+idPers).value = params.concerne;

                    //Re calcul le montant total pour la personne
                    //calculMontantPers(idPers);
                }
                
                if( func != null )
                {
                	func();
                }
            }
        });
    }else{
       
       if( func != null )
                {
                	func();
                }
      
      /* 
        $('code_error_'+idPers).update("");
        $('code_valide_'+idPers).update("");
        $('pourcentagepromo_'+idPers).value = 0;
        $('prixpromo_'+idPers).value = 0;

        //Re calcul le montant total pour la personne
        calculMontantPers(idPers);
        */
    }
}

/**
 * Vérification des cas particuliers des options
 */
function checkOptions(idPers, idOption, multiple)
{
    var nbOptions = $('nbOptions_'+idPers).value;

    var currentObject = $('option_'+idPers+'_'+idOption);
    
    if((multiple == 1) && (currentObject.checked == true))
    {
        for(var i=0; i < nbOptions; i++)
        {
            if($('option_'+idPers+'_'+i) != currentObject)
            {
                var currentValue = $('option_'+idPers+'_'+i).value;
                currentValue = currentValue.split('-');
                currentValue = currentValue[0];

                if(currentValue == 1)
                {
                    $('option_'+idPers+'_'+i).disabled = true;
                }
            }
        }
    }else if((multiple == 1) && (currentObject.checked == false)){
        for(var i=0; i < nbOptions; i++)
        {
            if($('option_'+idPers+'_'+i) != currentObject)
            {
                var currentValue = $('option_'+idPers+'_'+i).value;
                currentValue = currentValue.split('-');
                currentValue = currentValue[0];

                if((currentValue == 1) && ($('option_'+idPers+'_'+i).checked == false))
                {
                    $('option_'+idPers+'_'+i).disabled = false;
                }
            }
        }
    }

    calculOptions(idPers);
}

/**
 * Calcul du montant des options
 */
function calculOptions(idPers)
{
    var nbOptions = $('nbOptions_'+idPers).value;
    var optionsPrice = 0;

    for(var i=0; i < nbOptions; i++)
    {
        if($('option_'+idPers+'_'+i).disabled == false)
        {
            if($('option_'+idPers+'_'+i).checked == true)
            {
                var currentValue = $('option_'+idPers+'_'+i).value;
                currentValue = currentValue.split('-');
                currentValue = currentValue[1];
                
                optionsPrice = parseInt(optionsPrice)+parseInt(currentValue);
            }
        }
    }

    $('prix_options_'+idPers).value = optionsPrice;

    //Re calcul le montant total pour la personne
    calculMontantPers(idPers);
}

function serializeOptions(idPers)
{
	var nbOptions = $('nbOptions_'+idPers).value;
    var options = '';

    for(var i=0; i < nbOptions; i++)
    {
        if($('option_'+idPers+'_'+i).disabled == false)
        {
            if($('option_'+idPers+'_'+i).checked == true)
            {
                var currentValue = $('option_'+idPers+'_'+i).value;
                currentValue = currentValue.split('-');
                currentValue = currentValue[2];
                
               if( options.length > 0 )
               {
               	options += ",";
               }
                
               options += currentValue;
            }
        }
    }
    
    return options;
}

/**
 * Calcul le montant total pour une personne
 */
function calculMontantPers(idPers)
{
   	codePromo(idPers,function()
    {
   
   
    //Récupération des montants
    var promo_percent = $('pourcentagepromo_'+idPers).value;
    var promo_price = $('prixpromo_'+idPers).value;
    var promo_concerne = $('promoconcerne_'+idPers).value;
    var transport_price = $('prix_transport_'+idPers).value;
    var assurance_price = $('prix_assurance_'+idPers).value;
    var options_price = $('prix_options_'+idPers).value;
    var hebergement_price = $('prix_heberg_'+idPers).value;
     var hebergementfille_price = $('prix_hebergfille_'+idPers).value;
     
     
     var nom = $('nom_'+idPers).value;
     
     
    
    var sexe = document.getElementById('sexe_'+idPers);
    
    sexe = sexe.selectedIndex > 0 ? sexe.options[sexe.selectedIndex].value : '';
    
    if( sexe == 'F' && hebergementfille_price != '' )
    {
    	 hebergement_price = hebergementfille_price;
    }

    var prix_promo = 0;
    
   	
	if(promo_percent > 0)
    {
        
        if( promo_concerne != '' )
        {
            switch(promo_concerne)
	        {
	        	case 'heberg':
	        	{
	        		prix_promo = hebergement_price*promo_percent/100;
	        		break;
	        	}
	        	case 'options':
	        	{
	        		prix_promo = options_price*promo_percent/100;
	        		break;
	        	}
	        	case 'total':
	        	{
	        		prix_promo = 0;
	        		break;
	        	}
	        }
        }
        
        
        
    }else if(promo_price > 0){
        var prix_promo = promo_price;
    }
    
         
    //Déduction de la promo de l'hebergement
    var addition1 = hebergement_price-prix_promo;
    
    
    //Addition du tout
    var addition2 = addition1*1+transport_price*1+assurance_price*1+options_price*1;
    
    if( promo_percent > 0 && promo_concerne == 'total')
    {
    	addition2 *= (1-(promo_percent/100));
    }
    
    var montant_total = Math.round(addition2*100)/100;

    $('prix_total_'+idPers).value = montant_total;
    $('prix_'+idPers).update(montant_total);
    //Calcule le montant total de commande
    calculTotal();
    
    });
}

/**
 * Calcul du montant total de commande
 */
function calculTotal()
{
    var nbPers = $('nb_participant').value;
    
    var n = 1;
    var total = 0;
    
    for (var i=0; i < nbPers; i++)
    {
        var currentTotal = $('prix_total_'+n).value;
        total = total*1+currentTotal*1;
        n++;
    }
	
	total = Math.round(total*100)/100;
	
    $('prix_total_hidden').value = total;
    $('prix_total').update(total);
}

/**
 * Send complete informations to create Session Virtual tab info
 */
 var ajaxCalls = 0; 
function verifForm(formId)
{
    var stringToPost = $(formId).serialize();
    //Stock les informations des r�servations de chaque participant dans un tableau de donn�e SESSION
    //new Ajax.Request(baseUrl+'comboList.php',{
    
 //   alert(stringToPost);
 
 if( ajaxCalls > 0 )
 {
 	alert('Calcul du total en cours, veuillez patienter');
 	return false;
 }
    
    new Ajax.Request(root+'index2.php?option=com_content&view=article&id=21&Itemid=4&ajax=comboList',{
        method: 'post',
        parameters: 'action=stockReservation&'+stringToPost,
        onComplete: function (transport){

            var response = cleanText(transport.responseText);

            var Errors = response.split('&');
            var responseError = response.toQueryParams();
            
            if(responseError.errors == 1)
            {
                showErrors(Errors,Errors.length);
                alert("Vous avez ommis des informations.");
            }else{
                //--> Soumission du formulaire stringToPost contiens l'intégralité des données
				 //window.location.replace("index.php?file=reservation&fc=confirmation_reservation");
				 window.location.href = 'index.php?option=com_content&view=article&id=21&Itemid=4&fc=confirmation_reservation';
            }
        }
    });
}

/**
 * Rendering errors on forms
 */
function showErrors(Errors, nbErrors)
{
    for (var i=0; i < nbErrors; i++)
    {
        if($(Errors[i]+'_errorDiv'))
        {
            $(Errors[i]+'_errorDiv').show();
        }
    }
}
