/* codice x box di login */

//defaults value
var DEF_RURL = document.location;
//var DEF_ERRURL = 'http://www.ilsole24ore.com/errore.shtml';
var DEF_SITECODE = 'GS';
var DEF_SUBSCRIBE_SCRIPT = 'https://du.ilsole24ore.com/DU/iniziaRegistrazione.aspx';
var DEF_LOGIN_SCRIPT = 'https://du.ilsole24ore.com/du/authfiles/logincentrale.aspx';
var DEF_LOGOFF_SCRIPT = 'https://du.ilsole24ore.com/du/authfiles/logoff.aspx';
var DEF_USERPROFILE_SCRIPT = 'https://du.ilsole24ore.com/DU/Areautente/profiloutente.aspx';
var isAuthenticated = false;
var friendlyName = null;
var lastLogin = null;
var isPremium = -1;
var isPlus = -1;
var PopupAuthenticationTimeout=60000; //milliseconds
var DataOra;
var DEF_SEARCH_URL = "http://www.ricerca24.ilsole24ore.com";
var IMG_URL = "http://www.ilsole24ore.com/img2007/"; 
var IMG_PATH = "http://www.gruppo.ilsole24ore.com/";
var DEF_ERRURL = IMG_PATH + "/Public/IT/000_Home_Page/000_Home_Page_1_1_0_0_0.htm"

// Modified from Bill Dortch's Cookie Functions (hidaho.com) 
// (found in JavaScript Bible)
function setCookie(name,value,days,path,domain,secure) {
	  var expires, date;
	  if (typeof days == "number") {
	    date = new Date();
	    date.setTime( date.getTime() + (days*24*60*60*1000) );
			expires = date.toGMTString();
	  }
	  document.cookie = name + "=" + escape(value) +
	    ((expires) ? "; expires=" + expires : "") +
	    ((path) ? "; path=" + path : "") +
	    ((domain) ? "; domain=" + domain : "") +
	    ((secure) ? "; secure" : "");
}

// Modified from Jesse Chisholm or Scott Andrew Lepera ?
// (found at both www.dansteinman.com/dynapi/ and www.scottandrew.com/junkyard/js/)
function getCookie(name) {
	  var nameq = name + "=";
	  var c_ar = document.cookie.split(';');
	  for (var i=0; i<c_ar.length; i++) {
	    var c = c_ar[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameq) == 0) return unescape( c.substring(nameq.length, c.length) );
	  }
	  return null;
}
 
 
 // from Bill Dortch's Cookie Functions (hidaho.com) 
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function setCookieRitorno() {
	if (getCookie("URLRIT") == null) {
		setCookie("URLRIT",document.location,180,"/");
	}
	return true;
}

function deleteCookieRitorno() {
	if (getCookie("URLRIT") != null) {
		//deleteCookie("URLRIT");
		setCookie("URLRIT",'',-1,"/");
	}
	return true;
}

function getParameter(paramName) {
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	var result = null;
	var pos;
	var key;
	for (var i=0; i<parms.length; i++) {
		pos = parms[i].indexOf('=');
		if (pos > 0) {
			key = parms[i].substring(0,pos);
			if (key == paramName)
			{
				result = unescape(parms[i].substring(pos+1));
			}
		}
	}
	return result;
}

/*
Recupera le informazioni dell'utente stabilendo se si tratta di una connessione anonima o no
*/
function GetUserStatus(){
	var allCookies = document.cookie;	//all cookies
	var soleAuthStart = allCookies.indexOf("SoleAuth");
	
	if (soleAuthStart>=0){
		var soleAuth = allCookies.substring(soleAuthStart,allCookies.indexOf(";", soleAuthStart));
		if (soleAuth!="SoleAuth=") {
			isAuthenticated = true;
			SetFriendlyName();	
		}
	}
}


//Controllo periodico se autenticato
function CheckPopupAuthentication(){
	var allCookies = document.cookie;	//all cookies
	var soleAuthStart = allCookies.indexOf("SoleAuth="); //Start of SoleAuth
	
	if (soleAuthStart>0){	//SoleAuth present
		var soleAuth = allCookies.substring(soleAuthStart,allCookies.indexOf(";",soleAuthStart));
		
		var aSoleAuth = soleAuth.split('=')
		if (aSoleAuth[1].length>0){	//SoleAuth valid
			document.location.reload();
			return;
		}
	}
	
	// riattivo il check		
	setTimeout(CheckPopupAuthentication,PopupAuthenticationTimeout);	
}

