$(document).ready(function(){
    $("#login_form").validate({
        submitHandler: function() { 
            login();
        },
        rules: {     
            emailLogin:{          
                required: true,
                email:true    
            },
            passwordLogin:{
                required: true
            }
        },
        messages: {
            emailLogin: {
                required: function () {
                    $('#login_message').html(('insert_mail'))
                    }, 
                email: function () {
                    $('#login_message').html(__('invalid_mail'))
                    }
            },
            passwordLogin: {
                required: function () {
                    $('#login_message').html('password richiesta')
                    }
            }
        }
    });
});

var ig = {
    ajax : function (value) {
        if( value.showLoader == null || value.showLoader == true) {
            htmlLoadingDiv = '<div id="loaderWrapper" style="position:fixed;top:0px;left:0px;z-index:5000;width:100%">\
            <div id="loader" style="margin:auto;color:white;padding:2px;font-weight:900;font-size:12px;width:132px;padding-left:22px;background:#F10A74 url(\'/img/images/ajax-loader.gif\') no-repeat 1px 1px">\
            Caricamento in corso...\
            </div>\
            </div>';
            $("body").append( htmlLoadingDiv );
            value.complete = function (){
                $("#loaderWrapper").remove();
            }
        }
        $.ajax(value);
    }
}
 
function showRegistrationForm(region){
    _gaq.push(['ciaopeople._trackEvent', 'registrationPopup', 'view']); 
    var body = '';
    body += '<div class="igFaceboxTitle">';
    body += '<h1 style="padding:3px;color:#ffffff">'+    __('Resta in contatto con Incontra Gente')+'</h1>';
    body += '</div><div id="forcedRegistrationHook" class="clearfix"></div><div id="forcedRegistrationLoading" class="clearfix"></div>';
    $.extend($.facebox.settings, {
        opacity : 0.85
    });
    $(document).bind('loading.facebox', function() { 
        $("#facebox_overlay").unbind("click").click(function() 
        { }) 
    })  
    $.facebox(body);
    //      $.facebox("ie vera merda<br>ie vera merda<br>ie vera merda<br>");       
    
    forcedRegistrationSelectStates(29,region);
    $('#forcedRegistrationHook').html( $('#forcedRegistrationHtmlContainer').html() );
    $('#forcedRegistrationHtmlContainer').html( 'container cleaned' );    
}

function forcedRegistrationSubmitHandler() {
    //validate
    _gaq.push(['ciaopeople._trackEvent', 'registrationPopup', 'submitClick']);
    $("#forcedRegistrationCountry").css('border','');
    $("#forcedRegistrationErrorLabel").html('');
    if( $("#forcedRegistrationCountry").val() == '' ){
        $("#forcedRegistrationErrorLabel").html('<br>&nbsp;&nbsp;&nbsp;<b><font color="red">' + __('Inserisci la tua nazione per proseguire') + '</font></b><br>');
        $("#forcedRegistrationCountry").css('border','1px solid #f00');
    } else if( $("#forcedRegistrationState").val() == '' ){
        $("#forcedRegistrationErrorLabel").html('<br>&nbsp;&nbsp;&nbsp;<b><font color="red">' + __('Inserisci la tua regione per proseguire') + '</font></b><br>');
        $("#forcedRegistrationState").css('border','1px solid #f00');
    } else {
        _gaq.push(['ciaopeople._trackEvent', 'registrationPopup', 'submitValid']);
        mailPermissionHandler();   
    }   
}
    
function forcedRegistrationHideFields(){
    $("#forcedRegistrationSelectContainer").css( {
        display:'none'
    } );
}    
 
function forcedRegistrationSaveLocation(){ 
    ig.ajax({
        type: "POST",
        url: "/profile/index/savelocation/format/json?" + fbSig,
        dataType: "json",                   
        data: ({
            country : $('#forcedRegistrationCountry').val(),
            state : $('#forcedRegistrationState').val(),
            city : $('#forcedRegistrationCity').val()
        }),            
        success: function( data ){
            if( data.error ) {
            }else
            {        
                //document.location.reload();
                igInviter.init();
            }
        },
        error:  function (err){  
            faceError(__('error'),__('Error') );
        }
    });    
}

function checkInvitaMsn(){
    if(getCookie("invitaMsnPostRegistration")==1){
        window.setTimeout('igInviter.init()',500);         
    }               
}
            
function getCookie(sNome) {
    var asCookies = document.cookie.split("; ");
    for (var iCnt = 0; iCnt < asCookies.length; iCnt++){
        var asCookie = asCookies[iCnt].split("=");
        if (sNome == asCookie[0])
            return (unescape(asCookie[1]));
        return null;
    }
}

   
function autoPublishStream( ) {
    //     FB.Connect.showPermissionDialog('publish_stream, offline_access');
    if( isDefined( facebookUserid ) ) {
        if( facebookUserid != 668422391) {
            FB.Facebook.apiClient.fql_query("SELECT publish_stream FROM permissions WHERE uid="+facebookUserid, function(rows) {
                if( rows[0]['publish_stream'] != 0 ){
                    link = 'https://apps.facebook.com/incontra_gente/?from=apstream';
                    var attachment = {
                        'caption' : '',
                        'name' : 'Sto conoscendo nuove persone su Incontra Gente',
                        'description' : '' ,
                        'href' : link,
                        'media':
                        [{
                            'type':'image',
                            'src' : 'http://igcdn.s3.amazonaws.com/img/logo/app_1_68931197560_4530.gif',
                            'href' : link
                        }],
                        'properties' :
                        {
                            'hack':{
                                'text' : 'unknown',
                                'href' : link
                            },
                            'mac':{
                                'text' : 'mol',
                                'href' : link
                            }
                        }
                    }
                    FB.Connect.streamPublish('', attachment , null , null , null , null , true );
                }
            });
        }
    }
}
                

