/*INTERFACCIA JS PER GESTIRE IL CARRELLO*/

var id_prodotto;  //variabile che conterr l'id dell'elemento che conteneva il prodotto che andra tolto

var dati_utente = new Array();  //variabile che conterr tutti i dati dell'utente che sta andando an inserire
var dati_paxes = new Array();  //variabile che conterr tutti i dati dell'utente che sta andando an inserire
var pax_number = 0;

// Controlla se mostrare o nascondere i campi per la registrazione di un utente
function registration_fields() {
	
	if(document.getElementById('register').checked)
		display = display_for_browser();
	else
		display = 'none';
	document.getElementById('password_field').style.display = display;
	document.getElementById('pwdconfirm_field').style.display = display;
	// document.getElementById('newsletters_field').style.display = display;
	
	refresh_box();
}

//mostra a video i dati inseriti dall'utente per avere conferma prima dell'inserimento
function show_summary() {	
	reset_errors();
	var data = new Array();

	pax_number = eval(document.getElementById('pax_number').value);

	//mi faccio dare tutti gli elementi controllando se quelli obbligatori sono stati compilati o meno
	var  privacy_condition = document.getElementById('privacy_condition');
	var information_newsletter = document.getElementById('information_newsletter');
	if(information_newsletter.checked ){
		data['information_newsletter'] = 'Y';
	}
	if (!privacy_condition.checked ){
		print_error(js_dic_ERROR_CONDITION_PRIVACY);
		return false;		
	}
	// only if user is not logged
	if(document.getElementById('user_datas').style.display != 'none'){
		// is present section for tax_code and vat_number
		
		if(document.getElementById('tax_code') && document.getElementById('vat_number')){
			var cf = document.getElementById('tax_code').value;	
			var errorCf = ControllaCF(cf);
			
			var vat_number = document.getElementById('vat_number').value;
			var errorVatnumber = 	ControllaPIVA(vat_number);
			
			if(errorCf == "ko" && errorVatnumber == "ko"){
				print_error(js_dic_ERROR_NO_TAX_VAT_NUMBER);
				return false;
			}
			
			if (errorCf != "ko" && errorCf != "ok"){
				print_error(errorCf);
				return false;
			}
			
			if (errorVatnumber != "ko" && errorVatnumber != "ok"){
				print_error(errorVatnumber);
				return false;
			}		
		}

		///////// section to get the information data on DATA_CONTRACTING
		var form = document.getElementById('data_form');
		
		var input = form.getElementsByTagName('input');
		//adesso ciclo su tutti gli elementi
		for (var i=0; i<input.length; i++){
			//qualsiasi cosa faccia, la faccio solo se � visualizzato. e se non � un bottone
			if(input[i].parentNode.parentNode.style.display != 'none' && input[i].type != 'button'){
				if(input[i].value == '' && document.getElementById('err_'+input[i].id)){
					
					document.getElementById('err_'+(input[i].id)).innerHTML = ' '+'*';
					return false;
				}
				// se  stato inserito qualcosa, intanto azzero gli eventuali errori se ce ne erano precedentemente
				if(document.getElementById('err_'+input[i].id)){
					document.getElementById('err_'+(input[i].id)).innerHTML = '';
				}

				// dopodiche salvo il valore nello struct_param, ma solo se non e pwdconfirm 
				// no put in array the paxes fields
				if(input[i].id != 'pwdconfirm'){
					if(input[i].type == "checkbox"){
						if(input[i].checked){
							data[input[i].name] = input[i].value;
						}
					} else {
						data[input[i].name] = input[i].value;
					}
				}
				else{
					//controllo che la conferma della password sia effettivamente 
					//uguale alla password inserita, altrimenti lancio un errore
					if(input[i].value != data['password']){
						document.getElementById('err_pwdconfirm').innerHTML = ' '+js_dic_ERRORPWDCONFIRM;
						return false;
					}
				}
			}
		}

		
		

		var select = form.getElementsByTagName('select');
		for (i = 0; i < select.length; i++) {
			// passo solo i valori delle select non nascoste da js
			// no put in array the paxes fields
			if(form[i].parentNode.parentNode.style.display != 'none') {
				if(select[i] != null){
					data[select[i].name] = select[i].value;
				}
			}
		}
		
		//controllo che la password abbia almeno 6 caratteri, altrimenti lancio un errore:
		if(data['password'] != null){
			if( !length_pwd(data['password'])){
				document.getElementById('err_password').innerHTML = ' '+js_dic_ERRORPWDSHORT;
				return;
			}
			
		}
		
		
		
		dati_utente = data;
		//a questo punto popolo l'html
		document.getElementById('div_name').innerHTML = js_dic_NAME+' : '+data['name'];
		document.getElementById('div_surname').innerHTML = js_dic_SURNAME+' : '+data['surname'];
		document.getElementById('div_sex').innerHTML = js_dic_SEX+' : '+data['sex'];
		document.getElementById('div_email').innerHTML = js_dic_EMAIL+' : '+data['email'];
		document.getElementById('div_address').innerHTML = js_dic_ADDRESS+' : '+data['address']+', '+data['zip_code']+' '+data['town']+', '+data['district']+', '+data['nation'];
		document.getElementById('div_telephone').innerHTML = js_dic_TELEPHONE+' : '+data['telephone'];
		document.getElementById('div_fax').innerHTML = js_dic_FAX+' : '+data['fax'];
		document.getElementById('div_tax_code').innerHTML = js_dic_TAXCODE+' : '+data['tax_code'];
		document.getElementById('div_vat_number').innerHTML = js_dic_VAT_NUMBER+' : '+data['vat_number'];

		/////// end DATA_CONTRACTING  
		
		// display section summary data of contracting		
		document.getElementById('summary').style.display = display_for_browser();
		
		
		// hidden section data user
		document.getElementById('user_datas').style.display = 'none';
	}
	
	if(document.getElementById('user_details').style.display != 'none'){
		if(document.getElementById('user_data_name')){
			data['name'] = document.getElementById('user_data_name').value;
		}
		if(document.getElementById('user_data_surname')){
			data['surname'] = document.getElementById('user_data_surname').value;
		}

		if(document.getElementById('user_data_user')){
			data['user'] = document.getElementById('user_data_user').value;
		}		
		
		if(document.getElementById('user_data_sex')){
			data['sex'] = document.getElementById('user_data_sex').value;
		}
		if(document.getElementById('user_data_email')){
			data['email'] = document.getElementById('user_data_email').value;
		}
		if(document.getElementById('user_data_address')){
			data['address'] = document.getElementById('user_data_address').value;
		}
		if(document.getElementById('user_data_zip_code')){
			data['zip_code'] = document.getElementById('user_data_zip_code').value;
		}
		if(document.getElementById('user_data_town')){
			data['town'] = document.getElementById('user_data_town').value;
		}
		if(document.getElementById('user_data_district')){
			data['district'] = document.getElementById('user_data_district').value;
		}
		if(document.getElementById('user_data_nation')){
			data['nation'] = document.getElementById('user_data_nation').value;
		}
		if(document.getElementById('user_data_telephone')){
			data['telephone'] = document.getElementById('user_data_telephone').value;
		}
		if(document.getElementById('user_data_fax')){
			data['fax'] = document.getElementById('user_data_fax').value;
		}
		if(document.getElementById('user_data_tax_code')){
			data['tax_code'] = document.getElementById('user_data_tax_code').value;
		}
		if(document.getElementById('user_data_tax_code')){
			data['tax_code'] = document.getElementById('user_data_tax_code').value;
		}
		if(document.getElementById('user_data_vat_number')){
			data['vat_number'] = document.getElementById('user_data_vat_number').value;
		}
		if(document.getElementById('user_data_code_payment')){
			data['code_payment'] = document.getElementById('user_data_code_payment').value;
		}

		data['register'] = "login";
		
		dati_utente = data;
	}

	// save the custome_ref 
	if(document.getElementById('customer_ref')){
		cutomerRef =  trim(document.getElementById('customer_ref').value," ");
		if(cutomerRef != ""){
			data['customer_ref'] = cutomerRef;
		}
	} 


	///////  DATA_PAXES is always present 	


       var form_paxes = document.getElementById('user_data_paxes');
       var input = form_paxes.getElementsByTagName('input');
       var datap = new Array();
       if(pax_number < js_global_minimum_pax_number_group){

            //adesso ciclo su tutti gli elementi
            for (var i=0; i < input.length; i++){
                    //qualsiasi cosa faccia, la faccio solo se � visualizzato. e se non � un bottone
                    if(input[i].parentNode.parentNode.style.display != 'none' && input[i].type != 'button'){
                            if(input[i].value == '' && document.getElementById('err_'+input[i].id)){
                                    document.getElementById('err_'+(input[i].id)).innerHTML = ' '+'*';
                                    return false;
                            }
                            // se  stato inserito qualcosa, intanto azzero gli eventuali errori se ce ne erano precedentemente
                            if(document.getElementById('err_'+input[i].id)){
                                    document.getElementById('err_'+(input[i].id)).innerHTML = '';
                            }

                            // dopodiche salvo il valore nello struct_param, ma solo se non e pwdconfirm
                            // no put in array the paxes fields

                            if(input[i].type == "checkbox"){
                                    if(input[i].checked){
                                            datap[input[i].name] = input[i].value;
                                    }
                            } else {
                                    datap[input[i].name] = input[i].value;
                            }

                    }
            }

            for (var i = 0; i < pax_number; i++){
                    dati_paxes[i] = new Array();
                    dati_paxes[i]['name'] = datap['name_pax_'+i];
                    dati_paxes[i]['surname'] = datap['surname_pax_'+i];
                    document.getElementById('div_name_pax_'+i).innerHTML = js_dic_NAME+' : '+datap['name_pax_'+i];
                    document.getElementById('div_surname_pax_'+i).innerHTML = js_dic_SURNAME+' : '+datap['surname_pax_'+i];
            }
        }else {
     	   
            if(document.getElementById('flag_group_textarea').value == 'true'){
                if( document.getElementById('name_pax_leader') == '' && document.getElementById('surname_pax_leader') == ''){
                    alert(js_dic_ERRORCOMPULSORYFIELD);
                    return false;
                 }
                 dati_paxes[0] = new Array();
                 dati_paxes[0]['name'] = document.getElementById('name_pax_leader').value;
                 dati_paxes[0]['surname'] = document.getElementById('surname_pax_leader').value;
                 if(document.getElementById('textarea_pax').value != ""){
                     dati_paxes[0]['other_pax'] = document.getElementById('textarea_pax').value ;
                 }

                 document.getElementById('div_name_pax_leader').innerHTML = js_dic_NAME + ' : ' + dati_paxes[0]['name'];
                 document.getElementById('div_surname_pax_leader').innerHTML = js_dic_SURNAME + ' : ' + dati_paxes[0]['surname']
                 document.getElementById('div_textarea_pax').innerHTML = js_dic_OTHER_PASSENGERS + ' : ' + dati_paxes[0]['other_pax'];
            } else {
                for (var i=0; i < input.length; i++){
                        //qualsiasi cosa faccia, la faccio solo se e' visualizzato. e se non e' un bottone
                        if(input[i].parentNode.parentNode.style.display != 'none' && input[i].type != 'button'){
                                if(input[i].value == '' && document.getElementById('err_'+input[i].id)){
                                        document.getElementById('err_'+(input[i].id)).innerHTML = ' '+js_dic_ERRORCOMPULSORYFIELD;
                                        return false;
                                }
                                // se  stato inserito qualcosa, intanto azzero gli eventuali errori se ce ne erano precedentemente
                                if(document.getElementById('err_'+input[i].id)){
                                        document.getElementById('err_'+(input[i].id)).innerHTML = '';
                                }

                                // dopodiche salvo il valore nello struct_param, ma solo se non e pwdconfirm
                                // no put in array the paxes fields

                                if(input[i].type == "checkbox"){
                                        if(input[i].checked){
                                                datap[input[i].name] = input[i].value;
                                        }
                                } else {
                                        datap[input[i].name] = input[i].value;
                                }

                        }
                }

                for (var i = 0; i < pax_number; i++){
                        dati_paxes[i] = new Array();
                        dati_paxes[i]['name'] = datap['name_pax_'+i];
                        dati_paxes[i]['surname'] = datap['surname_pax_'+i];
                        document.getElementById('div_name_pax_'+i).innerHTML = js_dic_NAME+' : '+datap['name_pax_'+i];
                        document.getElementById('div_surname_pax_'+i).innerHTML = js_dic_SURNAME+' : '+datap['surname_pax_'+i];
                }

            }
        
        }
	/////////// END DATA_PAXES 
	//display the summary paxes data and hidden the paxes data  

    document.getElementById('div_customer_ref').innerHTML = js_dic_CUSTOMER_REF+' : '+data['customer_ref'];
       
	document.getElementById('user_data_paxes').style.display = 'none';
	document.getElementById('box_condition').style.display = 'none';
	document.getElementById('button_insert_data').style.display = 'none';
	document.getElementById('spacing').style.display = 'none';
	// document.getElementById('button_buy').style.display = display_for_browser();
	// document.getElementById('summary_paxes').style.display = display_for_browser();
    document.getElementById('div_paxes_box').style.display = display_for_browser();    
	$('#cart-top').css('background','url("../../images/webins/cart-top-3.jpg") no-repeat scroll 10px 0 transparent');
	if(pax_number < js_global_minimum_pax_number_group){
            document.getElementById('div_paxes').style.display = display_for_browser();
        } else {
           if(document.getElementById('flag_group_textarea').value == 'true'){
                document.getElementById('div_pax_area').style.display = display_for_browser();
            } else {
                document.getElementById('div_paxes').style.display = display_for_browser();
            }

        }
	refresh_box();

	save_purchase_data();
}



