// JavaScript Document

$(function(){

	// Tabs
	$('#login_tabs').tabs();
	$('#nav_tabs').tabs();
	$('#mail_tabs').tabs();
	$('#copertura_tabs').tabs();
	$('#news_tabs').tabs();
	$('#newsletter_tabs').tabs();

	
	$('#dialog_link, ul#icons li').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
	
});

function mycarousel_initCallback(carousel)
{
    
			
			carousel.buttonNext.bind('click', function() {
				carousel.startAuto(0);
			});
		
			carousel.buttonPrev.bind('click', function() {
				carousel.startAuto(0);
			});
		
			carousel.clip.hover(function() {
				carousel.stopAuto();
			}, function() {
				carousel.startAuto();
			
			});
};




jQuery(document).ready(function() {

	jQuery('#prodotti_carousel').jcarousel({
		auto: 3,
		wrap: 'circular',
		initCallback: mycarousel_initCallback
	});

});




jQuery(document).ready(function() {

	jQuery('#servizi_carousel').jcarousel({
								  
		auto: 4,
		wrap: 'last',
		initCallback: mycarousel_initCallback
	});
});


// Funzione News
$(function() {
	$(".newsticker-jcarousellite").jCarouselLite({
		vertical: true,
		hoverPause:true,
		visible: 3,
		auto:5000,
		speed:1000
	});
});

// Visualizza tutti i prodotti
$(function()
{

$("#view_all").click(function(event) {
event.preventDefault();
$("#view_prodotti").slideToggle();
});
/*
$("#view_prodotti a").click(function(event) {
event.preventDefault();
$("#view_prodotti").slideUp();
});
*/
});

// Funzione Ricerca Comuni
function findValue(li) {
	if( li == null ) return  jAlert('Nessun Comune trovato!', 'Verifica Copertura');
	if( !!li.extra ) var sValue = li.extra[0];
	else var sValue = li.selectValue;
}

function selectItem(li) {
	findValue(li);
}

function formatItem(row) {
	return row[0] + " (id: " + row[1] + ")";
}


function lookupLocal(){
	var oSuggest = $("#comune")[0].autocompleter;

	oSuggest.findValue();

	return false;
}

$(document).ready(function() {

	$("#comune").autocompleteArray(comuni,
		{
			delay:10,
			minChars:1,
			matchSubset:1,
			onItemSelect:selectItem,
			onFindValue:findValue,
			autoFill:true,
			maxItemsToShow:10
		}
	);
});
// Fine Funzione Ricerca Comuni


// Funzione segnasezione
function ChangeClass(id){
document.getElementById('faq').className='';
document.getElementById('assistenza').className='';
document.getElementById('webmail').className='';
document.getElementById('partner').className='';
document.getElementById('amministrazione').className='';
document.getElementById('web').className='';
document.getElementById('business').className='';
document.getElementById('privati').className='';
document.getElementById('home').className='';
document.getElementById(id).className='current';
}
// Funzione pulisci segnasezione
function CleanClass(){
document.getElementById('faq').className='';
document.getElementById('assistenza').className='';
document.getElementById('webmail').className='';
document.getElementById('partner').className='';
document.getElementById('amministrazione').className='';
document.getElementById('web').className='';
document.getElementById('business').className='';
document.getElementById('privati').className='';
document.getElementById('home').className='';
}

// Funzione admin segnasezione
function AdminChangeClass(id){
document.getElementById('cv').className='';
document.getElementById('admin_copertura').className='';
document.getElementById('partner').className='';
document.getElementById('admin_prodotti').className='';
document.getElementById('admin_servizi').className='';
document.getElementById('admin_newsletter').className='';
document.getElementById('clienti').className='';
document.getElementById('alerts').className='';
document.getElementById('home').className='';
document.getElementById(id).className='current';
}
// Funzione admin pulisci segnasezione
function AdminCleanClass(){
document.getElementById('cv').className='';
document.getElementById('admin_copertura').className='';
document.getElementById('partner').className='';
document.getElementById('admin_prodotti').className='';
document.getElementById('admin_servizi').className='';
document.getElementById('admin_newsletter').className='';
document.getElementById('clienti').className='';
document.getElementById('home').className='';
}

// Submit Form