function forcedRegistrationSelectStates(country,region) {
    if(country != ""){
        $("#forcedRegistrationStateSelected").css( {
            visibility : 'visible'
        } );
        $("#forcedRegistrationStateLabel").css( {
            visibility : 'visible'
        } );
   
        ig.ajax({
            type: "POST",
            url: "/profile/index/getstatesbycountryforcedregistration/c/" + country + "/r/"+region+"/format/json?" + fbSig,
            dataType: "json",                               
            success: function( data ){
                $('#forcedRegistrationStateSelected').html(data.selectStates); 
                $('#forcedRegistrationCitySelected').html("<select class=\"input_select\" name=\"city\" id=\"forcedRegistrationCity\" ><option value=\"\">" + __('Tutte le citta') + "</option></select>");      
            },
            error: function () {
                faceError(__('Errore'),__('Errore visualizzazione regioni'));
            }
        });
    }
}

function forcedRegistrationSelectCities(region) {
    $("#forcedRegistrationCitySelected").css( {
        visibility : 'visible'
    } );
    $("#forcedRegistrationCityLabel").css( {
        visibility : 'visible'
    } );
    ig.ajax({
        type: "POST",
        url: "/profile/index/getcitiesbyregionforcedregistration/r/" + region + "/format/json?",
        dataType: "json", 
        success: function( data ){
            $('#forcedRegistrationCitySelected').html(data.selectCities );       
        },
        error: function () {
            faceError('Errore visualizzazione città','Errore');
        }
    });
}      

function wrapperGAETracker(category, action, opt_label, opt_value){
    //    _gaq.push(['nealab._trackEvent', category, action]);
    _gaq.push(['main._trackEvent', category, action]);
    _gaq.push(['nealab._trackEvent', category, action]);
    _gaq.push(['ciaopeople._trackEvent', category, action]);
//m3Tracker._trackEvent(category, action, opt_label, opt_value);
}

/*<font color="RED">* Sei stato selezionato tra gli utenti di Incontra Gente per poter provare in anteprima il servizio "ricevi visite". Se dovessero verificarsi problemi ti invitiamo a contattarci privatamente all\'indirizzo incontragente@nealab.it</font>*/


function showBuyPvisitsWindowV3(){ 
    wrapperGAETracker( 'pvisitsbuy', 'viewWindow3' );
    var body = '';
    /* body += '<div class="igFaceboxTitle" style="width:736px">';
    body += '   <h1 style="padding:3px;color:#ffffff">';
    body +=         'Ricevi nuove visite al tuo profilo';
    body += '   </h1>';
    body += '</div>';
    */
    body += '<div id="showBuyPvisitsWindowV3DoReturnValue">\
                <div class="clearfix">\
                    <div style="valign:middle;float:right;margin-right:5px;margin-bottom:6px;cursor:pointer;font-size:10px;color:#666666" onclick="showBuyPvisitsWindowV2Close()">No, grazie &nbsp;<img src="http://www2.freebar.com/fbdir/immagini/errorClose.png"/></div>\
                </div>\
                <div class="clearfix"><img src="/img/other/popupV2.png"/><br><br><br> * Sei stato selezionato per una prova gratuita! <input type="button" value="Voglio guadagnare gratuitamente 10 visite" onclick="showBuyPvisitsWindowV3Do()" class="inputsubmit"></div></div>';
    body += '</div>';

    $.extend($.facebox.settings, {
        opacity : 0.85
    });
    $(document).bind('loading.facebox', function() { 
        $("#facebox_overlay").unbind("click").click(function() 
        { }) 
    })
        
    $.facebox(body);

    $(".leftcol").css( {
        height : '3000px'
    })
    
    $(".facebox_hide").css( {
        zIndex : '1'
    })
}

function showBuyPvisitsWindowV3Do() {
    ig.ajax({
        type: "GET",
        url: "/credits/channel/pvisitstest/format/json?" + fbSig,
        dataType: "json",                               
        success: function( data ){
            if( data.value == 1 ) {
                $("#showBuyPvisitsWindowV3DoReturnValue").html('<h2>Pronto a ricevere 10 nuove visite?</h2> <br>La tua prova è stata attivata, a breve il tuo profilo sarà proposto a tante nuove persone ed entro 24 ore riceverei almeno 10 nuove visite! <br><br><a href="javascript:$.facebox.close()">Chiudi</a><br><br>'); 
            }
            if( data.value == 2 ) {
                $("#showBuyPvisitsWindowV3DoReturnValue").html('<h2>Ti ringraziamo per il tuo interesse</h2> <br>Al momento possiamo offrire solo una prova per utente. <br><br><a href="javascript:$.facebox.close()">Chiudi</a><br><br>');
            }
        },
        error:  function (err){  
            faceError(__('error'),__('Error') );
        }
    });  
}

function buyPvisitsWindowV2ShowSupersonic(){                           
    $("#buyPvisitsWindowV2Iframe").attr( {
        'src' : 'http://www.supersonicads.com/delivery/panel.php?siteUserId=' + fbGlobalUserid  + '&siteId=4538'
        } )
}

function buyPvisitsWindowV2ShowSponsorpay(){                           
    $("#buyPvisitsWindowV2Iframe").attr( {
        'src' : 'http://iframe.sponsorpay.com/?appid=263&uid=' + facebookUserid
        } )
}

