/* ----------------------------------------------------
 * Reg Expression User Agent Options
 * ------------------------------------------------- */
function isMobile(){
	var regExpMobUserAgents = /iPhone|iPad|iPod|Android|Android Webkit Browser|BlackBerry|Blazer|Bolt|Browser for S60|Doris|Dorothy|Fennec|Go Browser|IE Mobile|Iris|Maemo Browser|MIB|Minimo|NetFront|Opera Mini|Opera Mobile|SEMC-Browser|Skyfire|TeaShark|Teleca-Obigo|WuZard Web/i;
	if(navigator.userAgent.match(regExpMobUserAgents) ){
		return true;	
	}else{
		return false;
	}
}
//alert( navigator.userAgent );
if(isMobile() == true)
{//mobile only
	
}else{// Desktop only
	$(".mobile_only").hide();
}


// Mobile Sharing Window
$("#MobileShareLink").click(function(){
	$("#MobileShareWindow").animate({height: '100%', paddingTop: '80px'});
});
$("#BtnCloseMobileShareWindow").click(function(){
	$("#MobileShareWindow").animate({paddingTop: '0', height: '0%'});
});


// Filtro Città versione MOBILE (no modalbox ma semplice select2)
$("#FilterByCityMobile").change(function(){
	var city = $(this).val();
	window.location.assign(document.SITE_URL+city+'/');
});



function createPlayer(id,video){
    if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
        setTimeout(function(){
             player = new YT.Player(id, { 
              height: '200',
              width: '320',
              videoId: video,
              events: {
                'onReady': onPlayerReady
              }
            });
        },1000);
                             
    }
    else{
        player = new YT.Player(id, { 
          height: '200',
          width: '320',
          videoId: video,
          events: {
            'onReady': onPlayerReady
          }
        });   
    }
} 
  
function onPlayerReady(event) {
    event.target.setVolume(0);
  	event.target.playVideo();
}

function scriviCookie(nomeCookie,valoreCookie,durataCookie)
{
  var scadenza = new Date();
  var adesso = new Date();
  scadenza.setTime(adesso.getTime() + (parseInt(durataCookie) * 60000));
  document.cookie = nomeCookie + '=' + escape(valoreCookie) + '; expires=' + scadenza.toGMTString() + '; path=/';
}


$('.closeCookie a').click(function(){
	$('#cookie-notice').hide();
	$('#cookie-notice').remove();
	
	$.ajax({
		type: "POST",
	  	url: document.SITE_URL+"service/?ws=setcookie",
	  	success: function(response){
			if(response.status==1){
				$('#cookie-notice').hide();
				$('#cookie-notice').remove();
			}
	  	},
	  	dataType: "json"
	});
	return false;
});
    
    



function getElementPos(id){
	var elem = document.getElementById(id);
	var r = elem.getBoundingClientRect()
	//var pos = [r.top, r.right, r.bottom, r.left];	
	return r;
	
	//alert("Top/Left: "+r.top+" / "+r.left+" Right/Bottom: "+r.right+" / "+r.bottom)
}



/* ----------------------------------------------------
 * PopUp Inserzione Sponsor 
 * ------------------------------------------------- */
$("div#sponsorPopup div.controls #close").click(function(){
	
	var pos = getElementPos("pImage");
	$("div#sponsorPopup").animate({top: pos.top+'px'});
	$("div#sponsorPopup").animate({left: pos.left+'px'});
	//$("div#sponsorPopup").animate({width: '0'});
	//$("div#sponsorPopup").animate({height: '0'});
	//$("div#sponsorPopup").fadeOut();
	
});



/* =============================================================
 * Invia Un Messaggio Tramite La Messaggistica Interna
 * ========================================================== */

    function NuovoMessaggioDaForm( id_parent, id_mittente, id_destinatario, messaggio, id_inserzione )
    {
        var url = document.SITE_URL + "action/nuovo_messaggio/";
        $.ajax({
          url: url,
          type: "POST",
          dataType: "JSON",
          data:{ 
            id_parent: id_parent, 
            id_mittente: id_mittente,
            id_destinatario: id_destinatario,
			id_inserzione: id_inserzione,
            messaggio: messaggio
          }
        }).done(function(response){
            if(response.status==0){
                // Messaggio Non Inviato
                console.log(response);
                return false;
            }else if(response.status==1){
                // Messaggio Inviato
                console.log(response);
                return true;
            }
        }).fail(function(error){
            console.log("\n\nErrore Messaggio: " + error + "\n\n");
            return false;
        });
    }
    
    

    