function xmlhttpPost(strURL,formname,responsediv,responsemsg) {

    var xmlHttpReq = false;

    var self = this;

    // Xhr per Mozilla/Safari/Ie7

    if (window.XMLHttpRequest) {

        self.xmlHttpReq = new XMLHttpRequest();

    }

    // per tutte le altre versioni di IE

    else if (window.ActiveXObject) {

        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");

    }

    self.xmlHttpReq.open('POST', strURL, true);

    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    self.xmlHttpReq.onreadystatechange = function() {

        if (self.xmlHttpReq.readyState == 4) {

			// Quando pronta, visualizzo la risposta del form

            updatepage('',responsediv);
			jAlert(self.xmlHttpReq.responseText, 'Modifica Dati'); 

        }

		else{

			// In attesa della risposta del form visualizzo il msg di attesa

			updatepage(responsemsg,responsediv);
			


		}

    }

    self.xmlHttpReq.send(getquerystring(formname));

}



function getquerystring(formname) {

    var form = document.forms[formname];

	var qstr = "";



    function GetElemValue(name, value) {

        qstr += (qstr.length > 0 ? "&" : "")

            + escape(name).replace(/\+/g, "%2B") + "="

            + escape(value ? value : "").replace(/\+/g, "%2B");

			//+ escape(value ? value : "").replace(/\n/g, "%0D");

    }

	

	var elemArray = form.elements;

    for (var i = 0; i < elemArray.length; i++) {

        var element = elemArray[i];

        var elemType = element.type.toUpperCase();

        var elemName = element.name;

        if (elemName) {

            if (elemType == "TEXT"

                    || elemType == "TEXTAREA"

                    || elemType == "PASSWORD"

					|| elemType == "BUTTON"

					|| elemType == "RESET"

					|| elemType == "SUBMIT"

					|| elemType == "FILE"

					|| elemType == "IMAGE"

                    || elemType == "HIDDEN")

                GetElemValue(elemName, element.value);

            else if (elemType == "CHECKBOX" && element.checked)

                GetElemValue(elemName, 

                    element.value ? element.value : "On");

            else if (elemType == "RADIO" && element.checked)

                GetElemValue(elemName, element.value);

            else if (elemType.indexOf("SELECT") != -1)

                for (var j = 0; j < element.options.length; j++) {

                    var option = element.options[j];

                    if (option.selected)

                        GetElemValue(elemName,

                            option.value ? option.value : option.text);

                }

        }

    }

    return qstr;


}

function updatepage(str,responsediv){
	$("#wizardpanel").hide();
    document.getElementById(responsediv).innerHTML = str;

}

// Funzione mostra Loading
function Loading(){
	var loader = jQuery('<div id="loadingdiv">Loading...</div>');
	 jQuery(document).ready(function(){
		$('body').hide();
		loader.prependTo(window);
	});
	jQuery(window).load(function(){
		loader.remove();
		$('body').show();
	});
}

// Funzione veriica copertura
function VerificaCopertura() {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var comune = document.forms['RequestCopertura'].elements['comune'].value;
   var address = document.forms['RequestCopertura'].elements['email'].value;
   if(reg.test(address) == false) {
	  jAlert('Indirizzo email non valido', 'Verifica Copertura'); 
      return false;
   } else {
	CleanClass();
	ajaxpagefetcher.load('content','verifica_copertura.php?comune='+comune+'&email='+address, true);   
   }
}


// Funzione Richiesta contatti
function validateContact() {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var nome = document.forms['ContactRequest'].elements['nome'].value;
   var address = document.forms['ContactRequest'].elements['email'].value;
   if(reg.test(address) == false) {
	  jAlert('Indirizzo email non valido', 'Richiesta contatti'); 
      return false;
   } else {
	CleanClass();
	ajaxpagefetcher.load('content','contatti.php?nome='+nome+'&email='+address, true, ['js/ContactForm.js']);   
   }
}

// Funzione Iscrizione Newsletter
function NewsletterSubscribe() {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var nome = document.forms['newsletter'].elements['nome'].value;
   var address = document.forms['newsletter'].elements['email'].value;
   if(reg.test(address) == false) {
	  jAlert('Indirizzo email non valido', 'Iscrizione Newsletter'); 
      return false;
   } else {
	CleanClass();
	ajaxpagefetcher.load('content','newsletter_subscribe.php?nome='+nome+'&email='+address, true);   
   }
}
// Funzione Iscrizione partner