function showBuyPvisitsWindowV2(){ 
    //body = '<h2>Ti ringraziamo per il tuo interesse</h2> <br>Il servizio non è al momento disponibile ma tornerà attivo entro pochi giorni. <br><br><a href="javascript:$.facebox.close()">Chiudi</a><br><br>';
    if( facebookLog == 0 ){
        
        wrapperGAETracker( 'pvisitsbuy', 'blockedByStandalone' );
        body = 'Devi essere collegato tramite facebook per poter effettuare questa operazione';
        $.facebox(body);
    }
    else {

        wrapperGAETracker( 'pvisitsbuy', 'viewWindow2' );
        var body = '';

        body += '<div class="clearfix">\
                <div class="clearfix">\
                    <div style="valign:middle;float:right;margin-right:5px;margin-bottom:6px;cursor:pointer;font-size:10px;color:#666666" onclick="showBuyPvisitsWindowV2Close()">No, grazie &nbsp;<img src="http://www2.freebar.com/fbdir/immagini/errorClose.png"/></a></div>\
                <\div>\
                <div class="clearfix">\
                        <img align="right" src="/img/other/popupV2.png"/>\
                </div>\
                <div style="height:30px"><br><center>\
                    <u style="color:pink"><a href="javascript:buyPvisitsWindowV2ShowSupersonic()"> Offerte tramite SuperSonic</a></u> - \
                    <u style="color:pink"><a href="javascript:buyPvisitsWindowV2ShowSponsorpay()">Offerte tramite SponsorPay</a></u></center>\
                    </td></tr></table>\
                </div>\
                <br>\
                <iframe id="buyPvisitsWindowV2Iframe" src="about:blank" width="728" height="2200" frameborder="no"></iframe>\
            </div>';
        //<iframe src="http://www.supersonicads.com/delivery/panel.php?siteUserId=' + fbGlobalUserid  + '&siteId=4538" width="728" height="2200" frameborder="no"></iframe>

        $.extend($.facebox.settings, {
            opacity : 0.85
        });
        $(document).bind('loading.facebox', function() { 
            $("#facebox_overlay").unbind("click").click(function() 
            { }) 
        })
        
        $.facebox(body);

        $(".facebox_hide").css( {
            zIndex : '1'
        })
        $(".leftcol").css( {
            height : '3000px'
        })
        buyPvisitsWindowV2ShowSupersonic()
    }
}

function showBuyPvisitsWindowV2Close(){
    $.facebox.close();
    wrapperGAETracker( 'pvisitsbuy','noThanksV2' );
}

function PSMMclose(){
    $.facebox.close();
    wrapperGAETracker( 'psmm','close' );
}

function showBuyPvisitsWindowV1(){ 
    wrapperGAETracker( 'pvisitsbuy', 'viewWindow1' );
    var body = '';
    body += '<div class="igFaceboxTitle" style="width:736px">';
    body += '   <h1 style="padding:3px;color:#ffffff">';
    body +=         'Ricevi nuove visite al tuo profilo';
    body += '   </h1>';
    body += '</div>';
    
    body += '<div class="clearfix igFaceboxContent"><div id="buyPvisitsDescription"> Completando una delle nostre offerte il tuo profilo verrà proposto a diversi utenti di Incontra Gente che vivono nella tua zona e che hanno caratteristiche che possono interessarti. <br><br> Se ad esempio completi una offerta da 5 visite il tuo profilo verrà proposto a diverse persone della tua città e con età e interessi secondo le tue richieste fin quando almeno 5 persone non avranno visitato il tuo profilo. <br><br><br> <input type="button" class="inputsubmit" value="Voglio ottenere nuove visite" onclick="showBuyPvisitsIframe()"> - <a href="javascript:$.facebox.close();wrapperGAETracker( \'pvisitsbuy\',\'noThanksV1\' );">No grazie, non sono interessato alla novità</a></div><div id="buyPvisitsIframe" style="display:none"><iframe src="http://www.supersonicads.com/delivery/panel.php?siteUserId=' + fbGlobalUserid  + '&siteId=4538" width="728" height="2200" frameborder="no></iframe></div>"';
    body += '</div>';
    
    $.extend($.facebox.settings, {
        opacity : 0.85
    });
    $(document).bind('loading.facebox', function() { 
        $("#facebox_overlay").unbind("click").click(function() 
        { }) 
    })
    
    $.facebox(body); 
    
    $(".leftcol").css( {
        height : '3000px'
    })
    $(".facebox_hide").css( {
        zIndex : '1'
    })
}

function showBuyPvisitsIframe(){
    wrapperGAETracker( 'pvisitsbuy','secondStepV1' );
    $("#buyPvisitsIframe").css( {
        display:''
    } );
//    $("#buyPvisitsDescription").css( {display:'none'} );
}

function extendedPermissionDialog() {
    FB.Facebook.apiClient.fql_query("SELECT email FROM permissions WHERE uid=" + facebookUserid, function(rows) {
        if( rows[0]['email'] == 0 ){
            FB.Connect.showPermissionDialog("email", function(perms) {
                if(perms){
                    saveMailAddress();
                }
            });
        }
    });
}
/* end extended permission dialog */

function getVoteDetails()                          
{       
    //    console.log("Console...");
    ig.ajax({
        type: "GET",
        url: "/points/index/votesdetail/format/json?" + fbSig,
        dataType: "json",
        success: function(msg){
            $.facebox(msg.response);
        },
        error: function () {
            faceError(__('error_connection'), __('error'));
        }
    });                 
}