function SetFriendlyName(){
	var allCookies = document.cookie;	//all cookies
	var soleUserStart = allCookies.indexOf("SoleUser="); //Start of SoleUser
	var ispremiumIdx;

	if (soleUserStart>0){	//SoleUser present
		var soleUser;	
		if (allCookies.indexOf(";", soleUserStart)>=0)
			soleUser = allCookies.substring(soleUserStart,allCookies.indexOf(";",soleUserStart)); //SoleUser content
		else
			soleUser = allCookies.substring(soleUserStart);
		
		var aSoleUser = soleUser.substring(soleUser.indexOf("=")+1).split(','); 
		
		for (i=0; i<aSoleUser.length; i++)
		{
			if (aSoleUser[i].toLowerCase().indexOf('friendlyname=')>=0)
			{
				isAuthenticated = true;
				ispremiumIdx = aSoleUser[i].toLowerCase().indexOf('&ispremium=');
			    if (ispremiumIdx == -1)
			        ispremiumIdx = aSoleUser[i].length;
			    else
			    {
			    	ispremiumPlusIdx = aSoleUser[i].toLowerCase().indexOf('&premiumlevel=');
			    	if (ispremiumPlusIdx == -1) ispremiumPlusIdx = aSoleUser[i].length;
			    	else isPlus = aSoleUser[i].substring(ispremiumPlusIdx+14);
			    	isPremium = aSoleUser[i].substring(ispremiumIdx+11,ispremiumPlusIdx);
			    }

				friendlyName = aSoleUser[i].substring(aSoleUser[i].indexOf('=')+1,ispremiumIdx);
				break;
			}
		}
	}	
	else{ 
		isAuthenticated = false;
		friendlyName = null;
		isPremium = -1;
		isPlus = -1;
	}
}

function authenticated_user()
{
	var content = '';

    if (document.location.href.indexOf('/IT') > 0)
    {
    	content = '<span class="c_testo">Benvenuto:</span><a id="lnkLogoff" href="" class="c_testo"><b>&nbsp;<span id="spnFriendlyName"></span>&nbsp;(Logout)&nbsp;&gt;</b></a>';
    }
    else
    {
	    content = '<span class="c_testo">Welcome:</span><a id="lnkLogoff" href="" class="c_testo"><b>&nbsp;<span id="spnFriendlyName"></span>&nbsp;(Logout)&nbsp;&gt;</b></a>';
    }
	
	deleteCookieRitorno();
	document.write(content);
}

//disegna la form di log-in
function auth_form() {
	var content = '<div>';
	content += '<form action="" method="post" name="authUser" onsubmit="setCookieRitorno()">';
	content += '<INPUT value="" name="URL" type="hidden"/><INPUT value="BYPOST" name="realSubmit" type="hidden"/>';
	content += '<INPUT type="hidden" name="RURL" value=""/><INPUT type="hidden" name="ERRURL" value=""/>';
	content += '<INPUT type="hidden" name="SC" value=""/>';
	content += '<table cellpadding="0" cellspacing="0" border="0">';
	content += '<tr style="height: 17px;" valign="middle">';
	content += '<td class="c_testo">';
	content += 'id&nbsp;<input name="txtUsername" value="" type="text" class="c_testo" />&nbsp;psw&nbsp;<input name="txtPassword" value="" type="password" class="c_testo" />&nbsp;';
	content += '</td>';
	content += '<td style="height: 17px;"class="hf_entra" style=\"cursor:hand;cursor:pointer;\" onclick="javascript:SubmitLoginUser();">';
	
    if (document.location.href.indexOf('/IT') > 0)
    {
        content += 'Entra <img alt="" style="border-width: 0px;" src="' + IMG_PATH + '/images/ico/freccia_entra.gif" />';
    }
    else
    {
        content += 'Enter <img alt="" style="border-width: 0px;" src="' + IMG_PATH + '/images/ico/freccia_entra.gif" />';
    }
    
    content += '</td>';
    content += '</tr>';
	content += '</table></form></div>';

	document.write(content);
}