function PartnerSubscribe() {
	ajaxpagefetcher.load('content','registrazione_partner.php', true);   
}

// Funzione Iscrizione nuovo cliente
function validateSignup() {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms['signupForm'].elements['new_email'].value;
   if(reg.test(address) == false) {
	  jAlert('Indirizzo email non valido', 'Registrazione cliente'); 
      return false;
   } else {
	CleanClass();
	ajaxpagefetcher.load('content','registrazione.php?email='+address, true);   
   }
}

$(document).ready(function() {
	$('#usernameLoading').hide();
	$('#new_email').blur(function(){
	  $('#usernameLoading').show();
      $.post("check_username.php", {
        username: $('#new_email').val()
      }, function(response){
        $('#usernameResult').fadeOut();
        setTimeout("finishAjax('usernameResult', '"+escape(response)+"')", 400);
      });
    	return false;
	});
});

function finishAjax(id, response) {
  $('#usernameLoading').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
} 
// Fine Funzione Iscrizione nuovo cliente


// Funzione Cookie

function detect()
{
	if(navigator.cookieEnabled)
	{
	return true;
	}
	else
	{
	jAlert('Il browser &egrave; configurato per il blocco dei cookie.\n &Egrave; necessario che il browser accetti i cookie.\nI cookie sono piccoli file di testo memorizzati nel computer e servono a informare i siti e i servizi CONNECTIVIA che hai effettuato l\'accesso.\n Per informazioni sulla procedura per accettare i cookie, vedi la Guida del browser.', 'E\' necessario accettare i cookie');
	}
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 ;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toUTCString());
}

// Form registrazione navigazione step
/*
function loadnext(divout,divin){

$("." + divout).hide();
$("." + divin).fadeIn("fast");
}
*/
// Form registrazione navigazione step
function loadnext(divout,divin){
	if(divout==1){
		
		
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		var address   = document.forms['SignupForm'].elements['email'].value;
		var username  = document.forms['SignupForm'].elements['username'].value;
		var password1 = document.forms['SignupForm'].elements['pass1'].value;
		var password2 = document.forms['SignupForm'].elements['pass2'].value;
		var illegalChars = /\W/;
		
		$("#attivazione_localita").autocompleteArray(comuni,
		{
			delay:10,
			minChars:1,
			matchSubset:1,
			onItemSelect:selectItem,
			onFindValue:findValue,
			autoFill:true,
			maxItemsToShow:10
		}
		);
		
		// Check Username
		if (username == "") {
    	jAlert('Specificare username', 'Registrazione cliente'); 
		return false;
		}
		else if ((username.length < 6) || (username.length > 14)) {
		jAlert('L\'username deve essere tra 6 e 14 caratteri', 'Registrazione cliente');
		return false;
		}
  		// permetto solo lettere, numeri e underscores
    	else if (illegalChars.test(username)) {
		jAlert('L\'username contiene caratteri non validi', 'Registrazione cliente');
		return false;
    	} 
		// Check Email
		if(reg.test(address) == false) {
		jAlert('Indirizzo email non valido', 'Registrazione cliente'); 
		return false;
		}
		// Check Password
		if (password1 == "") {
    	jAlert('Specificare una password', 'Registrazione cliente'); 
		return false;
 		}

   		var illegalChars = /[\W_]/; 
    	if ((password1.length < 6)) {
       	jAlert('La password deve essere minimo 6', 'Registrazione cliente'); 
		return false;
    	}
    	else if (illegalChars.test(password1)) {
      	jAlert('Le password contiene caratteri non validi', 'Registrazione cliente'); 
		return false;
    	}
		else if (password1 != password2) {
    	jAlert('Le password non coincidono', 'Registrazione cliente'); 
		return false;
 		} 
		// Setto i cookie
		setCookie('username',username,365);
		setCookie('email',address,365);
		setCookie('password',password1,365);	
	}

	if(divin==2){
	
	
	document.forms['RegisterForm'].elements['username'].value = getCookie('username');
	document.forms['RegisterForm'].elements['email'].value = getCookie('email');
	document.forms['RegisterForm'].elements['pwd'].value = getCookie('password');
	
	$("#attivazione_localita").autocompleteArray(comuni,
		{
			delay:10,
			minChars:1,
			matchSubset:1,
			onItemSelect:selectItem,
			onFindValue:findValue,
			autoFill:true,
			maxItemsToShow:10
		}
	);

	
	$("#luogo_nascita").autocompleteArray(comuni,
		{
			delay:10,
			minChars:1,
			matchSubset:1,
			onItemSelect:selectItem,
			onFindValue:findValue,
			autoFill:true,
			maxItemsToShow:10
		}
	);
	
	$("#data_nascita").dateEntry({dateFormat: 'dmy/'});

	$("#cap").keypress(function (e)  
	{ 
	  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
	  {
		jAlert('CAP deve essere numerico', 'Registrazione cliente');  
	    return false;
      }	
	});
	
	$("#telefono").keypress(function (e)  
	{ 
	  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
	  {
		jAlert('Telefono deve essere numerico', 'Registrazione cliente');  
	    return false;
      }	
	});
	
	$("#fax").keypress(function (e)  
	{ 
	  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
	  {
		jAlert('Fax deve essere numerico', 'Registrazione cliente');  
	    return false;
      }	
	});

	

	}
	
$("." + divout).hide();
$("." + divin).fadeIn("fast");
}