/* ====================================================================
   FORM Contatta Inserzionista | Shop | Deal
* ==================================================================== */
/* 
 * L'utente logato può inviare messaggi direttamente. */ 
if( $("#uid").val() ){
    $("#BtnUserSendMailToShop").click(function(event){
        event.preventDefault();
        var mittente = $("#uid").val();
        var messaggio = $("#messaggio").val();
        var destinatario = $("#fk_id_account").val();
		 var id_inserzione = $("#fk_id_inserzioni").val();
		 if(messaggio.replace(/\s/g,'') != "" ){
             NuovoMessaggioDaForm( 0, mittente, destinatario, messaggio,id_inserzione);
             swal("Messaggio Inviato");
             return false;
         }else{
             swal('Devi compilare tutti i campi');
         }

    });
}

    
    function SendMailToShop(){
        
        var randomPassword = Math.random().toString(36).slice(-8);
        var data = $("#FormSendMailToShop").serialize();
        
       
        var fk_id_account = $("#fk_id_account").val();
		var fk_id_inserzioni = $("#fk_id_inserzioni").val();
        var email = $("#email_account").val();
        var messaggio = $("#messaggio").val();
        
        // New User Registration
        /*$.ajax({
            type:"POST",
            url: SITE_URL+'action/registrazione_nuovo_account/',
            data: data,
            dataType: 'JSON'
        }).done(function(response){
            swal("Ci siamo quasi!", "Ti abbiamo inviato una email all'indirizzo: '"+email+". con le istruzioni per completare l'invio del messaggio.'", "success");
            NuovoMessaggioDaForm(0, response.id_account, fk_id_account, messaggio, fk_id_inserzioni);
        }).fail(function(error){
            console.log(error);
            swal({
                title: 'Ooops! Qualcosa &egrave; andato storto. Riprova tra poco.',
                text: 'Contattaci all\'indirizzo <a href="mailto:info@sihappy.it">info@sihappy.it</a> per risolvere il problema.',
                html:true
            });            
        });*/
        
        
        // Send Email Immediatly By AJAX
         
        $.ajax({
            type: "POST",
            url: SITE_URL + "action/sendemail_to_deal/",
            data: data+"&link="+window.location.href,
            success: function(response){
                if (response.status==1){
                    $("#BtnSendMailToShop").prop("disabled", true);
                    swal(response.message);
                }else if(response.status==0){
                    swal(response.message);
                }
            },
            dataType: 'JSON'
        });
        
    }
    
    
    $('#FormSendMailToShop').validate({
        rules:{
            nome:{
                required:true
            },
            cognome:{
                required:true
            },
            email_account:{
                required:true,
                email:true,
                remote: document.SITE_URL+"service/?ws=check_email"
            },
			password:{
				required: true
			},
			conferma_password:{
				required: true,
				equalTo: "#password"
			},
            telefono:{
                required:false
            },
            messaggio:{
                required:true
            },
            tos_flag:{
                required:true
            }
        },
        messages:{
            nome:{
                required:"Campo Richiesto"
            },
            cognome:{
                required:"Campo Richiesto"
            },
            email_Account:{
                required: "Campo Richiesto",
                email: "Formato E-Mail non valido",
                remote: "E-Mail gi&agrave; registrata. Accedi o Attiva il tuo account."
            },
			password:{
				required: "Campo Richiesto"
			},
			conferma_password:{
				required: "Campo Richiesto",
				equalTo: "Password non corrispondenti"
			},
            telefono:{
                required:"Campo Richiesto"
            },
            messaggio:{
                required:"Cosa desideri dire all'inserzionista?"
            },
            tos_flag:{
                required:"&Egrave; necessario accettare le condizioni per continuare"
            }
        }, 
        errorPlacement: function(error, element){        
           $('<span class="arrow" style="color:red;"></span>').insertBefore(element);
           $('<span class="error" style="color:red;"></span>').insertAfter(element).append(error)
        }       
    });
    
    $("#BtnSendMailToShop").click(function(event){
        event.preventDefault();
        if($("#FormSendMailToShop").valid()) {
            SendMailToShop();
        }
        return false;
    });
    