function sendMessage( recipientId, recipientName, extraHtml, citta, eta, sesso, igModule , socialnetwork, domain)
{   
    if( hasPSMM == 1 ) {
        _gaq.push(['ciaopeople._trackEvent', 'psmm', 'trytosend']);
        ig.ajax({
            type: "GET",
            url: "/messages/index/cansendmessage/format/json/?" + fbSig,
            dataType: "json",
            success: function(msg){           
                if( msg.response == 1)
                {
                    _gaq.push(['ciaopeople._trackEvent', 'psmm', 'cansend']);
                    var body = '';
                    body += '<div class="igFaceboxTitle" id="title">';
                    body += '<h1 style="padding:3px;color:white">';
                    body += __('send_message_row_1') + recipientName + '';
                    body += '</h1>';
                    body += '</div>';
                    body += '<div class="clearfix igFaceboxContent">';                                                            
                    body += __('send_message_row_2') + recipientName + __('send_message_row_3');
                    body += '<br>';
                    body += '<form id="formSendMessage" name="formSendMessage">';  
                    body += '<div>';
                    body += '<input type="hidden" id="sendMessageRecipient" value="' + recipientId + '">';
                    body += '<textarea id="sendMessageBody" name="messageBody" style="width:90%;height:100px;" rows="10"></textarea>';
                    body += '</div>';
                    body += '</form>';
                    body += '</div>';
                    body += '<div class="clearfix" id="advMessage" style="margin-top:8px;margin-left:3px;width:350px">\
                                        <iframe scrolling="no" height="60" frameborder="0" width="468" src="/gadm.php?citta=' + citta + 
                    '&eta=' + eta + '&sesso=' + sesso + '&igModule=' + igModule + '&socialnetwork=' + socialnetwork + '&domain=' + domain + '"             style="border: 0px none ;" marginheight="0" marginwidth="0" allowtransparency="true" hspace="0" vspace="0" name="advMessages"></iframe>\
                             </div>';
                    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="send" value="Invia messaggio" onclick="sendMessageDo()"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Chiudi" onclick="$.facebox.close()"></div></div>';
                    $.facebox(body);     
                }
                else
                {
                    _gaq.push(['ciaopeople._trackEvent', 'psmm', 'forbiddentosend']);
                    mustBuyPoints('message');
                }
            },
            error: function () {
                faceError(__('error'), __('error'));
                _gaq.push(['ciaopeople._trackEvent', 'psmm', 'errortosend']);
            }
        });                 
             
        
    } else {
        
        var body = '';
        body += '<div class="igFaceboxTitle" id="title">';
        body += '<h1 style="padding:3px;color:white">';
        body += __('send_message_row_1') + recipientName + '';
        body += '</h1>';
        body += '</div>';
        body += '<div class="clearfix igFaceboxContent">';                                                            
        body += __('send_message_row_2') + recipientName + __('send_message_row_3');
        body += '<br>';
        body += '<form id="formSendMessage" name="formSendMessage">';  
        body += '<div>';
        body += '<input type="hidden" id="sendMessageRecipient" value="' + recipientId + '">';
        body += '<textarea id="sendMessageBody" name="messageBody" style="width:90%;height:100px;" rows="10"></textarea>';
        body += '</div>';
        body += '</form>';
        body += '</div>';
        body += '<div class="clearfix" id="advMessage" style="margin-top:8px;margin-left:3px;width:350px">\
                            <iframe scrolling="no" height="60" frameborder="0" width="468" src="/gadm.php?citta=' + citta + 
        '&eta=' + eta + '&sesso=' + sesso + '&igModule=' + igModule + '&socialnetwork=' + socialnetwork + '&domain=' + domain + '"             style="border: 0px none ;" marginheight="0" marginwidth="0" allowtransparency="true" hspace="0" vspace="0" name="advMessages"></iframe>\
                 </div>';
        body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="send" value="Invia messaggio" onclick="sendMessageDo()"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Chiudi" onclick="$.facebox.close()"></div></div>';
        $.facebox(body);
        
    }
}

function pricingPopupClose(num){
    //gioco delle tre carte per salvarmi il contenuto del popup
    $("#"+num+"PopupPricing").html( $("#"+num+"PopupPricingContainer").html() );
    $("#"+num+"PopupPricingContainer").html( '' );
}

function getPricingPopup(type,num){
    var title = "";
    var message = "";
    if(type=="fbcontact"){
        title = "Ottieni subito il contatto facebook!";
        message = "Per ottenere i contatti Facebook di tutti gli utenti con cui scambi messaggi <br>scegli l'offerta più adatta a te!</br>";
    }else if(type=="message"){
        title = "La conversazione è bloccata.";
        message = "Per <b>sbloccare tutte le tue conversazioni</b> scegli l'offerta più adatta a te!</br>";
    }else{
        title = "Il servizio è bloccato."
        message = "<b>Sblocca il servizio!</b> Scegli l'offerta più adatta a te!</br>";
    }
    return '<div class="clearfix">\
                <div class="igFaceboxTitle" id="title"><h1 style="padding:3px;color:white">'+title+'</h1></div>\
                <div onclick="$(\'#facebox_overlay\').remove();pricingPopupClose(\''+num+'\');PSMMclose();" style="cursor:pointer;float:right;text-decoration:none;margin-right:5px;margin-top:5px;">\
                    <img src="http://www2.freebar.com/fbdir/immagini/errorClose.png">\
                </div>\
                <div class="clearfix" style="margin-bottom:25px;margin-top:15px;">'+message+'</div>\
                <div id="'+num+'PopupPricingContainer" style="width:500px;">' + $("#"+num+"PopupPricing").html() + '</div>\
            </div>';
}

function showPricingPopup(num){
    // nuovo sistema di abbonamento
    // se socialgoldhidden è vuoto significa che è ancora attivo il popup
    if( $("#"+num+"PopupPricing").html( ) == '' ) {
        $("#"+num+"PopupPricing").html( $("#"+num+"PopupPricingContainer").html( ) );
    }
    if(pricingType=="fbcontact"){
        $("#oneshotOption").css('display','none');
        $("#onebipOption").css('display','none');
    }else{
        $("#oneshotOption").css('display','block');
        $("#onebipOption").css('display','block');
    }

    body = getPricingPopup(pricingType,num);
    $("#"+num+"PopupPricing").html( '' );
    $.extend($.facebox.settings, {
        opacity : 0.85
    });
    $(document).bind('loading.facebox', function() {
        $("#facebox_overlay").unbind("click").click(function()
        {})
    })

    $.facebox(body);
    $(".facebox_hide").css( {
        zIndex : '1'
    })
    $(".leftcol").css( {
        height : '3000px'
    })
}

function mustBuyPoints(type) {
    pricingType = type;
    wrapperGAETracker( 'abbonamento', type );
    // psss
    if( facebookUserid != 'null'){
        if(type=="message" && igAge < 25)
            supersonicadsPopup();
        else
            showPricingPopup('first');
    }else
        supersonicadsPopup();
}