function setDUUrls() {
    var hostname = document.location.hostname.toLowerCase();

    if (hostname.indexOf('.dlv.') != -1) { // stage

		DEF_SUBSCRIBE_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/iniziaRegistrazione.aspx';
		DEF_LOGIN_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/authfiles/logincentrale.aspx';
		DEF_LOGOFF_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/authfiles/logoff.aspx';
		DEF_USERPROFILE_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/Areautente/profiloutente.aspx';

		login.LoginUrl  = "http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/authfiles/logincentrale.aspx";
        login.LogoutUrl = "http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/authfiles/logoff.aspx";
        login.UserProfileUrl = "http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/areautente/profiloutente.aspx";
        login.SubscribeUrl = "http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/iniziaregistrazione.aspx";
    }
    else if (hostname.indexOf('.dev.') != -1)   // sviluppo
    {
		DEF_SUBSCRIBE_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/iniziaRegistrazione.aspx';
		DEF_LOGIN_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/authfiles/logincentrale.aspx';
		DEF_LOGOFF_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/authfiles/logoff.aspx';
		DEF_USERPROFILE_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/Areautente/profiloutente.aspx';

        login.LoginUrl  = "http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/authfiles/logincentrale.aspx";
        login.LogoutUrl = "http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/authfiles/logoff.aspx";
        login.UserProfileUrl = "http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/areautente/profiloutente.aspx";
        login.SubscribeUrl = "http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/iniziaregistrazione.aspx";
    }
}

function disegna_auth(){
	setDUUrls();

	
	if (isPremium == "1"){
		
		if (isPlus == "2")
		{
			if (isAuthenticated && this.ShowWellcomeMessage){
				authenticated_user(); 
				{
	if (friendlyName.lastIndexOf("&") != -1 ) {
			  friendlyName = friendlyName.substr(0,friendlyName.lastIndexOf("&"));
			  }
					document.getElementById("spnFriendlyName").innerHTML = friendlyName.length<=20?friendlyName:friendlyName.substring(0,17) + "...";
					document.getElementById("lnkLogoff").href = this.LogoutUrl + "?RURL=" + escape(this.LoginRURL);
				}
			}
		}
		else
		if (isAuthenticated && this.ShowWellcomeMessage){
			authenticated_user(); 
			{
	if (friendlyName.lastIndexOf("&") != -1 ) {
			  friendlyName = friendlyName.substr(0,friendlyName.lastIndexOf("&"));
			  }
				document.getElementById("spnFriendlyName").innerHTML = friendlyName.length<=20?friendlyName:friendlyName.substring(0,17) + "...";
				document.getElementById("lnkLogoff").href = this.LogoutUrl + "?RURL=" + escape(this.LoginRURL);
			}
		}
	}else{
	
		if (isAuthenticated && this.ShowWellcomeMessage){
			authenticated_user(); 
			{
	if (friendlyName.lastIndexOf("&") != -1 ) {
			  friendlyName = friendlyName.substr(0,friendlyName.lastIndexOf("&"));
			  }

				document.getElementById("spnFriendlyName").innerHTML = friendlyName.length<=20?friendlyName:friendlyName.substring(0,17) + "...";
				document.getElementById("lnkLogoff").href = this.LogoutUrl + "?RURL=" + escape(this.LoginRURL);
			}
		}
	}
	
	if (!isAuthenticated && this.ShowLoginForm){
		
		auth_form(); 
		
		{	
			var f = document.forms["authUser"];
			if (getCookie("URLRIT") != null) {	
			
			        if (document.location.href.indexOf("index") < 0) 
			        	f.elements["RURL"].value = getCookie("URLRIT");
			        else
			        	f.elements["RURL"].value = this.LoginRURL;       	
			}else
				f.elements["RURL"].value = this.LoginRURL;       

				f.elements["ERRURL"].value = this.ERRURL;
				f.elements["SC"].value = this.SiteCode;
				f.action = this.LoginUrl;
	
			/*document.getElementById("lnkSubscribe").href = this.SubscribeUrl + "?SiteCode=" + this.SiteCode + "&RURL=" + escape(this.SubscribeRURL) + "&ERRURL=" + escape(this.ERRURL);*/

			if (this.CheckIfAuthenticated && f!='undefined')
				setTimeout(CheckPopupAuthentication,PopupAuthenticationTimeout);
		}
	}
}

function disegna_authprv(){	
	setDUUrls();
	
	auth_formprv(); 
	
	var f = document.forms["authUser"];

	f.elements["RURL"].value = this.LoginRURL;       
	f.elements["ERRURL"].value = this.ERRURL;
	f.elements["SC"].value = this.SiteCode;
	f.action = this.LoginUrl;
}

function CheckAuth()
{
	if (isAuthenticated == false)
	{
		if (document.location.href.toLowerCase().indexOf("private") > 0)
		{
			document.location.href = IMG_PATH + "/Public/IT/000_Home_Page/000_Home_Page_1_1_0_0_0.htm";
		}
	}
}