function rotate(id, degree) {
    if(degree==180)
    {
        degree==179;
    }
    var transform = $(id+" .flip-container").css("-webkit-transform");
    var transform = $(id+" .flip-container").css("-moz-transform");
    var transform = $(id+" .flip-container").css("-ms-transform");
    var transform = $(id+" .flip-container").css("transform");
    var transform = $(id+" .flip-container").css("-o-transform");
    $(id+" .flip-container").css("-webkit-transform", "rotateY("+degree+"deg)");
    $(id+" .flip-container").css("-moz-transform", "rotateY("+degree+"deg)");
    $(id+" .flip-container").css("-ms-transform", "rotateY("+degree+"deg)");
    $(id+" .flip-container").css("transform", "rotateY("+degree+"deg)"); 
    $(id+" .flip-container").css("-o-transform", "rotateY("+degree+"deg)"); 
}

function flip(id){
        $box= $(id);   
	
	
		var opts = {
            		lines: 13, // The number of lines to draw
            		length: 11, // The length of each line
            		width: 5, // The line thickness
            		radius: 17, // The radius of the inner circle
            		corners: 1, // Corner roundness (0..1)
            		rotate: 0, // The rotation offset
            		color: '#FFF', // #rgb or #rrggbb
            		speed: 1, // Rounds per second
            		trail: 60, // Afterglow percentage
            		shadow: false, // Whether to render a shadow
            		hwaccel: false, // Whether to use hardware acceleration
            		className: 'spinner', // The CSS class to assign to the spinner
            		zIndex: 2e9, // The z-index (defaults to 2000000000)
            		top: 'auto', // Top position relative to parent in px
            		left: 'auto' // Left position relative to parent in px
            	};
	
        $front  = $box.find(".front");
        $back   = $box.find(".back");
        
	if($back.find(".galleriaImmaginiInserzione").length>0)
	{
		var id_inserzione= id.replace("#flip-",""); 
		$back.find('.galleriaImmaginiInserzione').load(document.SITE_URL+'galleria_immagini/?id='+id_inserzione+'&template=true')
	}
	else{
		//console.log("Non esiste");
	}
        
        altezza  = $front.height();
        $back.height(altezza);
        
        display= $box.find(".front").hasClass("display");
        
		if(display==true)
		{
			// Check if 
			if(navigator.userAgent.match(/iPhone|iPod/i)){

			var target = document.createElement("div");
			document.body.appendChild(target);
			var spinner = new Spinner(opts).spin(target);
			iosOverlay({
				text: "caricamento",
				duration: 9e9,
				spinner: spinner
			});
               
        	}else{
        		rotate(id,181);	
        	}
            
            $front.removeClass("display").hide();
            $back.fadeIn();
            
             $mappa= $(id+"-map");
             
             if($(id).hasClass("viagogo"))
             {                          
                    $.ajax({
                      type: "POST",
                      url: "https://maps.googleapis.com/maps/api/geocode/json?address=Via%20Pasiano,%20Acireale",
                      success: function(response){ 
                        var res= response.results[0].geometry.location;
                        var lat= res.lat;
                        var lon= res.lng;
                        
                           
                        new GMaps({
                        el: id+"-map",  
                        lat: lat,
                        lng: lon,
                        zoomControl : false,
                        zoomControlOpt: {
                            style : 'SMALL',
                            position: 'TOP_LEFT'
                        },
                        panControl : false,
                        streetViewControl : false,
                        mapTypeControl: false,
                        scrollwheel: false,
                        navigationControl: false,
                        mapTypeControl: false,
                        scaleControl: false,
                        draggable: false,
                        overviewMapControl: false
                        }).addMarker({
                            lat: lat,
                            lng: lon,
                            title: 'Informazioni',
                            infoWindow: {
                              content: '<p>{$titolo}</p>'
                            }
                        });
                      },
                      dataType: "json"
                    });
             }
             else{
                  lat= $mappa.attr("data-lat"); 
                  lon= $mappa.attr("data-lon"); 
                  
                     
                    new GMaps({
                    el: id+"-map",  
                    lat: lat,
                    lng: lon,
                    zoomControl : false,
                    zoomControlOpt: {
                        style : 'SMALL',
                        position: 'TOP_LEFT'
                    },
                    panControl : false,
                    streetViewControl : false,
                    mapTypeControl: false,
                    scrollwheel: false,
                    navigationControl: false,
                    mapTypeControl: false,
                    scaleControl: false,
                    draggable: false,
                    overviewMapControl: false
                    }).addMarker({
                        lat: lat,
                        lng: lon,
                        title: 'Informazioni',
                        infoWindow: {
                          content: '<p>{$titolo}</p>'
                        }
                    });
                  
             }
      
     
       }
       if(display==false){
	       			
			//$(id).find(".btn-web-link").trigger( "click" );
			//var href= $(id).find(".btn-web-link").attr("href");
			//setTimeout(function(){window.open(href,'_blank');},1000);
			
			//notification.hide(spinner);
			//location.href= $(id).find(".btn-web-link").attr("href");               
			//return false;
	       
		    rotate(id,0);
		    $front.show().addClass("display");
		    $back.hide();
	       
	       // Check if 
			/*var target = document.createElement("div");
			document.body.appendChild(target);
			var spinner = new Spinner(opts).spin(target);
			iosOverlay({
				text: "caricamento",
				duration: 9e9,
				spinner: spinner
			});*/
			
			setTimeout(function(){
				$('.ios-overlay-show').fadeOut();
				$('.ios-overlay-show').remove();
			},2000);

			return false; 
        }     
}  
 