function supersonicadsPopup(){
    //vecchio sistema di pagamenti
    if( facebookLog == 1 ){
        siteId = '112';
    } else {
        siteId = '4668';
    }
    body = '<div class="clearfix">\
                <div class="igFaceboxTitle" style="width:auto;" id="title"><h1 style="padding:3px;color:white">La conversazione è bloccata!</h1></div>\
                <div onclick="$(\'#facebox_overlay\').remove();PSMMclose();" style="cursor:pointer;float:right;text-decoration:none;margin-right:5px;margin-top:5px;">Non voglio leggere e inviare messaggi &nbsp;<img src="http://www2.freebar.com/fbdir/immagini/errorClose.png"></div>\n\
                <br><div class="clearfix" style="margin-bottom:10px;margin-top:10px;"></br></br></br>Effettua una delle offerte di seguito riportate per <b>sbloccare tutte le tue conversazioni!</b><br> <i>1 moneta per ogni messaggio letto</i></div><div class="clearfix"></br></br></div>\
                <iframe id="buyPvisitsWindowV2Iframe" src="http://www.supersonicads.com/delivery/panel.php?siteUserId=' + fbGlobalUserid  + '&siteId=' + siteId + '" width="728" height="2200" frameborder="no"></iframe>\
            </div>';
    $.extend($.facebox.settings, {
        opacity : 0.85
    });
    $(document).bind('loading.facebox', function() {
        $("#facebox_overlay").unbind("click").click(function()
        { })
    })

    $.facebox(body);

    $(".facebox_hide").css( {
        zIndex : '1'
    })
    $(".leftcol").css( {
        height : '3000px'
    })
}

function sendMessageDo()                          
{
    if( $("#sendMessageRecipient").val() == '' ) {
        faceError(__('error'), __('error'));
    }
    if( $("#sendMessageBody").val() == '' ) {
        faceError(__('send_message_do_row_1'), __('send_message_do_row_2'));
    }
    ig.ajax({
        type: "GET",
        url: "/messages/index/send/format/json/?" + fbSig,
        dataType: "json",
        data: ({
            recipient : $("#sendMessageRecipient").val(), 
            messageBody : $("#sendMessageBody").val()
            }),
        success: function(msg){           
            if( msg.response == 1)
            {
                newFaceNotice('Messaggio inviato');
            //faceNotice('Il messaggio è stato inviato correttamente.', 'Messaggio inviato');     
            }
            else
            {
                faceError(__('send_message_do_row_3'), __('error'));
            }
        },
        error: function () {
            faceError(__('send_message_do_row_3'), __('error'));
        }
    });                 
}

function deleteMessage( messageId )
{
    ig.ajax({
        type: "GET",
        url: "/messages/index/deletem/format/json/?" + fbSig,
        data: ({
            messageid : messageId
        }),
        success: function(msg){ 
            $("#messageBox" + messageId).toggle();         
        /*      
           $("#messageBox" + messageId).css('display', 'none');  
           $("#messageBox" + messageId+ "_deleted" ).css('display', 'block');  
       }                                                       
        $("#messageBox" + messageId).animate({
            height : '0px',
            display : 'none',
            opacity : 0
        }, 1000);    */             
        }
    });
    return false;
}


function PSMMreadMessage( messageId )
{      
    _gaq.push(['ciaopeople._trackEvent', 'psmm', 'trytoreadmessage']);
    ig.ajax({
        type: "GET",
        dataType: 'json',
        url: "/messages/index/read/format/json/?" + fbSig,
        data: ({
            messageid : messageId
        }),
        success: function(msg){  
            if( msg.response == 2 )
            {
                _gaq.push(['ciaopeople._trackEvent', 'psmm', 'forbiddentoreadmessage']);
                mustBuyPoints('message');
                return false;     
            }      
            else if( msg.response == 0 )
            {
                _gaq.push(['ciaopeople._trackEvent', 'psmm', 'errortoread']);
                faceError(__('read_message_row_1'), __('error'));
                return false;     
            } else {
                _gaq.push(['ciaopeople._trackEvent', 'psmm', 'canreadmessage']);
                $.facebox( $("#message" + messageId ).html());
                return false;
            }
        }
    });
}          

function readMessage( messageId )
{       
    ig.ajax({
        type: "GET",
        dataType: 'json',
        url: "/messages/index/read/format/json/?" + fbSig,
        data: ({
            messageid : messageId
        }),
        success: function(msg){           
            if( msg.response == 0 )
            {
                console.log(msg.err);
                faceError(__('read_message_row_1'), __('error'));
                return false;     
            }
        }
    });
}          


function hideActiveContent()
{
    if( $(".activeContent").length > 0) {
        $(".activeContent").css("visibility","hidden");
    }   
}

function showActiveContent()
{
    if( $(".activeContent").length > 0) {
        $(".activeContent").css("visibility","visible");
    }
}

function publishFeed( inviteParams )
{    
    /*   FB.Connect.showFeedDialog(72473142560, null, null, 'prova', null, FB.RequireConnect.require, publishFeedDone, 'Pubblica la tua attivita\'', 'e\' online su Incontra genta e sta conoscendo nuove persone');*/
    /*
 templateData = {"images":[{"src": "http://dev.www.incontragente.com/img/logo/provaa.jpg","href":"http://apps.facebook.com/incontra_gente/profile/index/index/u/" + fbGlobalUserid + '/?='}]};
 FB.Connect.showFeedDialog(87699577560, templateData, null, '', null, FB.RequireConnect.require, publishFeedDone, 'Promuovi il tuo profilo');
 */
    var curdate = new Date()
    var mday = curdate.getDate()
    var url = 'http://apps.facebook.com/incontra_gente/people/?' + inviteParams;
    var profileUrl = 'http://apps.facebook.com/incontra_gente/profile/index/index/u/' + facebookUserid + '?' + inviteParams;
    var attachment = {
        'name': facebookName + ' sta conoscendo nuove persone su Incontra Gente',
        'href': url,
        'properties': {
            'Incontra': {
                'text': 'Incontra nuova gente su Facebook', 
                'href': url
            },
            'Visita': {
                'text': 'Visita il profilo di ' + facebookName + ' su Incontra Gente', 
                'href': profileUrl
            }
        },
        'media': [{
            'type': 'image', 
            'src': 'http://www.incontragente.com/img/logo/promotion.jpg', 
            'href': url
        }]
    }; 
    // var actionLinks = [{ "text": "Watch Video", "href": "http://www.myvideosite/videopage.html"}];
    FB.Connect.streamPublish('', attachment, null, null, 'Promuovi il tuo profilo', publishFeedDone);
 
}    

 

function publishFeedDone( data )
{
    /*    console.log();
    console.log( data );*/
    ig.ajax({
        type: "GET",
        url: "/credits/channel/statusadded?" + fbSig,
        success: function(msg){           
            faceNotice( __('publish_feed_done_row_1'), __('publish_feed_done_row_2'));
        }
    });
    
}