// Form attivazione navigazione step
function CurrencyFormatted(amount)
		{
			var i = parseFloat(amount);
			if(isNaN(i)) { i = 0.00; }
			var minus = '';
			if(i < 0) { minus = '-'; }
			i = Math.abs(i);
			i = parseInt((i + .005) * 100);
			i = i / 100;
			s = new String(i);
			if(s.indexOf('.') < 0) { s += '.00'; }
			if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
			s = minus + s;
			return s;
		}

function Aloadnext(divout,divin){
	
	if(divout==1){
		
		
		function ControllaCF(cf)
		{
			var validi, i, s, set1, set2, setpari, setdisp;
			if( cf == '' )  return '';
			cf = cf.toUpperCase();
			if( cf.length != 16 )
				return "La lunghezza del codice fiscale non è\n"
				+"corretta: il codice fiscale dovrebbe essere lungo\n"
				+"esattamente 16 caratteri.\n";
			validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			for( i = 0; i < 16; i++ ){
				if( validi.indexOf( cf.charAt(i) ) == -1 )
					return "Il codice fiscale contiene un carattere non valido `" +
						cf.charAt(i) +
						"'.\nI caratteri validi sono le lettere e le cifre.\n";
			}
			set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
			setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
			s = 0;
			for( i = 1; i <= 13; i += 2 )
				s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
			for( i = 0; i <= 14; i += 2 )
				s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
			if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
				return "Il codice fiscale non è corretto:\n"+
					"il codice di controllo non corrisponde.\n";
			return "";
		}
		
		
		function ControllaPIVA(pi)
		{
			if( pi == '' )  return '';
			if( pi.length != 11 )
				return "La lunghezza della partita IVA non è\n" +
					"corretta: la partita IVA dovrebbe essere lunga\n" +
					"esattamente 11 caratteri.\n";
			validi = "0123456789";
			for( i = 0; i < 11; i++ ){
				if( validi.indexOf( pi.charAt(i) ) == -1 )
					return "La partita IVA contiene un carattere non valido `" +
						pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
			}
			s = 0;
			for( i = 0; i <= 9; i += 2 )
				s += pi.charCodeAt(i) - '0'.charCodeAt(0);
			for( i = 1; i <= 9; i += 2 ){
				c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
				if( c > 9 )  c = c - 9;
				s += c;
			}
			if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
				return "La partita IVA non è valida:\n" +
					"il codice di controllo non corrisponde.\n";
			return '';
		}
		
		
		function verifica(cod)
		{
			
		
			if( cod == '' )
				err = "hai lasciato in bianco il campo!\n";
			else if( cod.length == 16 )
				err = ControllaCF(cod);
			else if( cod.length == 11 )
				err = ControllaPIVA(cod);
			else
				err = "Il codice introdotto non è valido:\n\n" +
					"  - un codice fiscale deve essere lungo 16 caratteri;\n\n" +
					"  - una partita IVA deve essere lunga 11 caratteri.\n";
		
			if( err > '' ){
				jAlert('VALORE ERRATO\n\n' + err + '\nCorreggi e riprova!', 'Richiesta Attivazione');
				return false;
				
			} 
			return true;

		}
		
		$("#attivazione_localita").autocompleteArray(comuni,
		{
			delay:10,
			minChars:1,
			matchSubset:1,
			onItemSelect:selectItem,
			onFindValue:findValue,
			autoFill:true,
			maxItemsToShow:10
		}
		);
		
		var ref = document.forms['AttivazioneForm'].elements['referente'].value;
		var cod = document.forms['AttivazioneForm'].elements['codice_fiscale'].value;
		var adress_wadsl = document.forms['AttivazioneForm'].elements['indirizzo_wadsl'].value;
		var cap = document.forms['AttivazioneForm'].elements['cap'].value;
		var localita = document.forms['AttivazioneForm'].elements['attivazione_localita'].value;
		var provincia = document.forms['AttivazioneForm'].elements['indirizzo_wadsl'].value;
		var tel = document.forms['AttivazioneForm'].elements['telefono'].value;
		var fax = document.forms['AttivazioneForm'].elements['fax'].value;
		
		if (adress_wadsl == "") {
    	jAlert('Specificare l\'indirizzo per l\'installazione WADSL', 'Richiesta Attivazione'); 
		return false;
		}
		if (verifica(cod) == "") {
		return false;
		}
		// Setto i cookie
		setCookie('referente',ref,365);
		setCookie('codice_fiscale',cod,365);
		setCookie('indirizzo_wadsl',adress_wadsl,365);
		setCookie('cap',cap,365);
		setCookie('localita',localita,365);
		setCookie('provincia',provincia,365);
		setCookie('tel',tel,365);
		setCookie('fax',fax,365);
		
		
	}
	

	if(divout==2){
		
	var totale_parziale_1 = 0;
		// verifico IP Pubblico
		if(document.forms['costi1'].elements['ip_pubblico'].checked==true){
		public_ip = document.forms['costi1'].elements['ip_pubblico'].value;
		totale_parziale_1 += parseInt(public_ip);
		setCookie('ip_pubblico',public_ip,365);
		} else {
		setCookie('ip_pubblico','',365);
		}
		// Verifico IP Pubblico Aggiuntivo
		if(document.forms['costi1'].elements['ip_pubblico_agg'].checked==true){
		public_ip_agg = document.forms['costi1'].elements['ip_pubblico_agg'].value;
		totale_parziale_1 += parseInt(public_ip_agg);
		setCookie('ip_pubblico_agg',public_ip_agg,365);

		} else {
		setCookie('ip_pubblico_agg','',365);
		}
		// Verifico LINEA FLAT
		if(document.forms['costi1'].elements['linea_flat'].checked==true){
		flat = document.forms['costi1'].elements['linea_flat'].value;
		n_flat = document.forms['costi1'].elements['n_linee_flat'].value;
		costo_flat = parseInt(flat*n_flat);
		totale_parziale_1 += parseInt(costo_flat);
		setCookie('linea_flat',flat,365);
		setCookie('n_linee_flat',n_flat,365);

		} else {
		setCookie('linea_flat','',365);
		setCookie('n_linee_flat','',365);
		}
		// Verifico ZERO VoIP
		if(document.forms['costi1'].elements['zero_voip'].checked==true){
		voip = document.forms['costi1'].elements['zero_voip'].value;
		n_voip = document.forms['costi1'].elements['n_linee_voip'].value;
		costo_voip = parseInt(voip*n_voip);
		totale_parziale_1 += parseInt(costo_voip);
		setCookie('zero_voip',voip,365);
		setCookie('n_linee_voip',n_voip,365);

		} else {
		setCookie('zero_voip','',365);
		setCookie('n_linee_voip','',365);	
		}
		setCookie('tot_parz_1',totale_parziale_1,365);

	
	}
	
	if(divout==3){
	var totale_parziale_2 = parseInt(getCookie('tot_parz_1'));
		// Verifico Attivazione ADSL
		if(document.forms['costi2'].elements['attivazione_adsl'].checked==true){
		attivazione_adsl = document.forms['costi2'].elements['attivazione_adsl'].value;
		totale_parziale_2 += parseInt(attivazione_adsl);
		setCookie('attivazione_adsl',attivazione_adsl,365);
		} else {
		setCookie('attivazione_adsl','',365);
		}
	
		if(document.forms['costi2'].elements['installazione_standard'].checked==true){
		installazione_standard = document.forms['costi2'].elements['installazione_standard'].value;
		totale_parziale_2 += parseInt(installazione_standard);
		setCookie('installazione_standard',installazione_standard,365);
		} else {
		setCookie('installazione_standard','',365);
		}
		
		if(document.forms['costi2'].elements['ata_voip'].checked==true){
		ata_voip = document.forms['costi2'].elements['ata_voip'].value;
		totale_parziale_2 += parseInt(ata_voip);	
		setCookie('ata_voip',ata_voip,365);
		} else {
		setCookie('ata_voip','',365);
		}
		
		if(document.forms['costi2'].elements['router_wifi'].checked==true){
		router_wifi = document.forms['costi2'].elements['router_wifi'].value;
		totale_parziale_2 += parseInt(router_wifi);
		setCookie('router_wifi',router_wifi,365);
		} else {
		setCookie('router_wifi','',365);
		}
		/*
		if(document.forms['costi2'].elements['access_point_wifi'].checked==true){
		accesspoint_wifi = document.forms['costi2'].elements['access_point_wifi'].value;
		totale_parziale_2 += parseInt(accesspoint_wifi);
		setCookie('access_point_wifi',accesspoint_wifi,365);		
		} else {
		setCookie('access_point_wifi','',365);
		}
		*/
		setCookie('tot_parz_2',totale_parziale_2,365);

	}
	
	if(divin==4){
	var totale_parziale_3 = parseInt(getCookie('tot_parz_2'));
	var txt = document.getElementById("Result");
	
	
	
	var msg = "";
		if(getCookie('ip_pubblico')!=""){
		msg +="IP PUBBLICO :<b style=\"float:right;\">"+getCookie('ip_pubblico')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('ip_pubblico'));
		}
		if(getCookie('ip_pubblico_agg')!=""){
		msg +="IP PUBBLICO AGGIUNTIVO :<b style=\"float:right;\">"+getCookie('ip_pubblico_agg')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('ip_pubblico_agg'));
		}
		if(getCookie('linea_flat')!=""){
		msg +="LINEA FLAT VoIP :<b style=\"float:right;\">"+getCookie('linea_flat')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('linea_flat')*getCookie('n_linee_flat'));
		}
		if(getCookie('n_linee_flat')!=""){
		msg +="N LINEE FLAT VoIP :<b style=\"float:right;\">"+getCookie('n_linee_flat')+"</b><br />";
		}
		if(getCookie('zero_voip')!=""){
		msg +="CONNECTIVIA ZERO VOIP :<b style=\"float:right;\">"+getCookie('zero_voip')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('zero_voip')*getCookie('n_linee_voip'));
		}
		if(getCookie('n_linee_voip')!=""){
		msg +="N LINEE ZERO VoIP :<b style=\"float:right;\">"+getCookie('n_linee_voip')+"</b><br />";
		}
		if(getCookie('attivazione_adsl')!=""){
		msg +="ATTIVAZIONE ADSL :<b style=\"float:right;\">"+getCookie('attivazione_adsl')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('attivazione_adsl'));
		}
		if(getCookie('installazione_standard')!=""){
		msg +="INSTALLAZIONE STANDARD :<b style=\"float:right;\">"+getCookie('installazione_standard')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('installazione_standard'));
		}
		if(getCookie('ata_voip')!=""){
		msg +="FORNITURA ADATTATORE ATA VoIP: <b style=\"float:right;\">"+getCookie('ata_voip')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('ata_voip'));
		}
		if(getCookie('router_wifi')!=""){
		msg +="FORNITURA ROUTER WIFI: <b style=\"float:right;\">"+getCookie('router_wifi')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('router_wifi'));
		}
		/*
		if(getCookie('access_point_wifi')!=""){
		msg +="FORNITURA ACCESS POINT WIFI: <b style=\"float:right;\">"+getCookie('access_point_wifi')+"</b><br />";
		totale_parziale_3 += parseInt(getCookie('access_point_wifi'));
		}
		*/
		totale = (totale_parziale_3/2);
		txt.innerHTML ="<p style=\"border-bottom:1px solid #F90;padding-bottom:11px;\">"+msg+"</p><b style=\"float:right;margin-right:10px;\">"+CurrencyFormatted(totale)+"</b>";
		
		
		// Imposto campi nascosti
		// Anagrafici
		var referente = document.getElementById("_referente");
		var cod_fiscale = document.getElementById("_cod_fiscale");
		var indirizzo_wadsl = document.getElementById("_indirizzo_wadsl");
		var cap = document.getElementById("_cap");
		var attivazione_localita = document.getElementById("_attivazione_localita");
		var provincia = document.getElementById("_indirizzo_wadsl");
		var tel = document.getElementById("_tel");
		var fax = document.getElementById("_fax");
		// Tecnici
		var ip_pubblico = document.getElementById("_ip_pubblico");
		var ip_pubblico_agg = document.getElementById("_ip_pubblico_agg");
		var linea_flat_voip = document.getElementById("_linea_flat_voip");
		var n_linee_flat_voip = document.getElementById("_n_linee_flat_voip");
		var linea_zero_voip = document.getElementById("_linea_zero_voip");
		var n_linee_zero_voip = document.getElementById("_n_linee_zero_voip");
		var attivazione_adsl = document.getElementById("_attivazione_adsl");
		var installazione_standard = document.getElementById("_installazione_standard");
		var router_wifi = document.getElementById("_router_wifi");
		
		// Setto i campi hidden 
		setCookie('referente',ref,365);
		setCookie('codice_fiscale',cod,365);
		setCookie('indirizzo_wadsl',adress_wadsl,365);
		setCookie('cap',cap,365);
		setCookie('localita',attivazione_localita,365);
		setCookie('provincia',provincia,365);
		setCookie('tel',tel,365);
		setCookie('fax',fax,365);
		
		referente.innerHTML = getCookie('referente');
		cod_fiscale.innerHTML =  getCookie('codice_fiscale');
		indirizzo_wadsl.innerHTML =  getCookie('indirizzo_wadsl');
		cap.innerHTML =  getCookie('cap');
		attivazione_localita.innerHTML =  getCookie('localita');
		provincia.innerHTML =  getCookie('provincia');
		tel.innerHTML =  getCookie('tel');
		fax.innerHTML =  getCookie('fax');
		
		ip_pubblico.innerHTML = parseInt(getCookie('ip_pubblico'));
		ip_pubblico_agg.innerHTML = parseInt(getCookie('ip_pubblico_agg'));
		linea_flat_voip.innerHTML = parseInt(getCookie('linea_flat')*getCookie('n_linee_flat'));
		n_linee_flat_voip.innerHTML = getCookie('n_linee_flat')
	 	linea_zero_voip.innerHTML = parseInt(getCookie('zero_voip')*getCookie('n_linee_voip'));
		n_linee_zero_voip.innerHTML = getCookie('n_linee_voip');
		attivazione_adsl.innerHTML = parseInt(getCookie('attivazione_adsl'));
		installazione_standard.innerHTML = parseInt(getCookie('installazione_standard'));
		router_wifi = parseInt(getCookie('router_wifi'));
		
	}
	