$('#entry-list').on("click", '.flipBoxLink', function(e) {
	
    var id= $(this).data("id");
	if ($(e.target).parent().hasClass('link_esterno')) {      
    }
    else{
        video= $("#yt-"+id).attr("rel");
        createPlayer("yt-"+id,video);        
        flip("#flip-"+id);
    }      
}); 

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   pos -= (node.data.substr(0, pos).toUpperCase().length - node.data.substr(0, pos).length);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};


/* -------------------------------------------------
 * Mappa
 * ---------------------------------------------- */
function apriMappa(){
    $('#openMap').html("<img src='"+SITE_URL+"images/map.png'/>");
    $('body').css("overflow","hidden");
    $('#cityMap').animate({
        opacity: 1, 
        top: "100",
      },1000);
    $('#cityMap').removeClass("closeMap"); 
}
function chiudiMappa(){
    $('#openMap').html("<img src='"+SITE_URL+"images/map.png'/>");
    $('body').css("overflow","auto");
    $('#cityMap').animate({
    opacity: 1,
    top: "-2000",
    },1000);
    $('#cityMap').addClass("closeMap");    
}



/* --------------------------------------------------------------------
		Messaggi Utente
 * ----------------------------------------------------------------- */
/* Get Last Message By AJAX */
 function checkNewMessages()
 {
	var url = document.SITE_URL + "action/messaggi_nuovi/";
	$.ajax({
	  type: "POST",
	  url: url,
	  success: function(response){
	      if(response.length > 0){
			$("#messagesNotify").text(response.length);    	
	      }else if(response.length == 0){
	          // Nessun Messaggio Da Leggere...
	      }else{
	          // Altri Problemi...
	      }
	  },
	  dataType: "JSON"
	});
}