function faceNotice( message, title ){
    var body = '';
    body += '<div class="igFaceboxTitle">';
    body += '<h1 style="padding:3px;color:#ffffff">';
    body += title;
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';                                                            
    body += message;
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Ok" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);        
}

function inviteFbFriends() 
{
    FB.getLoginStatus(function(response) {
        if (response.session) {
            FB.ui({
                method: 'apprequests', 
                message: 'Dovresti vedere quanta bella gente ho trovato su questo sito :D.', 
                data: ''
            });
        } 
    });
}

function newFaceNotice( title ){
    var body = '';
    body += '<div class="igFaceboxTitle">';
    body += '<h1 style="padding:3px;color:#ffffff">';
    body += title;
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';                                                            
    body += "Vuoi controllare se quest'utente ti risponde?<br><br>";
    body += '&nbsp;&nbsp;&nbsp;- Entra periodicamente in IncontraGente<br>';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Ok" onclick="$.facebox.close()"></div></div>';
    $.facebox(body); 
}

function informaWwwAccount( email , password ){
    var body = '';
    body += '<div class="igFaceboxTitle" style="width:550px;">';
    body += '<h1 style="padding:3px;color:#ffffff">';
    body += 'Avviso importante';
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';                                                            
    body += 'Da oggi puoi accedere ad Incontra Gente direttamente andando su <b>www.incontragente.com</b>.<br><br>';
    body += 'Ti abbiamo inviato una email al tuo indirizzo <b>'+email+'</b> contenente i tuoi dati di accesso.<br><br>';
    body += 'Eccoli riepilogati:<br><br>';
    body += ' -  <b>'+email+'</b><br> -  <b>'+password+'</b>';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Ok" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);        
}
                                 
function addBookmark() {
    var body = '';
    body += '<div class="igFaceboxTitle">';
    body += '<h1 style="padding:3px;color:#ffffff">';
    body += 'Aggiungi IncontraGente ai tuoi segnalibri';
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';                                                            
    body += 'Per non perdere nessuno dei tuoi contatti <br><br><a href="javascript:addBookMarkDo()">Aggiungi IncontraGente ai segnalibri</a>';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Ok" onclick="addBookMarkDo()"></div></div>';
    $.facebox(body);    
}
/*
function addBookMarkDo(){
    try {           
        FB.Connect.showBookmarkDialog();
    }
    catch( e ){}
    $.facebox.close();
}
*/

function addBookmarkDo(){                                                            
    try {      
        $(".facebox_hide").css( {
            zIndex : '1'
        })                                                      
        FB.Connect.showBookmarkDialog(/*addBookMarkCallback*/);
    }
    catch( e ){
        alert("error");
    }
} 

function addBookMarkCallback() {
    
}


function faceError( message, title)
{
    var body = '';
    body += '<div class="igFaceErrorTitle" id="title">';
    body += '<h1 style="padding:3px;color:black">';
    body += title;
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceErrorContent">';                                                            
    body += message;
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit  igFaceboxButton" name="Cancel" value="Ok" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);
}

function registerToApp(urlToRegister){
    
    var body = '';
    body += '<div class="igFaceboxTitle" id="title">';
    body += '<h1 style="padding:3px;color:white">';
    body += __('register_to_app_row_1');
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';                                                            
    body += __('register_to_app_row_2');
    body += '<br>';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button igFaceboxButton" class="inputsubmit" name="send" value="Vai al profilo" onclick="document.location.href=\''+urlToRegister+'\'"><input type="button" class="inputsubmit" name="Cancel" value="Annulla" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);
    
}

function uploadProfilePic(){
    var body = '';
    body += '<div class="igFaceboxTitle">';
    body += '<h1 style="padding:3px;color:#ffffff">';
    body += __('upload_profile_pic_row_1');
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';                                                            
    body += '<b>' + __('upload_profile_pic_row_2') + '</b>';
    body += '<form enctype="multipart/form-data"'; 
    body += 'action="/profile/index/uploadphoto?'+fbSig+'" method="post" target="uploadIframe">';
    body +=  '    <input name="file" id="file" type="file" ></input><br><br>';
    body +=  '    <input type="submit" value="upload"></input>';
    body += '</form>';
    body += '<iframe frameborder="no" src="about:blank" id="uploadIframe" name="uploadIframe" style="width: 1px; height: 1px;"></iframe>';
    body += "<br>Se l'upload dovesse impegare troppo potrebbero esserci problemi di rete. Prova a ricaricare la pagina e ricaricare la foto.";
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Annulla" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);
}

function photoUploaded(data){
    //var body = '';
    //body += '<h1>' + __('photo_uploaded_row_1')+ '</h1>';
    //body += '<div class="clearfix" style="margin-top:10px;">'
    //body += '<div style="float:right"><input type="button" class="inputsubmit" name="Cancel" value="Ok" onclick="$.facebox.close()"></div></div>';
    //$.facebox(body);
    if( $('#userPhotoProfile').attr("src") == data)
        //faceError("Si è verificato un errore di rete durante il processo di caricamento. Prova a ricaricare la foto. Se il problema persiste verifica che il file che stai caricando sia una immagine di tipo JPG, GIF o PNG ed eventualmente prova a caricare un'altra foto.",'Errore');
        faceNotice('La tua foto è stata caricata correttamente, potrebbe essere disponibile tra qualche minuto.', 'Carica la tua foto');
    else{
        $('#userPhotoProfile').attr("src", data);
        faceNotice('La tua foto è stata caricata correttamente, potrebbe essere disponibile tra qualche minuto.', 'Carica la tua foto');
    }   
    
}   

////////////////////////////////////////////////////////////////
//////////////////////////FUNZIONI WWW//////////////////////////
////////////////////////////////////////////////////////////////

function checkUserLogin(userId){ 
    ig.ajax({
        type: "POST",
        url: "/www/index/checkuserlogin/fbconnectuserid/"+userId+"/format/json?" + fbSig,
        dataType: "json",                   
        success: function( data ){
            document.location.href = "/";  
        },
        error:  function (err){  
            faceError(__('error'),__('Error') );
        }
    });    
}                                         