// Salva i dati di un utente per un acquisto o se egli lo richiede lo registra nel sistema
function save_purchase_data() {
    //var where = document.getElementById('summary_purchase');
    struct_param['query'] = new Array();
    struct_param['header']['product'] = 'purchase';
    struct_param['header']['type'] = 'save_purchase_data';
    //mi faccio ridare i dati che erano stati calcolati
    struct_param['query'] = dati_utente;
    
    xml_request(struct_param, url_xml_rpc, iso_encoding, control_after_save_purchase);
}


function control_after_save_purchase(response, type){
    if(type == "save_purchase_data"){
        if(response['result'] == "failure"){
            print_error(js_dic_ERRORDB);
        } else if(response['result'] == 'existing_user'){
            print_error(js_dic_ERROREXISTINGEMAIL);
        } else if(response['result'] == "no_registration"){
            print_error(js_dic_ERRORDB);
        } else {
            newsletters = false;
            if(dati_utente['information_newsletter'] == "true"){
                newsletters = true;
            }
            save_paxes_data(pax_number,newsletters,dati_paxes);
        }
    }
}

// Funzione per la gestione dei valori ritornati dalla Filter
function callback_html_response(response, where) {
    switch (response){
        case 'failure':
            print_error(js_dic_ERRORDB);
            document.getElementById('user_datas').style.display = display_for_browser();
            document.getElementById('loading').style.display = 'none';
            break;
        case 'existing_user':
            print_error(js_dic_ERROREXISTINGEMAIL);
            document.getElementById('user_datas').style.display = display_for_browser();
            document.getElementById('loading').style.display = 'none';
            break;
        default:
            location.reload(true);
            break;
    }
}