function initSwiper() {
    const swiper = new Swiper('.swiper-container', {
        // Optional parameters
        direction: 'horizontal',
        loop: true,
        speed: 4000,
        autoplay: {
            delay: 1,
            disableOnInteraction: false,
        },

        // If we need pagination
        //pagination: {
        //    el: '.swiper-pagination',
        //},

        // Navigation arrows
        //navigation: {
        //    nextEl: '.swiper-button-next',
        //    prevEl: '.swiper-button-prev',
        //},

        // And if we need scrollbar
        //scrollbar: {
        //    el: '.swiper-scrollbar',
        //},
        slidesPerView: 5,
        spaceBetween: 20,
        breakpoints: {
            200: {
                slidesPerView: 2,
                spaceBetween:55,
            },
            440: {
                slidesPerView: 2,
                spaceBetween:5,
            },
            640: {
                slidesPerView: 3,
                spaceBetween: 10,
            },
            992: {
                slidesPerView: 4,
            },
            1200: {
                slidesPerView: 5,
            },
        }
    });

    $('.swiper-container').on('mouseenter', function(e){
        console.log("enter");
        swiper.autoplay.stop();
    })
    $('.swiper-container').on('mouseleave', function(e){
        console.log("leave");
        swiper.autoplay.start();
    })
}