//function facebookLogout() {
//    FB.Connect.logout( 
//        function() { 
//            IGLogout(); 
//        }
//    );
//}

function facebookLogout(){
    //    console.log('aaaaaaaaa');
    ig.ajax({
        type: "POST",
        url: "/www/index/logout/format/json",
        dataType: "json",  
        success: function(msg){
            document.location.href = msg.url;  
        },
        error: function () {
            faceError(__('ig_logout_row_1'), __('error'));
        }
    });                     
}
                
function recoveryPasswordBox(){
    var body = '';
    body += '<div class="igFaceboxTitle" id="title">';
    body += '<h1 style="padding:3px;color:white">';
    body += __('recovery_password_box_row_1');                
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent" style="background-color:#fff;color:000;width:100%;height:100%;border-bottom:1px solid #ccc;margin-left:-10px;padding:10px;padding-right:0px;">';
    body += '<div style="float:left;margin-top:5px;margin-right:5px;">' + __('recovery_password_box_row_2')+'</div>';
    body += '<form id="formRecoveryPassword" name="formRecoveryPassword" onsubmit="return false;">';  
    body += '<div style="float:left;">';
    body += '<input type="hidden" id="recoveryPasswordRecipient"  action="">';
    body += '<input type="text" id="emailRecovery" name="emailRecovery" onkeydown="checkPasswordRecoveryEnterKey(event)">';
    body += '</div>';
    body += '</form>';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;padding-right:10px;"><div style="float:right">';
    body += '<input type="button" class="inputsubmit igFaceboxButton" name="recovery" value="Invia richiesta" onclick="sendRecoveryPasswordEmail(\'\')">';
    body += '<input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Cancella" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);
}

function recoveryPasswordBoxOnLoginError( email ){
    var body = '';
    body += '<div class="igFaceErrorTitle" id="title">';             
    body += '<h1 style="padding:3px;color:black">';
    body += 'Password errata';
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent" style="background-color:#fff;color:000;width:100%;height:100%;border-bottom:1px solid #ccc;margin-left:-10px;padding:10px;padding-right:0px;">';    
    body += '<div style="float:left;margin-top:5px;margin-right:5px;">' + 'La password che hai inserito &egrave; errata.<br><a href="#" onclick="sendRecoveryPasswordEmail(\''+email+'\')"><u>Recupera la password ricevendo un\'email all\'indirizzo: <b>' +email+'</b></u></a></div>';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;padding-right:10px;"><div style="float:right">';
    body += '<input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Cancella" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);
}

function sendRecoveryPasswordEmail( email ){
    if(email=='')
        email = $('#emailRecovery').val();
    if( email.length < 5 ){
        faceError(__('send_recovery_password_email_row_1'), __('error'));
        return false;
    }  
    ig.ajax({
        type: "POST",
        url: "/www/password/sendrecoverypasswordemail/format/json",
        dataType: "json",
        data: {
            email: email
        },
        success: function(msg){
            if(msg.response==1)
                faceNotice( __('send_recovery_password_email_row_2'), __('send_recovery_password_email_row_3'));
            else if( msg.response == 2 )
                faceError(__('L\'email che hai inserito è collegata ad un utente registrato tramite Facebook e non direttamente su www.incontragente.com.Se vuoi collegarti con un utente iscritto tramite Facebook clicca sul pulsante "Connect with Facebook". '), __('L\'email che hai inserito non è registrata ad Incontra Gente'));
            else {
                faceError(__('send_recovery_password_email_row_4'), __('error'));   
            }
        },
        error: function(){
            faceError(__('send_recovery_password_email_row_4'), __('error'));
        }
    });    
}

function changePasswordBox(){
    var body = '';
    body += '<div class="igFaceboxTitle" id="title">';
    body += '<h1 style="padding:3px;color:white">';
    body += __('change_password_box_row_1');
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';
    body += '<form id="formChangePassword" name="formChangePassword" action="">';  
    body += '<div style="float:left;">';
    body += '<input type="password" id="oldPasswordChange" name="oldPasswordChange"><span style="vertical-align:bottom">&nbsp;' + __('change_password_box_row_2')+'</span><br><br>';
    body += '<input type="password" id="newPasswordChange" name="newPasswordChange"><span style="vertical-align:bottom">&nbsp;' + __('change_password_box_row_3')+'</span><br>';
    body += '</div>';
    body += '</form>';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="recovery" value="Invia richiesta" onclick="changePassword()"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Cancella" onclick="$.facebox.close()"></div></div>';
    $.facebox(body);
}
   
function register(){      
    ig.ajax({
        type: "POST",
        url: "/www/index/register/format/json",
        dataType: "json",
        data: {
            name:             $('#name').val(),
            email:            $('#email').val(),
            password:         $('#password').val(),
            repeatPassword:   $('#repeat_password').val(),
            sex:              $('input[name=sex]:checked').val(),
            country:          $('#country').val(),
            state:            $('#state').val(),
            city:             $('#city').val(),
            controllerDate:   $('#controller_date').val()
        },
        success: function(){
            document.location.href="/"; 
        },
        error: function(){
            faceError(__('register_row_1'),__('error'));
        }
    });
}

// function to openinviter

function selectDeselectAll(){
    
    if($('.emailCheckList').attr('checked')){
        $('.emailCheckList').attr({
            checked:false
        });
        $('#anchor').html('Seleziona tutti'); 
    }
    else{
        $('.emailCheckList').attr({
            checked:true
        });
        $('#anchor').html('Deseleziona tutti');
    }
    return false;
}

function getCheckedValue(){
    var query_string = '';    
    form = document.getElementById('msnemail');
    for(i=0;i<form.email.length;i++){
        if (form.email[i].checked) 
            query_string += form.email[i].value + " ";         
    }
    return query_string.substring(0,(query_string.length - 1)); 
}