// Torna al form per far cambiare i dati personali appena inseriti
function change_data() {
	document.getElementById('user_datas').style.display = display_for_browser();
	document.getElementById('summary').style.display = 'none';
	refresh_box();
}





//elimina il prodotto dalla lista del carrello alla posizione key
function product_remove_cart(key){
	struct_param['query'] = new Array();
	struct_param['header']['product'] = 'cart';
	struct_param['header']['type'] = 'remove_product_cart';
	if (key != 'all'){
		//se devo cancellare un prodotto singolo
		id_prodotto = 'cart_'+key;
		struct_param['query']['key'] = key;
		xml_request(struct_param, url_xml_rpc, iso_encoding, reload_cart_after_product_removal);
		return;
	} 
	//se invece devo cancellarli tutti
	struct_param['query']['key'] = 'all';
	xml_request(struct_param, url_xml_rpc, iso_encoding, reload_cart_after_product_removal);
	return;

}


//funzione che viene chiamata dopo che e stato tolto il prodotto dal carrello per aggiornare al pagina
function reload_cart_after_product_removal(response, type){
	if (response['value'] == false){
		//se non sono riusito a cancellarlo non faccio niente..per il momento...appena scopro coem si gestiscono gli errori magari ci penso.....
		return;
	}
	//controllo se � ho cancellato utti i prodotti o se ce ne sono ancora
	if (response['type'] == 'all'){
		
		// var aux = document.getElementsByTagName('fieldset');
		// document.getElementById('all_cart').style.display = 'none';
		/*
		for (var i=0; i<aux.length; i++){
			aux[i].style.display = 'none';
		}
		*/
		var nproducts = document.getElementById("n_products").value;
		for (var i=0; i<nproducts; i++){
			document.getElementById("cart_"+i).style.display = 'none';
			document.getElementById("cart_image_"+i).style.display = 'none';
		}
		
		//visualizzo la scritta che mi dice che non ho elementi nel carrello
		document.getElementById("empty_cart").style.display = display_for_browser();
		//poi faccio in modo che non si vedano pi� i bottoni per procedere con l'acquisto e per svuotare il carrello(e gia vuoto)
		document.getElementById("button_buy").style.display = 'none';
		document.getElementById("button_removecart").style.display = 'none';
		window.location=js_global_root_url+'index.php';
		return;
	}
	//se arrivo qui vuol dire che ho cancellato con successo un solo elemento, devo far si che non si veda piu, ma ce ne sono ancora	
	document.getElementById(id_prodotto).style.display = 'none';
	//e poi devo aggiornare il valore del totale da pagare
	document.getElementById("total_amount").innerHTML = response['total_amount'] + js_dic_CURRENCY_SIGN;
	return;
}


