var blnLogged = false;
var USER_UAB_TYPE = "";
var IS_TRIAL_USER = false;

function using(jsFile) {
    document.write('<script type="text/javascript" src="'
    + jsFile + '"></script>');
}
using('http://static.yalp.alice.it/js/common/aa/ahtv_login.js');
using('/js/jquery.js');
using('/js/scriptAJAX_FMK.js');
//using('/trialusers.js');


function logged(isFirstTime, isAHTvUser, userProfileType, isNewUser, hasPendingData, userUabType, userCli) {
    //  alert("isAHTvUser:" + isAHTvUser + " - isNewUser:" + isNewUser + " - userProfileType:" + userProfileType + " - userUabType:" + userUabType);

    showFrame(); //visualizza il frame con la login

    USER_UAB_TYPE = userUabType.toUpperCase();

    /********* Filtro utenti *********/
    //IS_TRIAL_USER = isTrialUser(userCli);
    IS_TRIAL_USER = false;
    /*****************************/

    if ((userProfileType == "4") && (isFirstTime == "true")) {
        document.location.href = "/ahtv/MyHTV/basic.html";
        return false;
    }
    if (((userProfileType == "3")) && (isFirstTime == "true")) {
        document.location.href = "/ahtv/MyHTV/7_mega.html";
        return false;
    }
    if ((userProfileType == "2") && (isFirstTime == "true") && (isAHTvUser == "false")) {
        document.location.href = "/ahtv/MyHTV/7_mega.html";
        return false;
    }
    if ((isAHTvUser == "false") && (isFirstTime == "true")) {
        displayErrorMsgLogin('Il tuo profilo non è abilitato. Possono utilizzare i servizi sotto autenticazione solo gli utenti Alice home TV.');
        return false;
    }
 
    if ((isNewUser == "true") && (isAHTvUser == "true")) {
        switch (userProfileType) {
            case "1":
                document.location.href = 'http://' + window.location.hostname + "/ahtv/MyHTV/conferma_utente_gold_convergente.html";
                return false;
                break;
            case "2":
                document.location.href = 'http://' + window.location.hostname + "/ahtv/MyHTV/conferma_utente_gold.html";
                return false;
                break;
            default:
        }
    }
 
    if (isFirstTime == "true") {
        var addressUrl = document.location.href.toLowerCase();
        if ((addressUrl.indexOf("guidatv") != -1) || (addressUrl.indexOf("ahtv") != -1)) {
            var nrandom = Math.round(Math.random() * 1000000);
            var tabGuidaTV = "";

            if ((addressUrl.indexOf("guidatv") != -1) && (addressUrl.indexOf("tab=") == -1))
                tabGuidaTV = "&tab=0";

            var strRedirect = document.location.href;
            if (strRedirect.indexOf("?") != -1)
                strRedirect = strRedirect + "&counter=" + nrandom + tabGuidaTV;
            else
                strRedirect = strRedirect + "?counter=" + nrandom + tabGuidaTV;

            var parFinalUrl = getParameterTop("finalurlok");

            if (parFinalUrl != "")
                strRedirect = parFinalUrl;

            document.location.href = decode(strRedirect);
            return false;
        }
    }

    if ((isAHTvUser == "true") && (hasPendingData == "true")) {
        if (document.location.href.indexOf("avvisi_") != -1) {
            var valCookie = getCookie("AHTV_CLOSEPENDINGDATA");
            if (valCookie == "") {
                setCookie("AHTV_CLOSEPENDINGDATA", "true", null)
                displayErrorMsgLogin('Il tuo cellulare o la tua mail non risultano ancora validate. <BR>Vai alla sezione <A HREF="/ahtv/MyHTV/avvisi_recapiti.html"><STRONG>I tuoi recapiti</STRONG></A> per confermare i tuoi dati. ');
            }
        }
    }

    /*trial users*/
    if (isAHTvUser == "true") {
        if (IS_TRIAL_USER) {
            if (USER_UAB_TYPE == 'MASTER')
                $('#naviMytv_ahtv_MASTER_TRIAL').show();
            else
                if (USER_UAB_TYPE == 'SUB')
                $('#naviMytv_ahtv_SUB_TRIAL').show();
            else
                $('#naviMytv_ahtv').show();
        } else {
            if (USER_UAB_TYPE == 'MASTER')
                $('#naviMytv_ahtv_MASTER').show();
            else
                if (USER_UAB_TYPE == 'SUB')
                $('#naviMytv_ahtv_SUB').show();
            else
                $('#naviMytv_ahtv').show();
        }
    }
    else {
        $('#naviMytv').show();
    }

	$('#tool_areariservata').show();

    /*
    if (isAHTvUser == "true") {
    if (userUabType.toUpperCase() == 'MASTER')
    $('#naviMytv_AHTV_MASTER').show();
    else
    $('#naviMytv_AHTV').show();
    }
    else {
    $('#naviMytv').show();
    }
    */
    blnLogged = true;
    loadLoggedSession();

    try {
        EVENT_POST_LOGIN();
    }
    catch (e)
    { }
}