$("." + divout).hide();
$("." + divin).fadeIn("fast");
}


// Form Ragistrazione Cliente
function RegistraCliente(){
	
var str = $("#SignupForm").serialize();
	$.ajax({
	type: "POST",
	url: "registra_cliente.php",
	data: str,
	success: function(msg){
    
	$("#note").ajaxComplete(function(event, request, settings){
	if(msg != '') 
	{
	$("#wizardpanel").hide();
	}
	$(this).html(msg);
	});
	}
	
	});

return false;	
}
function showElements(oForm) {
  str = "Form Elements of form " + oForm.name + ": \n"
  for (i = 0; i < oForm.length; i++)
      str += oForm.elements[i].name + "\n"
  alert(str)
}

// Funzioni Newsletter
function OpenNewsletter(id_news){ 
mailwin=dhtmlwindow.open("ajaxbox", "iframe", "http://www.connectivia.it/newsletter.php?id_news="+id_news, "Newsletter", "width=604px,height=500px,resize=1,scrolling=1,center=1")
mailwin.onclose=function(){return window.confirm("Chiudere Connectivia Newsletter?")}
}

// Funzioni Alert
function OpenAlert(){ 
alertwin=dhtmlwindow.open("ajaxbox", "iframe", "http://www.connectivia.it/alert.php", "Connectivia Alert", "width=580px,height=400px,resize=1,scrolling=1,center=1")
alertwin.onclose=function(){return window.confirm("Chiudere Connectivia Alert?")}
setCookie('view_alert',1,365);
}