//funzione che mostra il form di login
function show_login_form(){
	document.getElementById("login_form").style.display = display_for_browser();
	document.getElementById("user_datas").style.display = 'none';
}

//funzione che effettua il login
function login_form(){
	
	//non mostro il form per la ricerca e invece mostro il loading
	document.getElementById('login_form').style.display = 'none';
	document.getElementById('loading').style.display = display_for_browser();
	refresh_box();
	
	//dopodiche devo loggare l'utente
	struct_param['query'] = new Array();
	struct_param['header']['product'] = 'authentication';
	struct_param['header']['type'] = 'login';
	struct_param['query']['email'] = document.getElementById('field_email').value;
	struct_param['query']['pwd'] = document.getElementById('field_pwd').value;
	
	if(document.getElementById('box'))
		refresh_box();
	xml_request(struct_param, url_xml_rpc, iso_encoding, authentication_callback_xml_request);
	
}


// Funzione per la gestione dei valori ritornati
function authentication_callback_xml_request(response, type) {
	if(response == 'failure'){
		print_error(js_dic_ERRORLOGIN); 
		document.getElementById('login_form').style.display = display_for_browser();
		document.getElementById('loading').style.display = 'none';
	}
	else{
		location.reload();
	}
}

//funzione che esce da form di login
function rollback(){
	document.getElementById("login_form").style.display = 'none';
	document.getElementById("user_datas").style.display = display_for_browser();
}