function isTrialUser(cli) {
    for (var i = 0; i < TRIAL_USERS.length; i++) {
        if (cli == TRIAL_USERS[i])
            return true;
    }
    return false;
}

function unlogged() {
    blnLogged = false;
    delCookie("AHTV_CLOSEPENDINGDATA");

	//$('#naviMytv_ahtv_MASTER_TRIAL').hide();
    //$('#naviMytv_ahtv_SUB_TRIAL').hide();
    $('#naviMytv_ahtv_MASTER').hide();
    $('#naviMytv_ahtv_SUB').hide();
    $('#naviMytv_ahtv').hide();
    $('#naviMytv').hide();

    SetCookie("AHTV_COMMUNITY", "", null, "/", document.location.hostname, null);
    //SetCookie("AHTV_GDI", "", null, "/", document.location.hostname, null);

	//SetCookie("aa.sandbox.attribute.spc", "", null, "/", document.location.hostname, null);
	//SetCookie("aa.sandbox.attribute.spc.token", "", null, "/", document.location.hostname, null);
	
	SetCookie("aa.sandbox.params", "", null, "/", document.location.hostname, null);

    logout();
}

function loadMySelMenu() {
	if	(myMenuSel == "ACQUISTI"){

		$("#navi_" + myMenuSel).attr("className", "bott_acquisti_att");
		$("#navi_ahtv_" + myMenuSel).attr("className", "bott_acquisti_att");
		$("#navi_ahtv_MASTER_" + myMenuSel).attr("className", "bott_acquisti_att");
		$("#navi_ahtv_SUB_" + myMenuSel).attr("className", "bott_acquisti_att");

	}else{
	
		$("#navi_" + myMenuSel).attr("className", "select");
		$("#navi_ahtv_" + myMenuSel).attr("className", "select");
		$("#navi_ahtv_MASTER_" + myMenuSel).attr("className", "select");
		$("#navi_ahtv_SUB_" + myMenuSel).attr("className", "select");
		//$("#navi_ahtv_MASTER_TRIAL_" + myMenuSel).attr("className", "select");
		//$("#navi_ahtv_SUB_TRIAL_" + myMenuSel).attr("className", "select");
	}	 
	//document.getElementById("navi_AHTV_" + myMenuSel).className = "selected";
}

function loadLoggedSession() {

    var url = "http://aa.alice.it/aa-activity/cookies/slat?aa-ref=ahtv&rndNumber=";
    var rndNumber = Math.floor(Math.random() * 100000);
    document.getElementById("ifrLoginSession").src = url + rndNumber;
}

function checkMail(strEmail, blnMandatory) {
    if ((strEmail == "") && (blnMandatory == true))
        return false;

    var x = strEmail;
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(x))
        return true;
    else
        return false;
}

/*Min 3 - Max 15 caratteri, solo lettere minuscole e numeri*/
function checkCommunityInput(x) {
    var filter = /^([a-z0-9]{3,15})$/;
    return filter.test(x)
}
/*numerico 4 cifre*/
function checkCommunityPin(x) {
    var filter = /^([0-9]{4,4})$/;
    return filter.test(x)
}
/*telefono cellulare*/
function checkCommunityPhone(x) {
    var filter = /^(3[0-9]{9,9})$/;
    return filter.test(x)
}


function checkPhoneNumber(strPhone, blnMandatory) {
    if ((strPhone == "") && (blnMandatory == true))
        return false;

    if ((strPhone == "") && (blnMandatory == false))
        return true;

    //^([+]39)?((38[{8,9}|0])|(34[{7-9}|0])|(36[6|8|0])|(33[{3-9}|0])|(32[{8,9}]))([\d]{7})$/;
    var filter = /^([+])?([\d]{7,50})$/; ;
    if (filter.test(strPhone)) {
        return true;
    }
    else
        return false;
}

function checkNumber(strNumber, blnMandatory) {
    if ((strNumber == "") && (blnMandatory == true))
        return false;

    if (!isNaN(strNumber))
        return true;
    else
        return false;
}


function displayErrorMsgLogin(strErrore) {

    if (document.getElementById("alert01") != null) {
        document.getElementById("alert01").innerHTML = '<p><strong>Attenzione!</strong><br>' + strErrore + '</p><p class="bt01"><a href="#" onClick="chiudi(this);return false;" title="Chiudi">Chiudi</a></p>';
        document.getElementById("alert01").style.display = "block";
    }
}