// Funzioni Webmail
function OpenWebmail(){ 
mailwin=dhtmlwindow.open("ajaxbox", "iframe", "http://mail.connectivia.it", "Webmail", "width=990px,height=500px,resize=1,scrolling=1,center=1")
mailwin.onclose=function(){return window.confirm("Chiudere Connectivia Webmail?")}
}

// Funzioni LiveChat
function OpenLiveChat(){ 
LiveChatwin=dhtmlwindow.open("ajaxbox", "iframe", "http://chatserver.comm100.com/ChatWindow.aspx?siteId=109847&planId=1430&partnerId=-1&visitType=1&byHref=1", "LiveChat", "width=560px,height=480px,resize=1,scrolling=1,center=1")
LiveChatwin.onclose=function(){return window.confirm("Chiudere Connectivia LiveChat?")}
}

function HideWebmail(){
	if(typeof mailwin == "undefined") {
	} else {
	mailwin.hide();
	return false
	}
}

// Funzione Login cliente
function crea_http_req() {
    var req = false;
    if (typeof XMLHttpRequest != "undefined")
        req = new XMLHttpRequest();
    if (!req && typeof ActiveXObject != "undefined") {
        try {
            req=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e1) {
            try {
                req=new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
                try {
                    req=new ActiveXObject("Msxml2.XMLHTTP.4.0");
                } catch (e3) {
                    req=null;
                }
            }
        }
    }
 
    if(!req && window.createRequest)
        req = window.createRequest();
 
    if (!req) alert("Il browser non supporta AJAX");
 
    return req;
}
 