function show_description_contract(productId){
  var file_name = "";
  var language = document.getElementById('language').value;
  // print_error(js_global_contracts_url+productId +'/'+productId+'_Description_'+language+js_global_extension_file_contracts);
  window.open(js_global_contracts_url+productId +'/'+productId+'_Description_'+language+js_global_extension_file_contracts);	
}

function show_contract_terms(contractFile){
  var file_name = "";  
  window.open(contractFile);
}

function show_terms_withdrawal(){
  var file_name = "";
  var language = document.getElementById('language').value;
  // print_error(js_global_contracts_url+productId +'/'+productId+'_Description_'+language+js_global_extension_file_contracts);
  window.open(js_global_contracts_url+js_global_name_withdrawal+'_'+language+js_global_extension_file_contracts);	
}



function upperCase(objText)
{
	var x = objText.value;
	objText.value = x.toUpperCase()
}

//return the value of the radio button that is checked
//return an empty string if none are checked, or
//there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	return radioLength;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function show_pax_text_area(){
    if (document.getElementById("pax_list") && document.getElementById("pax_area")){
        document.getElementById("pax_list").style.display = 'none';
        document.getElementById("pax_area").style.display = display_for_browser();
        document.getElementById("pax_group").style.display = 'none';
        document.getElementById("pax_group_list").style.display = display_for_browser();
        document.getElementById("flag_group_textarea").value = true;
    }
}

function show_pax_list(){
    if (document.getElementById("pax_list") && document.getElementById("pax_area")){
        document.getElementById("pax_list").style.display = display_for_browser();
        document.getElementById("pax_area").style.display = 'none';
        document.getElementById("pax_group").style.display = display_for_browser();
        document.getElementById("pax_group_list").style.display = 'none';
        document.getElementById("flag_group_textarea").value = false;
    }
}