function __Login() {
	this.LoginRURL = DEF_RURL;										//pagina di ritorno dal login
	this.ERRURL = DEF_ERRURL;											//ERRURL per form di login e registrazione
	this.SiteCode = DEF_SITECODE;									//SiteCode
	this.LoginUrl = DEF_LOGIN_SCRIPT;							//action del form di login
	this.SubscribeUrl = DEF_SUBSCRIBE_SCRIPT;			//url di avvio registrazione
	this.SubscribeRURL = DEF_RURL;								//url di ritorno dalla registrazione (es. secondo livello)
	this.LogoutUrl = DEF_LOGOFF_SCRIPT;						//url di ritorno dal logout
	this.UserProfileUrl = DEF_USERPROFILE_SCRIPT;	//url del link il mio profilo
	this.CheckIfAuthenticated = false;						//flag per l'avvio del timer per il controllo se autenticato
	this.SearchURL = DEF_SEARCH_URL;    					//action url del box di ricerca
	
	this.TestataHome = true;
	setDUUrls_Corporate();
	
	if (document.location.href.toLowerCase().indexOf("/ev_") <= 0)
	{
    	this.DrawLogin = disegna_auth;
	}

/*	this.DrawLoginPrv = disegna_authprv;
	this.DrawLoginError = disegna_prverror;
*/	
	GetUserStatus();
	CheckAuth();
}

var login = new __Login();
login.ShowLoginForm = true;
login.ShowWellcomeMessage = true;
if (document.location.href.toLowerCase().indexOf("/ev_") <= 0)
{
    login.DrawLogin();
}
/*alert('ISAUTHENTICATED: ' + isAuthenticated);*/
/*alert('NAME: ' + friendlyName);*/
/* find codice x box di login */

function cp_show(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	
	if (document.all) {
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	} else{
		posx = e.pageX;
		posy = e.pageY;
	}  
	
	// posx and posy contain the mouse position relative to the document
	document.getElementById("cp_box").style.display = "block";
	document.getElementById("cp_box").style.top = posy + "px";
	document.getElementById("cp_box").style.left = (posx-122) + "px";
	
}

function GetFriendlyName()
{
    if (friendlyName != null)
    {
        return getCookie("URLRITGRUPPO");
    }
    else
    {
        return '';
    }
}

function SubmitLoginUser()
{
	deleteCookieRitornoGruppo();
    document.authUser.submit();
	setCookieRitornoGruppo();
}

function setCookieRitornoGruppo() {
	if (getCookie("URLRITGRUPPO") == null) {
		setCookie("URLRITGRUPPO",document.getElementById("txtUsername").value,180,"/");
	}
	return true;
}

function deleteCookieRitornoGruppo() {
	if (getCookie("URLRITGRUPPO") != null) {
		setCookie("URLRITGRUPPO",'',-1,"/");
	}
	return true;
}

function setDUUrls_Corporate() {
    var hostname = document.location.hostname.toLowerCase();

    if (hostname.indexOf('.dlv.') != -1) { // stage

		IMG_PATH = "http://corporate.dlv.24orepro.in.ilsole24ore.it/SvilCorporate/";
		DEF_SUBSCRIBE_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/iniziaRegistrazione.aspx';
		DEF_LOGIN_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/authfiles/logincentrale.aspx';
		DEF_LOGOFF_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/authfiles/logoff.aspx';
		DEF_USERPROFILE_SCRIPT = 'http://duprovisioning.dlv.24orepro.in.ilsole24ore.it/DU/Areautente/profiloutente.aspx';
        DEF_ERRURL = IMG_PATH + "/Public/IT/000_Home_Page/000_Home_Page_1_1_0_0_0.htm"
    }
    else if (hostname.indexOf('.dev.') != -1)   // sviluppo
    {
		IMG_PATH = "http://corporate.dev.24orepro.in.ilsole24ore.it/SvilCorporate/";
		DEF_SUBSCRIBE_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/iniziaRegistrazione.aspx';
		DEF_LOGIN_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/authfiles/logincentrale.aspx';
		DEF_LOGOFF_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/authfiles/logoff.aspx';
		DEF_USERPROFILE_SCRIPT = 'http://duprovisioning.dev.24orepro.in.ilsole24ore.it/DU/Areautente/profiloutente.aspx';
        DEF_ERRURL = IMG_PATH + "/Public/IT/000_Home_Page/000_Home_Page_1_1_0_0_0.htm"
    }
}