var http_req = crea_http_req();
function invia_dati() {
    var dati_post = "username=" +
                    encodeURIComponent( document.getElementById("username").value ) +
                    "&password=" +
                    encodeURIComponent( document.getElementById("password").value );
 
    http_req.onreadystatechange = gestisci_risposta;
    http_req.open('POST', 'login.php', true);
    http_req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http_req.setRequestHeader("Content-length", dati_post.length);
    http_req.setRequestHeader("Connection", "close");
    http_req.send(dati_post);
}
 
// recupero e gestisco la risposta inviata dal server
function gestisci_risposta() {
    if(http_req.readyState == 4) {
        var esito = http_req.responseText;
        switch (esito) {
          case '1':
          jAlert('username o pasword non presente nel sistema', 'Autenticazione non riuscita');
          break;
 
          case '2':
          jAlert('Logout effettuato con successo', 'Logout');
          break;
 
          case '3':
          jAlert('username o password non inserite', 'Autenticazione non riuscita'); 
          break;
 
          case '4':
          ajaxpagefetcher.load('login_form','member.php', true);
          break;
 
          default:
          jAlert('Risposta del server non riconosciuta:' + esito, 'Autenticazione non riuscita');
        }
    }
}

var area1 
function toggleTextArea() {
if(!area1) {
area1 = new nicEditor({fullPanel : true}).panelInstance('descrizione',{hasPanel : true});
} else {
area1.removeInstance('descrizione');
area1 = null;
}
}


// Fine Funzione Login cliente

function checkEnter(e){
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
	if (keycode == 13){
	invia_dati();
	}
}

function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

var action_param = gup( 'action' );
var action_div = gup( 'div' );
if(action_param!="" && action_div!=""){
	$(function() {
	alert(action_param+ ""+action_div);
	});
}


// Funzione preload hompage
function _body_onload()
{
	setScrollInIE();
	turnAutocompleteOff();
	loff();
	
}

function _body_onresize()
{
	setScrollInIE();
	
}

function _body_onunload()
{
	lon();
	
}
// Fine Funzione preload hompage
detect();


// Get params
function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


function GoTo(sezione){
ajaxpagefetcher.load('content', sezione+'.php',true, ['js/tabs.js', 'js/web.js']);
}