function changePassword(){
    length = $('#newPasswordChange').val().length;
    if(( length < 5 ) || ( length > 10 )){
        faceError(__('change_password_row_1'), __('error'));
        return false;
    }  
    ig.ajax({
        type: "POST",
        url: "/www/password/changepassword/format/json",
        dataType: "json",
        data: {
            oldPassword: $('#oldPasswordChange').val(),
            newPassword: $('#newPasswordChange').val()
            },
        success: function(msg){
            faceNotice( __('change_password_row_2'), __('send_recovery_password_email_row_3'));
        },
        error: function(){
            faceError(__('change_password_row_3'), __('error'));
        }
    });    
}

function checkKeyEnter(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if ( charCode == 13)
        return true;
    return false;

}

function checkMsnEnterKey(evt){
    if(checkKeyEnter(evt))
        igInviter.findFriends();
}   

function checkPasswordRecoveryEnterKey(evt){
    if(checkKeyEnter(evt))
        sendRecoveryPasswordEmail('');
}   


// callback tra function..

var igInviter = {
    callBack: null,
    init: function(callBack){
        igInviter.callBack = callBack;
        var body = '';
        body += '<div style="height:250px;">';
        body += '<div class="igFaceboxTitle" id="title">';
        body += '<h1 style="padding:3px;color:white">';
        body += __('ig_inviter_row_1');
        body += '</h1>';
        body += '</div>';
        body += '<div class="clearfix" style="height:15px">';
        //contenuto all'interno del facebox...
        body += '<div onclick="$.facebox.close();" style="cursor:pointer;float:right;text-decoration:none;margin-right:5px;">';
        body += '<img src="http://www.incontragente.com/img/other/errorClose.png"></img>';
        body += '</div>';
        body += '<div align="center" id="faceboxContent" style="margin-top:15px;">';
        body += '<p style="margin-left: 20px; margin-top: 10px; margin-bottom: 0px;" align="left"><font color="#336699" size="4"><b>';
        body += '<img src="http://www.incontragente.com/img/other/msnlogo_1.gif" alt=""/>&nbsp;&nbsp;'+__('ig_inviter_row_2')+'</b></font></p><br>';
        body += '<hr color="#336699" size="1" width="90%">';
        body += '</div>';
        body += '<div id="labelUser"></div>';
        body +='<div align="center" style="margin-top: 10px;">';
        body +='<table border=0 cellspacing=10>';
        body += '<tr><td>'+__('ig_inviter_row_3')+'<td><input name="msnLogin" id="msnLogin" size="20" type="text" onkeydown="checkMsnEnterKey(event)"></tr>';
        body += '<tr style="height:10px;"><td><td></tr>';
        body += '<tr><td>'+__('ig_inviter_row_4')+'&nbsp;&nbsp;&nbsp;<td><input class="bginput" id="msnPasswd" size="20" type="password" onkeydown="checkMsnEnterKey(event)"></tr></table>';
        body += '<br><br><font color="#336699">I tuoi dati non saranno salvati in alcun modo</font>';
        body += '<br><br><input type="button" onclick="igInviter.findFriends();" id="friendFinderSubmit" class="inputsubmit  igFaceboxButton" value="Trova">';
        body += '<div id="friendFinderLoading" style="display:none">Caricamento in corso...</div>';
        body +='</div>';
        //fine contenuto..
        body += '</div>';            
        $.facebox(body);
    },
    sendMailToFriends: function(){
        ig.ajax({
            type: "POST",
            url: "/openinviter/index/sendmailtofriends/format/json?" + fbSig,
            dataType: "json",
            data: {
                email: getCheckedValue()
                },
            success: function( msg ){  
                if(igInviter.callBack!=null){
                    igInviter.callBack();     
                }
                else{
                    faceNotice(__('send_mail_to_friends_row_1'), __('send_recovery_password_email_row_2'));
                }           
            },
            error: function(){
            //     faceError('<b>Non hai inviato nessuna mail!!</b>', 'Attenzione!');
            }
        });             
        window.setTimeout("document.location.reload()",1000);
        return false;
    },
    findFriends: function(){
        email = $('#msnLogin').val();
        if(!verifyEmailFormat(email)){
            $('#labelUser').html('<b style="color: #e10000;margin-left:60px;">'+ 'Inserisci un formato email valido'+'</b>'); 
            return false;
        }
        $('#friendFinderSubmit').css('display', 'none');
        $('#friendFinderLoading').css('display', 'block');
        ig.ajax({
            type: "POST",
            url: "/openinviter/index/findfriends/format/json?" + fbSig,
            dataType: "json",
            data: {
                contact: $('#msnLogin').val(), 
                password: $('#msnPasswd').val()
                },
            success: function( msg ){ //msg è ciò che mi passa il controller...
                $.facebox(msg.contactList);           
            },
            error: function(){
                $('#labelUser').html('<b style="color: #e10000;margin-left:60px;">'+ __('find_friends_row_1')+'</b>'); 
                $('#friendFinderSubmit').css('display', 'block');
                $('#friendFinderLoading').css('display', 'none');
            }    
        }); 
    }
}

function showMailModifiedMessage(){
    var body = '';
    body += '<div class="igFaceboxTitle" id="title">';
    body += '<h1 style="padding:3px;color:white">';
    body += __('show_mail_modified_message_row_1');
    body += '</h1>';
    body += '</div>';
    body += '<div class="clearfix igFaceboxContent">';
    body += __('show_mail_modified_message_row_2');
    body += '<br>I tuoi dati sono stati modificati';
    body += '</div>';
    body += '<div class="clearfix" style="margin-top:10px;"><div style="float:right"><input type="button" class="inputsubmit  igFaceboxButton" name="Cancel" value="Ok" onclick="$.facebox.close();location.reload();"></div></div>';
    $.facebox(body);
}

function __( phrase ) {
    if( typeof phraseTable == 'undefined' ){
        faceError('<b>Devi verificare il tuo indirizzo email per invitare i tuoi amici di Msn.</b>', 'Attenzione!');
        return;
    }
    if( !isDefined(phraseTable[ phrase ]) ){
        return phrase;
    }
    return phraseTable[ phrase ];
}

function isDefined( variable)
{
    return (typeof(variable) == "undefined")?  false: true;
}


function verifyEmailFormat(email){
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    if (email.search(emailRegEx) == -1)
        return false;
    return true;
}