function chiudi() {
    if (document.getElementById("alert01") != null) {
        //setCookie("AHTV_CLOSEPENDINGDATA", "true", null) 
        document.getElementById("alert01").style.display = "none";
    }
}

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(NameOfCookie, value, expiredays) {
    var ExpireDate = new Date();
    ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
    document.cookie = NameOfCookie + "=" + escape(value) + ";path=/" + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}

function delCookie(NameOfCookie) {
    if (getCookie(NameOfCookie)) {
        var ExpireDate = new Date();
        setCookie(NameOfCookie, '', ExpireDate - 1);
        //document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function displayEmail(valueEmail) {
    if (valueEmail.length > 20)
        return valueEmail.substring(0, 20) + "...";
    else
        return valueEmail;
}


function displayErrorMsg(strErrore, strIDElement) {

    if (document.getElementById("ErrorDisplayMsg") != null) {
        var arrPositon = findPos(document.getElementById(strIDElement));
        var offTop = -50;

        var offsetLeft = 250;
        if ((arrPositon[0] - offsetLeft) < 100)
            offsetLeft = 20;

        document.getElementById("ErrorDisplayMsg").style.top = arrPositon[1] + offTop + "px";
        document.getElementById("ErrorDisplayMsg").style.left = arrPositon[0] - offsetLeft + "px";

        document.getElementById("ErrorDisplayMsg").innerHTML = "<p class='bt01' style='left:280px'><a title='Chiudi' onclick='document.getElementById(\"ErrorDisplayMsg\").style.display = \"none\";return false;' href='#'>&nbsp;&nbsp;&nbsp;</a></p><CENTER>" + strErrore + "<CENTER>";
        document.getElementById("ErrorDisplayMsg").style.display = "block";
    }
    else {
        var externalDiv = document.createElement("div");
        externalDiv.id = "ErrorDisplayMsg";
        externalDiv.style.border = "solid 1px gray";
        externalDiv.style.width = "300px";
        //externalDiv.style.height="130px";
        externalDiv.style.position = "absolute";
        var arrPositon = "";
        var offTop = -50;

        arrPositon = findPos(document.getElementById(strIDElement));

        var offsetLeft = 250;
        if ((arrPositon[0] - offsetLeft) < 100)
            offsetLeft = 20;

        externalDiv.style.top = arrPositon[1] + offTop + "px";
        externalDiv.style.left = arrPositon[0] - offsetLeft + "px";
        externalDiv.style.background = "#ffffff";
        externalDiv.style.zIndex = "2000";

        externalDiv.innerHTML = "<p class='bt01' style='left:280px'><a title='Chiudi' onclick='document.getElementById(\"ErrorDisplayMsg\").style.display = \"none\";return false;' href='#'>&nbsp;&nbsp;&nbsp;</a></p><CENTER>" + strErrore + "<CENTER>";
        document.getElementById("main").appendChild(externalDiv);
    }
}

function getParameterTop(param) { var val = ""; var qs = top.document.location.search; var start = qs.indexOf(param); if (start != -1) { start += param.length + 1; var end = qs.indexOf("&", start); if (end == -1) { end = qs.length } val = qs.substring(start, end); } return val; }

function decode(str) {
    return unescape(str.replace(/\+/g, " "));
}


/*************************************/
// autenticazione js
/*************************************/
//var finalUrlOk = 'http://tv.telecomitalia.alice.it/ahtv/sunrise/authorize';
var finalUrlOk = 'http://alicehometv.alice.it/ahtv/sunrise/authorize';

var finalUrlKo = 'http://tv.telecomitalia.it/login/login.html?pgt=2';

var remember = false;
var authLock = 0;

function login(username, password) {
    if (!isAuthLocked()) {
        lockAuth();
        hideFrame();
        loginAHTV(username, password, finalUrlOk, finalUrlKo, remember)
    }
}

var logout_win = null;
var logout_timeout = null;

function logout() {
    unLockAuth();
	//goLogout(getUrlLogout());

	logout_win = window.open("/auth/logout.html", "winLogout", "width=100,height=100");	
		
	window.focus();

	logout_timeout = setTimeout("logout_cb()", 500);
}

function logout_cb() {
	logout_win.close();
	logout_timeout = null;

	top.document.location.href = getUrlLogout();
}

function getUrlLogout() {
    var currentUrl = top.document.location.href;
    var hpUrl = 'http://tv.telecomitalia.it';

    var destinationUrl = ((currentUrl.indexOf("/ahtv/MyHTV/") != -1) ? hpUrl : currentUrl);

    return destinationUrl;
}


function isAuthLocked() {
    return authLock == 1;
}
function lockAuth() {
    authLock = 1;
}
function unLockAuth() {
    authLock = 0;
}

function showFrame() {
    resizeFrame(80);
}

function hideFrame() {
    resizeFrame(0);
}

function resizeFrame(n) {
    try {
        parent.document.getElementById('iLogin').height = n;
    } catch (e)
{ }
}
