/**
 * Created by m.niciarelli on 09/06/2015.
 */

jQuery(document).ready(function () {
    /*jQuery(".fc-event").click(function(){
     jQuery(".box-dettaglio-evento").collapse('toggle');
     jQuery(".box-calendario-eventi").collapse('toggle');
     });*/

    /* GESTISCO LA VISIBILITA' DEL MENU SLIDER */
    jQuery("#trigger-slider-menu,#close-slider-menu").click(function () {

        // Set the effect type
        var effect = 'slide';

        // Set the options for the effect type chosen
        var options = 'direction: left';

        // Set the duration (default: 400 milliseconds)
        var duration = 500;
        /*jQuery('#trigger-slider-menu').toggle();*/
        jQuery('.slider-menu').toggle(effect, options, duration);
    });
	
	    /* INIZIALIZIO IL CALENDARIO EVENTI */
		jQuery('.date input').datepicker({
                        format: "dd/mm/yyyy",
                        weekStart: 1,
                        todayBtn: "linked",
                        language: "it",
                        todayHighlight: true
            });
            
            /*           
            $('.date input').on('change', function(){
                $('.datepicker').hide();
            });
            */

	
});

function getContatore(urlServizio){
	$('#bannerEvento').html("");
	//var debug=true;
	$.ajax({
		url: urlServizio,
		type: 'GET',
		dataType: 'jsonp',
		jsonp: 'callback',
		jsonpCallback: 'contatoreCallback',
		timeout: 10000,
		error: function(xhr, ajaxOptions, thrownError){
			//if (debug) alert ('Errore di comunicazione con servizio REST ['+xhr.status+'] ('+ajaxOptions+') '+thrownError);
		},
		success: function(jsonp){

		$('#bannerEvento').html(contatoreFormat(jsonp));
		}
	});
}

function contatoreCallback(data){
	$('#bannerEvento').html(contatoreFormat(data));
}

function contatoreFormat(mycount){	
	mycount += '';
	x = mycount.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';

	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1;
}

function getAjaxWithJSONResponse(_successEvent, _urlService, _errorEvent){
	$.ajax({
		type: 'GET',
		url: _urlService,
		dataType: 'json',
		success: function(data) {
			 _successEvent(data);
		 },
		error: function(xhr, textStatus, errorThrown){
			if(_errorEvent){
				_errorEvent(xhr, textStatus);
			}else{
				if(xhr.status && (xhr.status=="401" || xhr.status=="403")){
					showMessage("fail" ,MSG_USER_UNAUTHORIZED);
				}else if(xhr.responseText && xhr.responseText!=""){
					var json_obj = JSON.parse(xhr.responseText);
					showMessage("fail",json_obj.message);
				}else{
					showMessage("fail");
				}	
				hideLoadingAnimation();
			}
		}
	});	
}

function getMenuServiziOnLine(url){
	var _successEvent=function(data) {
		if( $.isArray(data) &&  data.length ) {
			var items = [];
			$.each(data, function (id, menu) {
				items.push('<li title=\"' + menu.description + '\"><a href=\"' + menu.url + '\"><span class=\"fa ' + menu.icon + '\"></span>' + menu.description + '</a></li>');
			});  
			$(".ul_menu").empty();
			$(".ul_menu").html(items.join(''));
		}
	};
	getAjaxWithJSONResponse(_successEvent,url);	
}

function setCharAt(str,index,chr) {
	if(index > str.length-1) return str;
	str=''+str;
	return str.substr(0,index) + chr + str.substr(index+1);
}

function loadHeaderFoto(urlRest,matricolaCorrente) {
	var url;
	//recupero foto
	url = urlRest + "personeStrutture/getFoto/" + matricolaCorrente;
	$.ajax({
		type: 'GET',
		url: url,
		timeout:7000, //millisecondi
		responseType: 'text',
		complete: function(xhr,status) {
			if(xhr.status > 199 && xhr.status < 300){
				var response = ''+xhr.responseText;
				if(response.startsWith('"') && response.endsWith('"')){
					response =  setCharAt(response,0,"");
					response =  setCharAt(response,response.length-1,"");
				}
				
				$("#profile_header_img").attr("src","data:image/png;base64," + response);
				// $("#profile_header_img").attr("src","data:image/png;base64," + xhr.responseText);
			 
			}else{
				$("#profile_header_img").attr("src","/static/img/anonimo.jpg");
			}
		}
	});
}




// Recupero UToken e notifiche
var wcpRootUrl = '/esc-rest/api/';

function recuperaUToken() {
 var wcpResourcesSite = wcpRootUrl + "resourceIndex";
 $.getJSON(wcpResourcesSite)
 .done(function(data) {
  $.each(data.links, function(key, link) {
   if (link.href) {
    var startIndex = link.href.indexOf("utoken=");
    utoken = link.href.substring(startIndex + 7, link.href.length);
    
    if (utoken) {
             console.log("GetTokenAndNotifications - Retrieved utoken - Utoken = " + utoken);
      return utoken;
        }
   }
  });
 })
  .fail(function() {
   console.log("Errore nel recupero del utoken");
  });
}
function impostaNumeroNotifice(){
 
	var urlUltimaDataLettura = wcpRootUrl + "notifications/count?utoken=" + recuperaUToken() ;
	  var notificationsEl = $(".strumenti-profilo>.notifica-social").last();
	                $.getJSON(urlUltimaDataLettura).done(function(count) {
	  if (count && count > 0) {
	  	 notificationsEl.html(count);
	  	 notificationsEl.removeClass("hidden");
	  } else {
	   	notificationsEl.addClass("hidden");
	  }
	 });
}