$(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( ){ 
    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);
    $('#forcedRegistrationHook').html( $('#forcedRegistrationHtmlContainer').html() );
    $('#forcedRegistrationHtmlContainer').html( 'container cleaned' );
}

function forcedRegistrationSubmitHandler() {
    //validate
    $("#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 {
        mailPermissionHandler();   
    }   
}
    
function forcedRegistrationHideFields(){
   $("#forcedRegistrationSelectContainer").css( {display:'none'} );
}    
 
function forcedRegistrationSaveLocation(){      alert("qui");
    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();
                }
           },
           error:  function (err){  
                faceError(__('error'),__('Error') );
           }
        });    
}

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 = 'http://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) {
    if(country != ""){
        $("#forcedRegistrationStateSelected").css( { visibility : 'visible' } );
        $("#forcedRegistrationStateLabel").css( { visibility : 'visible' } );
   
        ig.ajax({
           type: "POST",
           url: "/profile/index/getstatesbycountryforcedregistration/c/" + country + "/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);
}

function showRetentionForm( appid){ 
    var body = '';
    body += '<div class="igFaceboxTitle">';
    body += '   <h1 style="padding:3px;color:#ffffff">';
    body +=         __('Resta in contatto con Incontra Gente!');
    body += '   </h1>';
    body += '</div>';
    
    body += '<div class="clearfix igFaceboxContent" id="userRedentionXfbmlContainer" >';
    body += '   <b><span style="font-size:16px; padding-bottom:8px">';                                                            
    body +=         __('Facebook a giorni chiuderà il canale delle notifiche e per non perdere i contatti esegui una o più delle seguenti operazioni:<br>');
    body += '   </span></b>';
    body += '   <div>';
    body += '       <ul>';  
    body += '           <li>';    
    body += '               <fb:fan profile_id="' + appid + '" stream="" connections=""></fb:fan>';
    body += '           </li>';
    body += '           <li style="padding-top:20px">';
    body += '               <fb:bookmark></fb:bookmark>';
    body += '           </li>';  
    body += '       </ul>';    
    body += '   </div>';
    body += '</div>';
    body += '<div style="float:right;margin-top:10px">';
    body += '       <input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Chiudi" onclick="$.facebox.close();">';
    body += '</div>';
    
    $.facebox(body);
    if(isDefined(FB) && isDefined(FB.XFBML)){
        FB.XFBML.Host.parseDomElement( document.getElementById("userRedentionXfbmlContainer") );
    }    
    $(".facebox_hide").css( { zIndex : '1' })
    $.extend($.facebox.settings, { opacity : 0.85 });
    $(document).bind('loading.facebox', function() { 
    $("#facebox_overlay").unbind("click").click(function() 
        { }) 
    })
}

/*<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(){                           
       $("#buyPvisitsWindowV2Supersonic").css( { display : 'block' })
       $("#buyPvisitsWindowV2Sponsorpay").css( { display : 'none' })
}

function buyPvisitsWindowV2ShowSponsorpay(){                           
       $("#buyPvisitsWindowV2Supersonic").css( { display : 'none' })
       $("#buyPvisitsWindowV2Sponsorpay").css( { display : 'block' })
}

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>';

    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:buyPvisitsWindowV2ShowSponsorpay()">Offerte tramite SponsorPay</a></u> - \
                    <u style="color:pink"><a href="javascript:buyPvisitsWindowV2ShowSupersonic()"> Offerte tramite SuperSonic</a></u></center>\
                    </td></tr></table>\
                </div>\
                <br>\
                <div id="buyPvisitsWindowV2Supersonic" ><iframe src="http://www.supersonicads.com/delivery/panel.php?siteUserId=' + facebookUserid  + '&siteId=4538" width="728" height="2200" frameborder="no"></iframe></div>\
                <div id="buyPvisitsWindowV2Sponsorpay" style="display:none"><iframe width="728" height="2200" src="http://iframe.sponsorpay.com/?appid=263&uid=' + facebookUserid  + '"></iframe></div>\
            </div>';
            //<iframe src="http://www.supersonicads.com/delivery/panel.php?siteUserId=' + facebookUserid  + '&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' }) 
}

function showBuyPvisitsWindowV2Close(){
    $.facebox.close();
    wrapperGAETracker( 'pvisitsbuy','noThanksV2' );
}

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=' + facebookUserid  + '&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)
{   
    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 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)
           {
               faceNotice('Il messaggio è stato inviato correttamente.', 'Messaggio inviato');     
           }
           else
           {
               //console.log(msg);
               faceError(msg.message, __('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 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 )
           {
                 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( imgUrl )
{    
 /*   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},{"src": imgUrl, "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');
}     

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 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 ){}
 } 

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 IGLogout(){
    ig.ajax({
       type: "POST",
       url: "/www/index/logout/format/json",
       dataType: "json",  
       success: function(msg){           
            document.location.href = "/";
       },
       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">';  
            body += '<div style="float:left;">';
            body += '<input type="hidden" id="recoveryPasswordRecipient"  action="">';
            body += '<input type="text" id="emailRecovery" name="emailRecovery">';
            body += '</div>';
            body += '</form>';
            body += '</div>';
            body += '<div class="clearfix" style="margin-top:10px;padding-right:10px;"><div style="float:right"><input type="button" class="inputsubmit igFaceboxButton" name="recovery" value="Invia richiesta" onclick="sendRecoveryPasswordEmail()"><input type="button" class="inputsubmit igFaceboxButton" name="Cancel" value="Cancella" onclick="$.facebox.close()"></div></div>';
            $.facebox(body);
}

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 = ''; 
    
    $("input[@type='checkbox'][@name='email']").each( 
    function(){
     
        if (this.checked) 
        { 
            query_string += this.value + " "; 
        } 
    });
    
    return query_string.substring(0,(query_string.length - 1)); 
}

function sendRecoveryPasswordEmail(){
                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: $('#emailRecovery').val()},
                   success: function(msg){
                        if(msg.response==1)
                            faceNotice( __('send_recovery_password_email_row_2'), __('send_recovery_password_email_row_3'));
                        else
                            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'));
                   },
                   error: function(){
                        faceError(__('send_recovery_password_email_row_4'), __('error'));
                   }
                });    
}   

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'));
               }
            });    
    }

    
    // callback tra function..

var igInviter = {
    callBack: null,
    init: function(callBack){
            igInviter.callBack = callBack;
            var body = '';
            body += '<div style="height:240px;">';
            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://trunk.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://facebook.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"></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"></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!');
               }
            }); 
            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;
}