var $j = jQuery.noConflict();
var cookieName = "ugcCookie";
var cookiePresence = false;
var autenticationCall = "http://servizi.mediaset.it/Vugc/perform_login/ugcSession.jsp";
var customerLoginCall = "http://servizi.mediaset.it/Customer/Customer/auth_Light_json.jsp";
var deleteUgcSessionCall = "http://servizi.mediaset.it/Vugc/perform_login/ugcSessionDel.jsp"
var jsonPath = "http://www.16mm.it/json";

var responseAutentication =  new Array();
var autErrorMsg = "DATI AUTENTICAZIONE ERRATI";

function autenticationLightCustomerFromHeader(username, password){  
	//console.log("autenticationLightCustomer SUCCESS");
	var autenticationCallUrl = customerLoginCall + "?srvc=0&user=" + username + "&pwd=" + password + "&callback=?";
	//console.log('PATH AUTENTICATION COMPLETA: '+autenticationCallUrl);
	try{
		//Chiamata di autenticazione che permette l'utilizzo del single signon su customer (deve essere effettuata dal client utente per legare la sessione del browser utente al customer)
		$j.ajax({
		  type: 'GET',
		  
		  url: customerLoginCall,
		  data: "user=" + username + "&pwd=" + password + "&srvc=0&CMD=1&portal=16mm",
		  dataType: "jsonp",		  		 
		  async: false,		  
		  success: function(data){
			try{
				var resp = eval(data);
				
				var errCode = resp.response[0].result;
										
				if(errCode != "OK") {
					alert("Errore nei dati di autenticazione");
					
				} else {
					
					//setCookie($j('#usernameId').val(), jsonPath); 
					var exp = new Date();
					//document.cookie = "nonProfilato=; expires=" + exp.toGMTString() + '; path=/';
					setCookie(resp.response[0].username, jsonPath); 
					//getUser();
					//console.log("TODO USERNAME IN TESTATA: "+username);
					//leeCookie();
					
					window.location.reload();
					
				}

		  
			}catch(e){ 
			//console.log("ERRORE IN AUTENTICAZIONE"); 
			}
		  },
		  error: function(data){
				//console.log("ERRORE IN AUTENTICAZIONE");
		  }   
		});
		
	}catch(e){ 
		//console.log("ERRORE IN AUTENTICAZIONE");
	}
	
}

function setCookieNP(userName)
{
	document.cookie = cookieName + '=' + userName +'||||';
}

function setCookie(userName, pathJson)
{
  var urlPathJson = pathJson+'/'+userName+'.json';
  //console.log('XXXX SET COOKIE: '+userName+' URL JSON: '+urlPathJson);
  var valueCookie;
  var nick;
  var pathImage;
  var gender;

  try{
		$j.ajax({
			url: urlPathJson,
			async: false,
			cache: false,
			type: 'get',
			dataType: "JSON",
			success: function (data) {
				// Carica i dati dalla JSP e crea il value cookie
				//var myJSON = jQuery.parseJSON(data);
				
		
				nick = data.user_data.nickname;
				pathImage = data.user_data.image;
				gender = data.user_data.sesso;
				
				if( gender =='m'){gender ='male'}
				if( gender =='f'){gender ='female'}
				
				valueCookie = userName+"||"+nick+"||"+pathImage+"||"+gender;
				document.cookie = cookieName + '=' + valueCookie + '; path=/';
				//console.log('COOKIE SCRITTO: '+document.cookie);
			},
			error: function(xhr,err) {
				//console.log("fail Ajax");
				//console.log("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
				//console.log("responseText: "+xhr.responseText);
			}		
		});
  }catch(e){ 
	//console.log("## CATCH AJAX SET COOKIE ERROR");
	//console.log(e);
  }
  	
}

function getUser()
{  
  //console.log("XXXX GET User");
  if (document.cookie.length > 0)
  {
    var inizio = document.cookie.indexOf(cookieName + "=");
    if (inizio != -1)
    {
      inizio = inizio + cookieName.length + 1;
      var fine = document.cookie.indexOf("||",inizio);
      if (fine == -1) fine = document.cookie.length;
      return unescape(document.cookie.substring(inizio,fine));
    }else{
       return "";
    }
  }
  return "";
}

function getNick()
{  
  //console.log("XXXX GET Nick");
  if (document.cookie.length > 0)
  {
    var inizio = document.cookie.indexOf(cookieName + "=");
    if (inizio != -1)
    {
      inizio = inizio + cookieName.length + 1;
	  var inizioNick = document.cookie.indexOf("||",inizio) + 2;
	  //console.log("inizioNick "+inizioNick);
	  //*DEBUG*/ alert('inizioNick ='+ inizioNick);
	  
      var fine = document.cookie.indexOf("||",inizioNick);
	  
      if (fine == -1) fine = document.cookie.length;
		//*DEBUG*/	alert('inizio = '+inizio+' inizioNick = ''fine = '+ fine);
	    //console.log("Fine "+fine);
		//*DEBUG*/alert('nickaname =' + unescape(document.cookie.substring(inizioNick,fine)));
		
      return unescape(document.cookie.substring(inizioNick,fine));
	  
    }else{
       return "";
    }
  }
  return "";
}

function checkCookie()
{  
  //console.log("XXXX CHECK Cookie");
  if (document.cookie.length > 0 && document.cookie.indexOf(cookieName + "=") != -1)
  {	
	return true;
  }else{
	return false;
  }
  
}

function deleteCookie() { 
	//console.log("XXXX DELETE Cookie");
	var exp = new Date(); 
	exp.setTime (exp.getTime() - 1); 
	document.cookie = cookieName + "=; expires=" + exp.toGMTString() + '; path=/';
	document.cookie = "nonProfilato=; expires=" + exp.toGMTString() + '; path=/';
	
	
	try{
		//Chiamata di cancellazione sessione da customer
		$j.ajax({
		  type: 'GET',
		  
		  url: customerLoginCall,
		  data: "user=&pwd=&srvc=0&CMD=2&portal=16mm",
		  dataType: "jsonp",		  		 
		  async: false,		  
		  success: function(data){
			try{
				//var resp = eval(data);
				//console.log('SUCCESS');

		  
			}catch(e){ 
				//console.log("ERRORE IN AUTENTICAZIONE"); 
			}
		  },
		  error: function(data){
				//console.log('ERROR');
				
		  }   
		});
		
		var autenticationCallUrl = deleteUgcSessionCall+"?callback=?";
		//console.log('PATH AUTENTICATION COMPLETA: '+autenticationCallUrl);
		//Chiamata per pulizia token per identificazione sessione utente sul app customer mantenuto in sessioen da app ugc
		$j.getJSON(autenticationCallUrl, function(data) {
			//console.log(data.message);	
			//location.reload();
			window.location.reload();			
		});	
		
	}catch(e){ 
		//console.log("ERRORE IN AUTENTICAZIONE");
	}
	
	
	
	
	//http://pre-servizi.mediaset.it:8580/Customer/Customer/auth_Light.jsp?portal=16mm&CMD=2&srvc=0&user=matteoPasqualini&pwd=xxx
	
	
	
	
	//console.log("Valore Cookie DELETE: "+document.cookie);
}

function leggiCookie(){
	console.log("Valore Cookie LEGGI: "+document.cookie);

}