$(document).ready(function() {
    var bodyId = $('body').attr('id');

    if($(".select").length > 0){
        $(".select").select2();
    }

    //Navigation Menu Slider
    $('#nav-expander').on('click',function(e){
        e.preventDefault();
        $('body').toggleClass('nav-expanded');
    });
    $('#nav-close').on('click',function(e){
        e.preventDefault();
        $('body').removeClass('nav-expanded');
    });

	checkNewMessages();

	/* -------------------------------------------------
	 * Selezione Categorie
	 * ---------------------------------------------- */
	
	 $(".categorie_sito").change(function(event){
	    var slug = $(event.target).val();
        window.open(slug + "/", "_self");
    });

	 if(bodyId === 'index') {
         initSwiper();
     }

	/*
	$('#categorie_sito').select({
	  containerCssClass: 'categorie_sito',
	  dropdownCssClass: 'categorie_sito'
	});
	*/ 

/* ----------------------------------------------------
 * "Search" Side Panel
 * ------------------------------------------------- */        
    $('#panelHandleSearch').click(function() {            
        if($(this).hasClass("add"))
        { 
            $(this).removeClass("add");
            $('#sidePanelVetrina, #sidePanel').animate({
                left: '-300px' 
            }, 800); 
            
            $('#sidePanelSearch').animate({	
                    left: '-300px' 
                }, 800);
        }
        else{
		$('#inputCerca').focus();
            $(this).addClass("add");
             $('#sidePanelSearch').animate({
                'left': '0px'
            }, 900); 
            
            $('#sidePanel, #sidePanelVetrina').animate({	
                    left: '-360px' 
            }, 800);
           
        }
    });
    
    /* ----------------------------------------------------
 * "Vetrina" Side Panel
 * ------------------------------------------------- */        
    $('#panelHandleVetrina').click(function() {            
        if($(this).hasClass("add"))
        { 
            $(this).removeClass("add");
            $('#sidePanelVetrina, #sidePanelSearch').animate({
                left: '-300px' 
            }, 800);
            
            $('#sidePanel').animate({	
                    left: '-300px' 
                }, 800);
        }
        else{
            $(this).addClass("add");
             $('#sidePanelVetrina').animate({
                'left': '0px'
            }, 900); 
            
            $('#sidePanel, #sidePanelSearch').animate({	
                    left: '-360px' 
            }, 800);
           
        }
    });
	
	    
	/* ----------------------------------------------------
 	* Facebook Side Panel 
 	* ------------------------------------------------- */
    $('#panelHandle').click(function() {            
        if($(this).hasClass("add"))
        {
            $(this).removeClass("add");
            $('#sidePanel').animate({	
                left: '-300px' 
            }, 800);
            
              $('#sidePanelVetrina, #sidePanelSearch').animate({
                left: '-300px' 
            }, 800);
        }
        else{
            $(this).addClass("add");
             $('#sidePanel').animate({
                'left': '0px'
            }, 900);
            
            $('#sidePanelVetrina, #sidePanelSearch').animate({
                left: '-360px' 
            }, 800);
           
        }
    }); 

    $('#searchBoxInput').click(function(e) {
        idCheck= e.target.id;
        
        if(idCheck=='inputCerca')
        {}else{
            if($(this).hasClass("add"))
            {       
                  $(this).removeClass("add");
                  $('#searchBoxInput').animate({
                    right: '-175px' 
                }, 800);
            }
            else{
                 $("#inputCerca").focus(); 
                $(this).addClass("add");
                 $('#searchBoxInput').animate({
                    'right': '0px'
                }, 900);
               
            }
        }
    }); 


                
    $('#openMap').click(function(){
        check= $('#cityMap').hasClass("closeMap");
        
        if(check==true)
        {
            apriMappa();
        }
        else{
           chiudiMappa();
        }
        
        
    }); 
    
    
	$(".theme div").click(function(){
		var color = $(this).attr("rel");
    	$("#relCss").attr("href", SITE_URL+"views/templates/sihappy/css/general/"+color+".css");
		$(".logo-sihappy").attr("src", SITE_URL+"views/templates/sihappy/img/logo"+color+".png");   
   
   	
    	//scriviCookie('theme', color, 240);
    
	    $.ajax({
		    type: "POST",
		    url: '../ajax/set_theme.php',
		    data: 'theme='+color,
		    dataType: "html",
			success: function(response){
				console.log(response);
			},
			error: function(response){						
				console.log("error: " . response);
			}
		});
	    
	    /*
	    $.post('../ajax/set_theme.php', {
			theme: color       	
	    }).done(function(data){
	   		console.log("Theme to Cookie: " + data);
		}).fail(function(data){
	       	console.log("Theme to Cookie: " + data);
	    });
		*/
		       
       console.log(color);
	});
    
    $('button[data-target=#cities]').click(function(){
        setTimeout(function(){$('#cercaCity').focus();},1000);
    });
    
    function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
    }
    $('#cercaCity').keyup(function(){
        var parola= $('#cercaCity').val();
        $(".tabbable").removeHighlight();
         $(".tabbable").highlight(parola);
        var l= parola.slice(0,1);
        if(l=='a' || l=='b' || l=='c' || l=='d' || l=='e' || l=='f')
        {
            $("#clicca1").click();
        }
        
         if(l=='g' || l=='h' || l=='i' || l=='l' || l=='m')
        {
            $("#clicca2").click();
        }
        
         if(l=='n' || l=='o' || l=='p' || l=='q' || l=='r')
        {
            $("#clicca3").click();
            
        }
        
         if(l=='s' || l=='t' || l=='u' || l=='v' || l=='z')
        {
            $("#clicca4").click();
        }
        
        $(".cities .tab-content ul li a").show();
        
        if(parola.length>1)
        {
            $(".cities .tab-content ul li a").hide();
            $(".cities .tab-content ul li a:contains('"+capitalizeFirstLetter(parola)+"')").show();
        }
    });   
     
 
 
	$(document).on('click', function (e) {
		if($('#cities').hasClass( "open" ))
		{
		    if ($(e.target).closest("#cities").length === 0) {
			 showHideBox(0);
		    }
	    }
	});
	
	
	
	/* ====================================================================
		Email Contatti Sito
	 * ================================================================= */
	function InvioEmailContatti(){
		if( $("#g-recaptcha-response").val() != "" )
		{
			/*
			var mySecret = $(".g-recaptcha").attr('data-sitekey');
			var myResponse = $("#g-recaptcha-response").val();
			$.post('https://www.google.com/recaptcha/api/siteverify', {
				secret: mySecret,
				response: myResponse
			}).done(function(response){
				console.log(response);
			}).fail(function(response){
				console.log(response);
			});
			*/	
			//XMLHttpRequest cannot load https://www.google.com/recaptcha/api/siteverify. 
			//No 'Access-Control-Allow-Origin' header is present on the requested resource. 
			//Origin 'http://www.sihappy.it' is therefore not allowed access.
		
			var data = $("#InvioEmailContatti").serialize();
				$.ajax({
					type: "POST",
					url: document.SITE_URL + "action/sendemail/",
					data: data,
					success : function(response) {
						if (response.status==1){
							$("#BtnSubmitMessage").prop("disabled", true);
							swal(response.message);
						}else if(response.status==0){
							swal(response.message);
						}
					},
					dataType : 'JSON'
				});
			}
			return false;
	}
	
	$('#InvioEmailContatti').validate({
		rules:{
			nome:{
				required:true
			},
			email:{
				required:true
			},
			telefono:{
				required:false
			},
			oggetto:{
				required:true
			},
			messaggio:{
				required:true
			},
			copia_mittente:{
				required:false
			},
			tos_flag:{
				required:true
			}
		},
		messages:{
			nome:{
				required:"Campo richiesto."
			},
			email:{
				required:"&Egrave; necessario indicare almeno la tua email."
			},
			telefono:{
				required:"Campo richiesto."
			},
			oggetto:{
				required:"Dicci di cosa si tratta."
			},
			messaggio:{
				required:"&Egrave; necessario scrivere il contenuto del tuo messaggio."
			},
			copia_mittente:{
				required:"Campo richiesto."
			},
			tos_flag:{
				required:"Per inviare il messaggio accetta la privacy policy."
			}
		},
		errorPlacement: function(error, element){
           $('<span class="arrow" style="color:green;"></span>').insertBefore(element);
           $('<span class="error" style="color:red;"></span>').insertAfter(element).append(error)
        },
        submitHandler: function(){
            if( $("#InvioEmailContatti").valid() ){
               InvioEmailContatti();    
            }
        }
	});


    $("#BtnSubmitMessage").on("click",function(event){
        event.preventDefault();
        if( $("#InvioEmailContatti").valid() ){
            InvioEmailContatti();
        }
    })
	
	
	
	
	
	/* --------------------------------------------------------------------
		Iscrizione News Letter
	 * ----------------------------------------------------------------- */
	$("#newsletterSubmit").click(function() {
	
		//var data = $(this).serialize();
		var actionUrl = "http://c6a4c.s56.it/frontend/subscribe.aspx";
		
		var name  = ''+$("#iscrizioneNewsletter #newsletterName").val();
		var email = ''+$("#iscrizioneNewsletter #newsletterEmail").val();
		var city  = ''+$("#iscrizioneNewsletter #newsletterCitta").val();
		var list  = '3';
		var confirm = 'on';
		
		if(name==='' || email==='' || city===''){
			$("#contact.iscrizioneNewsletter").append("<div id=\"newsletterMessage\"><div class=\"message\">Tutti i campi sono obbligatori</div></div>");
			$("#newsletterMessage div").animate({top: '-264px'});
			var t= setTimeout(function(){
				$("#newsletterMessage").animate({opacity: '0'}, 3000, function(){
					$("#newsletterMessage").remove();
				});
			}, 2000);
			
		}else{
			$.post(actionUrl, {
			name: name,
			email: email,
			campo4: city,
			list: list
			}).done(function(data){
				$("#contact.iscrizioneNewsletter").append("<div id=\"newsletterMessage\"><div class=\"message\">"+data+"</div></div>");
				$("#newsletterMessage div.message").animate({top: '-264px'});
				var t= setTimeout(function(){
					$("#newsletterMessage").animate({opacity: '0'}, 3000, function(){
						$("#newsletterMessage").remove();
					});
				}, 2000);
			}).fail(function(data){
				console.log(data)
			});
				
		}
		
		return false;
	});
	
	
}); // END of $(document).ready()

/*function showNumber(number){

    $("#itc-see-number").hide();
    var itcCallMeLabel = $("#itcCallMeLabel").html();
    var html =`<a href="tel:${number}">${number} ${itcCallMeLabel}</a>`;

    $("#itc-number").append(html);
}

function getNumber(id_utenti, id_inserzioni){

    $.ajax({
        type: "POST",
        url: document.SITE_URL + "action/get_number/",
        data: { "id_utenti": id_utenti , "id_inserzioni": id_inserzioni},
        success : function(data) {

            showNumber(data.telefono);
        },
        dataType : 'JSON'
    });
    return false;
}

$("#itc-see-number").on("click",function(event){

    event.preventDefault();

    var id_utenti = $(this).data('idutenti');
    var id_inserzioni = $(this).data('idinserzioni');

    getNumber(id_utenti, id_inserzioni);
});*/

$('#lettersTabs a' ).click( function ( e ) {
  e.preventDefault();
  $( this ).tab( 'show' );
});



