var I18n=I18n||{};
I18n.translations={it:{messages:{"delete":"Elimina","public":"Pubblico",reply:"Rispondi","private":"Privato",send:"Invia"},places:{"new":{photo:"Foto",add:"Aggiungi!",my_sports:"Sport Praticabili *",create_place_hint:"Conosci una struttura pubblica o privata che vuoi condividere con gli altri utenti di We-Sport? Completa i dati sottostanti in modo corretto cos\u00ec che la struttura possa essere visualizzata sulla mappa nel punto esatto. (Tutte le strutture sono soggette alle segnalazioni degli altri utenti We-Sport: non inserire, per favore, strutture inesistenti o inappropriate).",set:"Cerca",
costs_required:"Costi",hours_required:"Orari",place_description_required:"Descrizione struttura *",mail:"Indirizzo email",max_500_chars:"max 500 caratteri",address_hint:"Inserisci l'indirizzo esatto (una volta inserito l'indirizzo potrai spostare il marker nella posizione esatta in cui si trova la struttura sportiva): *",save:"Salva",website:"Sito web",phone:"Numero di telefono",place_name_required:"Nome della struttura *",edit_place:"Modifica la struttura",create_place:"Inserisci una nuova struttura",
days_required:"Giorni",sport_hint:"Inserisci i giorni, gli orari e i costi dello sport praticato nella struttura:",special_sports:"Sport Speciali",sport:"Sport"},locations_hint:"Ricerca eventi vicini all'indirizzo specificato!",been:"In cui sei stato",search_places:"Strutture",search_places_hint:"Ricerca strutture per nome",favorites:"Preferite",show:{flag3:"A pagamento",no_sports:"L'utente non pratica alcuno sport",no_photos:"Non ci sono foto.",back:"Indietro",flag4:"Gratuito",friends:"Collegati alla struttura",
edit:"Modifica",flag5:"Personale qualificato",add_a_photo:"Aggiungi una foto!",comments:"Commenti",no_videos:"Non ci sono video.",days:"Giorni",cleverness_count:"Livello sportivo: {{count}}","private":"Privato",upload:"Upload",photos:"Foto",no_events:"Non sono presenti eventi",videos:"Video",send_message:"Invia",events:"Eventi",no_friends:"Non ci sono utenti collegati",quality_count:"Qualit\u00e0: {{count}}",stars_count:"Punteggio: {{count}}",remove:"Rimuovi",feedback:"Esprimi un feedback sulla struttura:",
youtube_hint:"Inserisci un qualsiasi indirizzo di video YouTube o Vimeo, verr\u00e0 mostrato direttamente nel tuo profilo.",save:"Salva",new_event:"Nuovo evento",costs:"Costi",hours:"Ore",flag1:"Al coperto",add_a_video:"Aggiungi un video!",sports:"Sport",flag2:"All'aperto",reliability_count:"Affidabilit\u00e0: {{count}}",youtube_url:"YouTube o Vimeo URL",abuse:"Segnala abuso"},locations:"Luogo",mine:"Inserite da me",sport:"Sport",sport_hint:"Ricerca eventi legati a sport di tuo interesse!",nearby:"Vicini",
create_new:"Inserisci struttura",search:"Cerca"},layout:{otherwise_login_with_social_networks:"o connettiti con",my_home:"Home",change_password:"Modifica password",logout:"Logout",messages:{insert_email:"Errore: per favore, inserisci la tua email nel campo apposito e riprova.",forgot_password:{insert_email:"Errore: per favore, inserisci la tua email nel campo apposito e riprova.",new_password_was_sent:"Una nuova password \u00e8 stata inviata al tuo indirizzo email!",email_not_found:"Errore: l'email indicata non \u00e8 registrata su We-Sport!",
error:"Errore durante la procedura di ripristino password: controlla di aver digitato correttamente la tua email, oppure prova ad effettuare il log in attraverso uno dei social network presenti sulla destra. (Dettaglio errore: {{status_detail}})"},login:{insert_email:"Errore: per favore, inserisci la tua email nel campo apposito e riprova.",insert_password:"Errore: per favore, inserisci la tua password nel campo apposito e riprova.",username_or_password_invalid:"Errore: username o password non corretti!"}},
forgot_your_password:"Recupera password",my_profile:"Profilo",welcome:"We-Sport ti da il benvenuto nella community dedicata allo sport in cui potrai scegliere tra pi\u00f9 di 300 sport e trovare nuovi e vecchi amici con cui praticarli. Iniziamo a conoscerci: inserendo i tuoi dati e la citt\u00e0 in cui pratichi sport potrai individuare gli sportivi e gli eventi pi\u00f9 vicini a te.",inbox:{one:"Inbox (1)",other:"Inbox ({{count}})",zero:"Inbox"},settings:"Impostazioni",stay_logged_in:"Resta collegato",
login:"Login",password:"Password",email:"Email"},"static":{contact_us_title:"Contact Us",privacy_title:"Privacy Policy",news_title:"News",press:{view_article:"Visualizza l'articolo"},news:{news6_text_long:"<p>Precedenti studi preliminari suggeriscono che l'esercizio meditativo possa produrre benefici in soggetti con insufficienza cardiaca cronica, tuttavia non si era ancora riusciti a testare un campione di grosse dimensioni.</p> <p>Il gruppo di ricercatori guidati dal Dott. Phillips ha indagato se il tai chi, in aggiunta alle cure standard, migliori la capacit\u00e0 funzionale e la qualit\u00e0 della vita in pazienti con insufficienza cardiaca cronica.</p> <p>Lo studio, pubblicato nell'Archive of Internal Medicine ha valutato 100 pazienti. Un gruppo  ha svolto un programma di Tai chi di 12 settimane, un altro \u00e8 stato il gruppo di controllo.</p> <p>Le misurazioni comprendevano la capacit\u00e0 di svolgere esercizio fisico ed un questionario sulla qualit\u00e0 della vita.</p> <p>Al termine dello studio, durante il confronto tra il gruppo che ha praticato esercizi di Tai Chi ed il gruppo di controllo, il primo gruppo aveva maggiori miglioramenti della qualit\u00e0 della vita, oltre ad ulteriori miglioramenti osservati nell'esercizio fisico e nell'umore.</p> <p>In conclusione il Tai Chi pu\u00f2 migliorare la qualit\u00e0 della vita, l'umore, e l'esercizio nei pazienti con insufficienza cardiaca cronica.</p> <p><a target='_blank' href=\"http://archinte.ama-assn.org/cgi/content/abstract/171/8/750\">http://archinte.ama-assn.org/cgi/content/abstract/171/8/750</a></p>",
news6_text:"Precedenti studi preliminari suggeriscono che l'esercizio meditativo possa produrre benefici in soggetti con insufficienza cardiaca cronica, tuttavia non si era ancora riusciti a testare un campione di grosse dimensioni... ",news6_date:"09/12/2011",news5_text:"Il Journal of Atherosclerosis and Thrombosis ha pubblicato un articolo di un gruppo di ricercatori giapponesi, guidato dal dott. Tanaka, che ha dimostrato come l'attivit\u00e0 fisica incrementi l'attivit\u00e0 della lipoproteina lipasi... ",
news5_date:"09/12/2011",news4_text:"",news4_date:"01/05/2011",news3_text:"",news2_text_long:"<p>Lo scopo,\u00a0di questo\u00a0studio \u00e8\u00a0di\u00a0esaminare\u00a0le relazioni tra\u00a0clima\u00a0e\u00a0attivit\u00e0 fisica all'aperto\u00a0(PA).\u00a0Ogni giorno \u00e8 stata registrata la temperatura max\u00a0[DMT], le\u00a0precipitazioni\u00a0e la\u00a0velocit\u00e0\u00a0del vento.\u00a0Un contatore all\u2019infrarosso ha fornito i dati sull\u2019uso quotidiano di un percorso podistico in un parco in un\u00a0periodo di 2 anni.  Considerando i giorni della settimana ed i mesi dell\u2019anno si \u00e8 evidenziato come la temperatura massima, l\u2019entit\u00e0 di precipitazioni ed il vento abbiano influenzato in modo significativo la pratica sportiva all\u2019aperto.</p>",
news1_text:"Pochi studi hanno indagato i fattori che influenzano la predisposizione a svolgere attivit\u00e0 fisica durante la transizione dall'adolescenza all'et\u00e0 adulta. Questo studio esplora le associazioni di fattori socio-demografici, comportamentali, socio-culturali... ",news1_title:"Fattori che influenzano la predisposizione a svolgere attivit\u00e0 fisica.",news3_date:"02/05/2011",news2_text:"Lo scopo, di questo studio \u00e8 di esaminare le relazioni tra clima e attivit\u00e0 fisica all'aperto (PA). Ogni giorno \u00e8 stata registrata la temperatura max [DMT], le precipitazioni e la velocit\u00e0 del vento. Un contatore all\u2019infrarosso ha fornito i dati sull\u2019uso quotidiano di un percorso podistico in un parco in un periodo di 2 anni... ",
news2_title:"Relazioni tra il clima e l\u2019attivit\u00e0 fisica all'aperto.",news5_title:"Dodici settimane di allenamento di jogging aumentano le concentrazioni sieriche di lipoproteina lipasi in uomini di mezza et\u00e0 sovrappeso/obesi.",news3_title:"Equilibrio\u00a0psicologico\u00a0in\u00a0atleti\u00a0di alto livello: differenze\u00a0di genere\u00a0e\u00a0modelli\u00a0specifici per lo sport.",news2_date:"09/05/2011",news4_title:"Stile di vita,\u00a0abitudini alimentari e\u00a0abitudini di consumo\u00a0degli studenti\u00a0universitari\u00a0di sesso maschile\u00a0a seconda\u00a0della frequenza\u00a0dei consumi\u00a0di bevande\u00a0commerciali.",
news3_text_long:"<strong>OBIETTIVI:</strong> <p>Pochi\u00a0studi\u00a0epidemiologici\u00a0si sono concentrati sulla\u00a0salute\u00a0psicologica degli atleti\u00a0di alto livello.\u00a0Questo studio ha\u00a0lo scopo di\u00a0identificare\u00a0i principali problemi\u00a0psicologici che gli atleti di alto livello incontrano e\u00a0le\u00a0variazioni\u00a0 basate\u00a0sul sesso\u00a0e\u00a0lo sport\u00a0praticato.</p> <strong>RISULTATI:</strong> <p>Si \u00e8 analizzato un campione rappresentativo\u00a0del\u00a013% della\u00a0popolazione\u00a0atleta\u00a0francese.</p> <p>Il 17%\u00a0degli atleti\u00a0ha\u00a0almeno un disturbo\u00a0in corso\u00a0o\u00a0recente; il\u00a0disturbo d'ansia generalizzato\u00a0(GAD) \u00e8\u00a0il pi\u00f9\u00a0diffuso\u00a0(6%),\u00a0seguito da\u00a0disturbi del comportamento alimentare\u00a0non\u00a0specifici\u00a0(4,2%).\u00a0Complessivamente, il 20,2% delle donne\u00a0ha avuto almeno un\u00a0psicopatologia,\u00a0contro il\u00a015,1%\u00a0degli uomini.</p> <p>Questa predominanza\u00a0femminile riguarda ansia\u00a0e\u00a0disturbi alimentari,\u00a0depressione, disturbi del sonno\u00a0e comportamenti\u00a0autolesionisti.\u00a0I tassi pi\u00f9 elevati\u00a0di\u00a0GAD\u00a0sono legati allo  sport\u00a0estetico\u00a0(16,7%\u00a0vs\u00a06,8%\u00a0in\u00a0altri sport\u00a0per gli uomini\u00a0e\u00a038,9%\u00a0vs\u00a010,3% per le donne),\u00a0la prevalenza pi\u00f9 bassa\u00a0\u00e8 stata\u00a0trovata\u00a0in\u00a0atleti di\u00a0sport ad alto\u00a0rischio (3,0%\u00a0vs\u00a03,5%)\u00a0.\u00a0I disturbi alimentari\u00a0sono\u00a0pi\u00f9\u00a0comuni\u00a0tra\u00a0le donne\u00a0nelle competizioni sportive\u00a0(14% vs\u00a09%),\u00a0ma per\u00a0gli uomini\u00a0sono stati\u00a0trovati\u00a0soprattutto\u00a0in\u00a0sport di combattimento\u00a0(7%\u00a0vs\u00a04,8%).</p> <strong>DISCUSSIONE:</strong> <p>Questo\u00a0studio\u00a0mette in luce\u00a0importanti differenze\u00a0psicopatologiche\u00a0tra\u00a0atleti\u00a0maschi e femmine, a dimostrazione\u00a0che\u00a0le numerose differenze\u00a0in base al sesso\u00a0nella popolazione\u00a0generale si applicano\u00a0agli atleti\u00a0d'elite.\u00a0Mentre\u00a0la prevalenza\u00a0di problemi psicologici\u00a0non \u00e8\u00a0maggiore\u00a0rispetto alla popolazione\u00a0generale,\u00a0le variazioni\u00a0di psicopatologie\u00a0in\u00a0diversi sport\u00a0suggeriscono\u00a0che\u00a0i vincoli\u00a0specifici\u00a0potrebbero influenzare\u00a0lo sviluppo\u00a0di alcuni\u00a0disturbi.</p>",
news1_text_long:"<p>Pochi\u00a0studi\u00a0hanno\u00a0indagato\u00a0i fattori\u00a0che influenzano la predisposizione a svolgere attivit\u00e0 fisica durante la\u00a0transizione\u00a0dall'adolescenza all'et\u00e0 adulta.\u00a0Questo\u00a0studio\u00a0esplora\u00a0le associazioni\u00a0di\u00a0fattori socio-demografici, comportamentali,\u00a0socio-culturali,\u00a0attitudinali e\u00a0fisici\u00a0misurati\u00a0durante l'infanzia\u00a0e\u00a0l'adolescenza\u00a0con\u00a0la predisposizione a svolgere attivit\u00e0 fisica\u00a0durante la\u00a0transizione\u00a0dall'adolescenza all'et\u00e0 adulta. I fattori che influenzano maggiormente la predisposizione alla pratica sportiva in et\u00e0 adulta per le femmine sono l\u2019aver sviluppato in et\u00e0 adolescenziale competenze sportive e capacit\u00e0 cardiorespiratorie, per i maschi l\u2019avere un padre attivo e praticare sport al di fuori dell\u2019orario scolastico.</p>",
news1_date:"05/05/2011",news5_text_long:"<p>Il Journal of Atherosclerosis and Thrombosis ha pubblicato un articolo di un gruppo di ricercatori giapponesi, guidato dal dott. Tanaka, che ha dimostrato come l'attivit\u00e0 fisica incrementi l'attivit\u00e0 della lipoproteina lipasi, ovvero l'enzima deputato alla conversione della frazione a bassa densit\u00e0 del colesterolo (LDL), pericolosa per la salute, in quella ad alta densit\u00e0 (HDL).</p> <p>L'aumento della lipoproteina era stato gi\u00e0 dimostrato dopo somministrazione di farmaci, ma per la prima volta lo studio ha dimostrato come anche l'attivit\u00e0 fisica concorra all'incremento della concentrazione sierica dell'enzima.</p> <p>Questo studio \u00e8 stato svolto con l'obiettivo di investigare gli effetti di 12 settimane di allenamento aerobico supervisionato, in relazione al livello di concentrazione, nel siero di LPL pre-eparina in uomini sovrappeso/obesi.</p> <p>Quindici uomini sovrappeso/obesi di mezz'et\u00e0 sono stati sottoposti ad esercizi supervisionati in un periodo che andava da una a dodici settimane: un gruppo a piedi (8 partecipanti con un progressivo aumento di velocit\u00e0 di camminata, a ritmo sostenuto, in sessioni di 60 minuti per 3 volte alla settimana) ed un gruppo di jogging (7 partecipanti che hanno aumentato progressivamente la velocit\u00e0 di corsa, in sessioni di allenamento di 60 minuti per 3 volta alla settimana). Tutti i partecipanti hanno mantenuto una dieta libera. I campioni di sangue sono stati raccolti all'inizio ed alla fine delle 12 settimane.</p> <p>Le concentrazioni sieriche di pre-eparina LPL sono incrementate nei soggetti del gruppo jogging. Nel gruppo della camminata, le concentrazioni sieriche di pre-eparina LPL sono rimaste invece invariate dopo le 12 settimane.</p> <p>Questo studio dimostra come 12 settimane di allenamento di jogging aumentino le concentrazioni sieriche di pre-eparina LPL in uomini di mezz'et\u00e0 sovrappeso/obesi.</p> <p><a target='_blank' href=\"http://www.ncbi.nlm.nih.gov/pubmed/20075597\">http://www.ncbi.nlm.nih.gov/pubmed/20075597</a></p>",
news4_text_long:"<p>Un consumo eccessivo di\u00a0bevande\u00a0zuccherate\u00a0pu\u00f2 ridurre\u00a0la\u00a0qualit\u00e0\u00a0di apporto nutrizionale;\u00a0questo\u00a0studio ha esaminato i\u00a0modelli\u00a0di consumo\u00a0di\u00a0bevande commerciali,\u00a0stile di vita,\u00a0abitudini alimentari\u00a0e la percezione\u00a0del\u00a0gusto dolce.\u00a0I partecipanti\u00a0sono stati\u00a0407, tutti  studenti\u00a0universitari\u00a0di sesso maschile\u00a0e\u00a0sono state raccolte informazioni\u00a0attraverso un questionario autosomministrato.\u00a058 soggetti del gruppo, non fumatori\u00a0, hanno partecipato alla\u00a0prova di degustazione.\u00a0I partecipanti\u00a0sono stati\u00a0divisi in tre\u00a0gruppi\u00a0a seconda\u00a0della frequenza\u00a0dei consumi\u00a0di bevande\u00a0commerciali:\u00a0120\u00a0con consumo sporadico (<1 consumo\u00a0a settimana),\u00a0227\u00a0moderato\u00a0(1-3 consumi\u00a0alla settimana)\u00a0e 133\u00a0gruppi di\u00a0frequente\u00a0consumo\u00a0(>\u00a03 consumi\u00a0a settimana).\u00a0La maggior parte dei soggetti\u00a0facenti parte del\u00a0gruppo con consumo sporadico hanno scelto\u00a0acqua, t\u00e8 e\u00a0latte di soia come\u00a0 loro\u00a0drink\u00a0preferiti,\u00a0la maggioranza del gruppo con consumo\u00a0frequente hanno scelto\u00a0bibite gassate\u00a0e caff\u00e8.\u00a0Il gruppo con consumo frequente ha\u00a0consumato succhi di\u00a0frutta,\u00a0caff\u00e8,\u00a0e\u00a0bibite per lo sport significativamente pi\u00f9 spesso\u00a0del gruppo con consumo sporadico,\u00a0ma\u00a0non\u00a0ha scelto latte\u00a0e\u00a0t\u00e8.\u00a0Il gruppo dei consumatori frequenti ha consumato bevande\u00a0casualmente, senza\u00a0una specifica occasione\u00a0(P\u00a0=0.000)\u00a0rispetto al gruppo\u00a0di consumatori\u00a0sporadici.</p> <p>L\u2019uso frequente\u00a0di\u00a0bevande\u00a0commerciali\u00a0\u00e8 stato associato a\u00a0spuntini\u00a0frequenti\u00a0(P\u00a0=\u00a00,002),\u00a0fast food\u00a0(p\u00a0=\u00a00,006), mangiare\u00a0fuori casa\u00a0(P\u00a0=\u00a00,003), mangiare\u00a0cibi\u00a0precotti \u00a0(P\u00a0=\u00a00,000), mangiare prodotti alimentari trasformati\u00a0(P\u00a0=\u00a00,001)\u00a0e\u00a0dolci\u00a0(P\u00a0=\u00a00,002),\u00a0e al bere\u00a0bevande alcoliche (P\u00a0=\u00a00,029).\u00a0Il gruppo con consumo frequente\u00a0tendeva ad\u00a0avere\u00a0una soglia pi\u00f9 elevata\u00a0di\u00a0sapore dolce,\u00a0senza\u00a0raggiungere\u00a0la significativit\u00e0 statistica.\u00a0I risultati\u00a0forniscono\u00a0informazioni per\u00a0lo sviluppo di\u00a0strategie\u00a0per il programma di\u00a0educazione alla nutrizione incentrate\u00a0sulla riduzione del consumo\u00a0di\u00a0bevande\u00a0zuccherate commerciali non necessarie.</p>",
download_pdf:"Scarica il PDF",news6_title:"Esercizi di Tai Chi in pazienti con insufficenza cardiaca cronica.",more:"Continua",search:"Cerca"},tos_title:"Termini del Servizio",sponsor_title:"Sponsor",press_title:"Press"},events:{"new":{modified:"L'evento \u00e8 stato modificato correttamente!",friends:"Amici",users_hint:"Clicca sugli sportivi che vuoi invitare:",waiting:"In attesa di risposta","public":"pubblico",reached_max:"* E' stato raggiunto il numero minimo di partecipanti per creare le squadre.",
event_description:"Descrizione evento",required_fields:"* Campi obbligatori","private":"privato",select_location:"Modifica il luogo selezionando uno dei tuoi luoghi:",max:"max *",partecipants:"Partecipanti ",hour:"Ora *",other_users:"Clicca sugli altri sportivi che vuoi invitare:",declined:"Non partecipanti",sn:"Social Network",event_name:"Nome evento *",date:"Data *",create_event:"Crea evento",edit_event:"Modifica evento",recall_tip:"Recupera ultimo evento",selected_users:"Sportivi selezionati:",
other_emails:"Email di altri sportivi (separate da virgola)",max_500_chars:"max 500 caratteri",save:"Salva",resend_message:"Invia un sollecito via mail a questo sportivo!",notify_me:"Avvertimi quando viene raggiunto il numero minimo di partecipanti per creare le squadre.",address_hint:"Luogo di incontro o in cui si praticher\u00e0 l'attivit\u00e0: *",min:"min *",general_infos:"Info generali",users:"Sportivi",create_event_hint:"Crea un nuovo evento sportivo, una partita o un incontro di allenamento. Completa le informazioni richieste:",
message:"Inserisci un messaggio personale (facoltativo)",nearby:"Vicini",invited:"Sportivi invitati",sport:"Sport *",event_type:"Tipo di evento *",recall:"Recupera",created:"L'evento \u00e8 stato creato correttamente!",create_teams:"Crea le squadre (facoltativo) *",search:"Cerca",edit_event_hint:"Modifica l'evento, la partita o l'incontro di allenamento. Completa le informazioni richieste:"},locations_hint:"Ricerca eventi vicini all'indirizzo specificato!",invites:"Inviti",events:"Eventi",events_hint:"Ricerca eventi per nome!",
show:{waiting_for_confirmation:"In attesa di conferma",edit:"Modifica","delete":"Elimina",comments:"Commenti",declined_partecipants:"Non partecipanti",partecipants:"Partecipanti",waiting_for_acceptation:"In attesa di approvazione",send:"Invia"},locations:"Luogo",sport:"Sport",sport_hint:"Ricerca eventi legati a sport di tuo interesse!",nearby:"Vicini",create_new:"Crea un evento",search:"Cerca",created:"Creati da me"},inbox:{wall_message:{title:"{{name}} scrive:",reply_here:"Rispondi qui:",sent_success:"Risposta inviata!",
send:"Invia!"},no_message:"Nessun messaggio",new_pro_message:{location:"Luogo",intro:"Usa questo strumento per comunicare novit\u00e0 sui servizi che offri. Puoi contattare non solo gli sportivi, ma anche i PRO.",pro:"Pro",send_message:"Invia!",max_500_chars:"max 500 caratteri",users:"Sportivi",block_pro:"Messaggi bloccati da questo PRO",write_message:"Scrivi il messaggio da inviare:",sport:"Sport",button_label:"Nuovo messaggio PRO"},event_message:{title:"{{name}} ha scritto un messaggio nell'evento {{event}}:"},
friendship_request:{title:"{{name}} ti ha chiesto l'amicizia:"},show_more:"Mostra altri",mark_as_read:'Segna come "letto"',invite_event:{title:"{{name}} ti ha invitato all'evento {{event}}:",declined:"Hai declinato l'invito all'evento.",accepted:"Hai accettato l'invito all'evento!"},request_partecipation_event:{title:"{{name}} vuole partecipare all'evento {{event}}:",declined:"Hai declinato la richiesta di partecipazione all'evento.",accepted:"Hai accettato la richiesta di partecipazione all'evento!"},
event_feedback:{given_feedback:"Hai dato un punteggio di {{feedback}}!",vote:"Vota!",title:"Evento {{event}}:",message:"Esprimi il tuo feedback sui partecipanti e la struttura!"}},settings:{step3:{add:"Aggiungi",associated_sports_for_place:"Sport che pratichi qui",previous:"<< Precedente",your_places:"I tuoi luoghi",your_main_place:"Il tuo luogo principale",show_my_position:"Mostra la mia posizione nella mappa!",my_sports_for_place:"Sport che pratichi",save:"Salva",your_places_hint:"Seleziona i luoghi in cui pratichi abitualmente sport e associali all'attivit\u00e0 praticata. In questo modo sar\u00e0 pi\u00f9 semplice trovare altri sportivi che condividono le tue stesse passioni\u2026 vicino a te! Se lo desideri, puoi completare questo step e modificare tutti i dati in un secondo momento cliccando su 'Impostazioni'.",
address_hint:"Inserisci l'indirizzo di un luogo in cui pratichi sport:",sports_for_place:"Clicca sugli sport che pratichi in questo luogo:",all_sports:"Associa tutti",other_places:"Gli altri tuoi luoghi",search:"Cerca"},step2_pro:{service_sports_error:"Per favore, inserisci almeno uno sport per il servizio.",minor_sports:"Altri sport",associated_sports_for_place:"Sport associati al servizio",edit:"Modifica",previous:"<< Precedente","delete":"Elimina",click_to_add_service:"Clicca qui per aggiungere un nuovo servizio!",
your_services:"I tuoi servizi",other_services:"Gli altri tuoi servizi",main_sports:"Sport pi\u00f9 selezionati",find_service:"Cerca il tuo servizio o prodotto tra quelli gi\u00e0 esistenti, oppure inseriscine uno nuovo!",save:"Salva",general_description:"Inserisci una descrizione generale (max 500 caratteri)",next:"Successivo >>",special_sports:"Special sport",choose_sports_for_service:"Offri questo servizio per i seguenti sport:",service_placeholder:"Nome del servizio o prodotto...",your_main_service:"Il tuo servizio principale",
service_name_error:"Per favore, specifica il nome del servizio.",your_services_hint:"Specifica i servizi che puoi offrire agli utenti di We-Sport. Pi\u00f9 dettagliato sarai nell'indicare gli sport collegati ai tuoi servizi, pi\u00f9 facile sar\u00e0 trovarti con gli appositi strumenti di ricerca (per servizi offerti non si intende lo sport o gli sport di cui ti occupi, bens\u00ec i servizi che offri ai tuoi clienti /associati /tesserati). Per completare correttamente la registrazione devi specificare almeno un servizio."},
change_pass:{title:"Cambia password",change:"Cambia",new_password:"Nuova password:",hint:"Inserisci la vecchia password e quella nuova:",repeat_password:"Ripeti la nuova password:",old_password:"Vecchia password:"},step3_pro:{previous:"<< Precedente",main_place:"Il tuo luogo principale",add:"Aggiungi",edit:"Modifica",associated_services:"I servizi che offri qui",your_places:"I tuoi luoghi",show_my_position:"Mostra la mia posizione nella mappa!",services_for_place:"Clicca sui servizi che offri in questo luogo:",
save:"Salva",address_hint:"Inserisci l'indirizzo di un luogo in cui offri i tuoi servizi:",your_places_hint:"Possiedi o gestisci delle strutture sportive? Pratichi frequentemente la tua attivit\u00e0 in un determinato luogo? Hai pi\u00f9 di un punto di vendita? In questa sezione puoi indicare questi luoghi.",all_services:"Associa tutti",services:"I tuoi servizi",other_places:"Gli altri tuoi luoghi"},step0:{login_as_user:"Accedi come SPORTIVO",pro:"PRO?",login_as_pro:"Accedi come PRO",pro_hint:"Registrati qui se sei un un'associazione, una struttura, una federazione sportiva, un'azienda o un professionista che pu\u00f2 dare aiuto per svolgere nel migliore dei modi l'attivit\u00e0 fisica degli sportivi. Se non sei un PRO, iscriviti come SPORTIVO.",
user_hint:"Registrati qui per creare un profilo da SPORTIVO e poter cos\u00ec contattare altri sportivi vicino a te, partecipare a eventi e lanciare sfide!",user:"SPORTIVO?"},notifications:{event_message:"Quando viene scritto un messaggio sulla pagina di un evento a cui sono stato invitato.",title:"Notifiche",friendship_request:"Quando ricevo una richiesta di amicizia.",change:"Cambia",event_invite:"Quando vengo invitato ad un evento.",statement:"Desidero ricevere un'email:",hint:"Qui puoi selezionare quali notifiche desideri ricevere sulla tua casella di posta elettronica:",
we_sport_news:"Quando ci sono novit\u00e0 da parte del Team di We-Sport.",profile_message:"Quando viene scritto un messaggio sul mio profilo.",confirm_friendship_request:"Quando viene accettata una richiesta di amicizia."},step1:{address_hint_pro:"Inserisci il tuo indirizzo principale (una volta inserito l'indirizzo potrai spostare il marker nella posizione esatta in cui si trova la tua sede o la struttura sportiva da te gestita o in cui pratichi l'attivit\u00e0): *",phone_required:"Numero di telefono da visualizzare *",
company:"Azienda",info_mail:"Email da visualizzare",structure:"Sport Sociale",association:"Associazione",last_name_required:"Cognome *",upload_error:"La dimensione della foto deve essere max 500Kb e il formato dev'essere JPG o PNG",sex_required:"Sesso *",first_name_required:"Nome *",info_mail_required:"Email *",federation:"Federazione sportiva",pro_name_required:"Nome PRO ufficiale *",required_fields:"* Campi obbligatori",sex_female:"Femmina",upload:"Upload",choose_photo:"Scegli foto",infos_hint:"Inserisci i tuoi dati in modo da trovare sportivi adatti al tuo livello e che praticano sport nella tua stessa area.",
show_my_position:"Mostra la mia posizione nella mappa!",email_required:"Email *",profession_required:"Categoria *",address_hint:"Inserisci l'indirizzo di un luogo in cui pratichi sport (una volta inserito l'indirizzo potrai spostare il marker nella posizione esatta che desideri): *",website:"Sito web",professional:"Professionista",next:"Successivo >>",sex_male:"Maschio",personal_infos:"Dati personali",birth_year:"Anno di nascita *",limit_upload:"Max. 500KB",search:"Cerca",contact_required:"Nome e Cognome del contatto di riferimento *"},
step2:{ability1:"Debuttante",minor_sports:"Altri sport",your_sports:"I tuoi sport",previous:"<< Precedente",ability2:"Amatore",your_sports_warning:"Per favore, inserisci almeno uno sport!",ability3:"Esperto",anytime:"Sempre!",from:"Dalle ore",days:"Giorni",ability4:"Agonista",special_sports_hint:"Gli sport speciali sono gli sport praticabili anche da sportivi diversamente abili.",hour:"Ora",to:"Alle ore",your_ability_level:"Il tuo livello di abilit\u00e0 in questo sport:",main_sports:"Sport pi\u00f9 selezionati",
max_500_chars:"max 500 caratteri",save:"Salva",describe_record:"Descrivi il tuo livello e racconta un record:",add_day_hour:"Aggiungi un giorno/orario",your_sports_hint:'Seleziona gli sport che pratichi pi\u00f9 o meno abitualmente e specifica il tuo livello di abilit\u00e0. La lista viola indica gli sport pi\u00f9 praticati. Se non trovi lo sport che pratichi in questa lista, clicca su "Altri sport": troverai 300 sport tra cui scegliere! <strong>Per completare correttamente la registrazione devi selezionare almeno uno sport.</strong>',
next:"Successivo >>",days_hours_for_sport:"Giorni e orari in cui vorresti praticare questo sport:",special_sports:"Special sport"}},homepage:{social_video_head:"Il social network dedicato allo sport",social_video_descr:"30 secondi per scoprire cos'\u00e8 e come funziona We-Sport",banner:{popup5:"Sono un istruttore di sub. Non avrei mai pensato che nella mia citt\u00e0 ci fossero cos\u00ec tanti appassionati di diving e immersioni. Con We-Sport organizzare le mie lezioni \u00e8 diventato un gioco da ragazzi!",
popup6:"Alle 19.30 vado a correre al Parco Sempione. Qualcuno si unisce?",popup1:"Mi sono trasferito e non potevo pi\u00f9 allenare la mia squadra. Grazie a We- Sport nella mia nuova citt\u00e0 ho incontrato un altro team da seguire.",popup2:"Poco tempo e orari imprevedibili! Con We- Sport posso organizzarmi anche all\u2019ultimo momento e non rinunciare a una partita last minute di squash.",popup3:"Sono un massaggiatore sportivo e con We-Sport posso ampliare la mia clientela e rispondere a eventuali domande relative al mio lavoro.",
popup4:"Erano mesi che cercavo di organizzare una partita di Beach Volley nel campo vicino a casa mia. Finalmente ce l\u2019ho fatta!"},signup:{invalid_email:"Errore: l'indirizzo email \u00e8 invalido. Riprovare.",change_password:"Password modificata. Email di conferma inviata.",bad_password:"La password deve contenere almeno 5 caratteri.",accept_tos_error:"Devi accettare le condizioni d'uso e l'informativa sulla privacy prima di proseguire",help:"Sei uno SPORTIVO e desideri contattare altri sportivi vicino a te, partecipare a eventi e lanciare sfide? Oppure sei un PRO, ovvero un'associazione, una struttura, una federazione sportiva, un'azienda o un professionista che pu\u00f2 dare aiuto per svolgere nel migliore dei modi l'attivit\u00e0 fisica degli sportivi? Registrati qui!",
equal_passwords:'Il campo "ripeti password" non coincide col campo password!',insert_password:"Per favore, inserisci la password",valid_email:"E' necessario inserire un campo email valido!",accept_tos:"E' necessario accettare le <a href='#/tos' target='_blank'>condizioni d'uso</a> e l'<a href='#/privacy' target='_blank'>informativa sulla privacy</a> per procedere",register_here:"REGISTRATI QUI:",signup:"Registrati!",email_required:"e-mail (richiesta)",password_required:"password (richiesta)",still_not_registered:"SEI UNO SPORTIVO O UN PRO E NON SEI ANCORA REGISTRATO?",
general_error:"Errore nella registrazione [Dettaglio errore: {{status_detail}}]",repeat_password:"ripeti password",existing_email:"Errore: \u00e8 gi\u00e0 stata effettuata una registrazione con questa email!"},view_archive:"Consulta l'archivio"},global:{geocode_fail:"Indirizzo non trovato/riconosciuto!",new_login_required:"Attenzione: devi effettuare nuovamente il login",cancel:"Annulla",month:"Mese",pro:{company:"Azienda",votes:"{{count}} ({{total}} voti)",request_friendship:"Richiedi amicizia!",
structure:"Sport Sociale",association:"Associazione",federation:"Federazione sportiva",not_existing:"Il PRO selezionato non esiste pi\u00f9.",reject_friendship:"Revoca amicizia!",professional:"Professionista",detail:"Dettagli",distance:"Distante: {{distance}}"},ie7warning:"Gentile utente, abbiamo notato che stai utilizzando Internet Explorer 7 come browser per la navigazione. Ti avvertiamo che la tecnologia di questo browser \u00e8 superata e potrebbe essere causa di malfunzionamenti durante l'utilizzo di We-Sport. Per evitare fastidiosi inconvenienti ti suggeriamo di aggiornare il tuo browser <a href='http://windows.microsoft.com/it-IT/internet-explorer/downloads/ie-8' target='_blank'>qui</a>.",
days:{day0:"Luned\u00ec",day1:"Luned\u00ec",day2:"Marted\u00ec",day3:"Mercoled\u00ec",day4:"Gioved\u00ec",day5:"Venerd\u00ec",day6:"Sabato",day7:"Domenica"},nav:{back:"Indietro",previous:"Precedente",forward:"Avanti",select_all:"Seleziona tutti",next:"Successivo"},schedule:{errors:{time:"{{time}} non \u00e8 un'ora valida."}},not_logged_in:"Devi fare il login per visualizzare questa pagina",signup:{back:"indietro",modify_password:"modifica password",confirm_delete:"Sei sicuro di voler cancellare il tuo account?",
messages:{changed_password:"Password modificata!",min_one_service:"Per proseguire \u00e8 necessario inserire almeno un servizio.",success:"Iscrizione avvenuta! Controlla il tuo indirizzo di posta e segui il link presente nel messaggio che ti abbiamo inviato.",min_one_sport:"Prima di proseguire, \u00e8 necessario specificare almeno uno sport.",changed_notifications:"Preferenze notifiche modificate!",min_one_association_between_places_and_services:"Per proseguire \u00e8 necessario aver associato almeno un luogo ad un tuo servizio."},
errors:{invalid_time_range:"L'intervallo di tempo {{start}}-{{end}} non \u00e8 valido."},delete_account:"cancella account",notifications:"notifiche"},loading:"Caricamento in corso...",event:{messages:{declined:"L'evento \u00e8 stato rifiutato.",reminder_sent:"E' stato inviato un sollecito!",accepted:"Hai accettato di partecipare all'evento!"},edit:"Modifica",confirm_delete:"Sei sicuro di voler eliminare questo evento?","public":"Evento pubblico",partecipating:"Partecipa all'evento!","private":"Evento privato",
not_existing:"L'evento selezionato non esiste pi\u00f9.",closed:"Evento chiuso",invited_public:"E' invitato",not_partecipating:"Non partecipa all'evento",errors:{name:"Per favore, specifica il nome dell'evento.",address:"Per favore, specifica un'indirizzo corretto per l'evento.",notify:"Per favore, specifica se ti interessa essere avvertito quando viene raggiunto il numero minimo di partecipanti per creare le squadre.","private":"Per favore, specifica se l'evento \u00e8 pubblico o privato.",max:"Per favore, inserisci il numero di giocatori massimi richiesti.",
marker:"Per favore, inserisci un marker nella mappa per segnalare la posizione dell'evento.",min_max:"Il numero di giocatori minimi supera il numero di giocatori massimi richiesti.",date:"Per favore, specifica una data corretta per l'evento.",min:"Per favore, inserisci il numero di giocatori minimi richiesti.",sport:"Lo sport relativo all'evento non \u00e8 stato selezionato!"},missing_count:{one:"Manca ancora uno sportivo!",other:"Mancano {{count}} sportivi!",zero:"Evento completo"},partecipants:"Min: {{min}} - Max: {{max}}",
cancel_partecipation:"Annulla partecipazione?",waiting_for_acceptation_public:"In attesa di approvazione",created_by_prefix:"Creato da: ",created_by:"Creato da {{creator}}",waiting_for_acceptation:"In attesa di accettazione, vuoi declinare?",want_to_partecipate:"Vuoi partecipare?",delete_success:"L'evento \u00e8 stato eliminato!",reminder_sent:"E' stato inviato un sollecito!",detail:"Dettagli evento",confirmed_count:{one:"1 confermato",other:"{{count}} confermati",zero:"Nessuna conferma"},no_description:"Nessuna descrizione",
invited:"Invitato, vuoi partecipare?",distance:"Distante: {{distance}}",you_created:"Hai creato questo evento."},year:"Anno",months:{month10:"Ottobre",month6:"Giugno",month7:"Luglio",month11:"Novembre",month8:"Agosto",month12:"Dicembre",month9:"Settembre",month0:"Gennaio",month1:"Gennaio",month2:"Febbraio",month3:"Marzo",month4:"Aprile",month5:"Maggio"},place_sport:{errors:{days:"Per favore, specifica i giorni in cui si pu\u00f2 praticare lo sport.",hours:"Per favore, specifica gli orari in cui si pu\u00f2 praticare lo sport.",
costs:"Per favore, specifica i costi che si applicano a questo sport."}},connection_error:"Errore di comunicazione col server. Preghiamo di riprovare pi\u00f9 tardi.",message:{errors:{message:"Per favore, specifica il contenuto del messaggio."}},user:{votes:"{{count}} ({{total}} voti)",messages:{friendship_declined:"Hai rifiutato la richiesta di amicizia!",friendship_accepted:"Hai accettato la richiesta di amicizia!"},request_friendship:"Richiedi amicizia!",friendship_requested:"Hai richiesto l'amicizia con successo!",
details:"Dettaglio",female:"donna",not_existing:"L'utente selezionato non esiste pi\u00f9.",errors:{address:"Per favore, inserisci un indirizzo principale.",business_name:"Per favore, inserisci il tuo nome PRO, senza caratteri speciali.",marker:"Per favore, inserisci un marker nella mappa per segnalare il tuo indirizzo principale.",contact:"Per favore, inserisci il tuo contatto di riferimento.",last_name:"Per favore, inserisci il tuo cognome, senza caratteri speciali.",phone:"Per favore, inserisci il tuo numero di telefono.",
age:"Per favore, inserisci il tuo anno di nascita.",email:"Per favore, inserisci un'email.",first_name:"Per favore, inserisci il tuo nome, senza caratteri speciali."},reject_friendship:"Revoca amicizia!",friendship_rejected:"Hai annullato l'amicizia con successo!",male:"uomo",distance_short:"Distante: {{distance}}",age:"{{count}} anni",distance:"Distante: {{distance}}"},place:{votes:"{{count}} ({{total}} voti)",request_friendship:"Aggiungi alle preferite!",edit:"Modifica",friendship_requested:"Hai aggiunto la struttura alle preferite!",
abuse_reported:"I dati relativi a questa struttura sportiva sono in fase di verifica",not_existing:"La struttura selezionata non esiste pi\u00f9.",errors:{name:"Per favore, specifica il nome per la struttura.",address:"Per favore, specifica un'indirizzo testuale per la struttura.",marker:"Per favore, inserisci un marker nella mappa per segnalare la posizione della struttura.",min_one_place_sport:"Per favore, specifica almeno uno sport praticato nella struttura.",description:"Per favore, specifica una descrizione della struttura."},
reject_friendship:"Elimina dalle preferite!",friendship_rejected:"Hai eliminato la struttura dalle preferite!",detail:"Dettagli struttura",distance:"Distante: {{distance}}"}},pros:{locations_hint:"Ricerca PRO vicini ad un luogo!",been:"__",structures:"Sport Sociale",invite:"Invita amici",search_category:"Cerca PRO per categoria!",pro_categories:"Categorie",federations:"Federazioni sportive",search_pro_hint:"Ricerca PRO per nome!",search_pro:"Nome",professionals:"Professionisti",companies:"Aziende",
favorites:"Preferiti",all_categories:"Tutte",search_service:"Servizio",show:{no_photos:"Non ci sono foto.",friends:"Amici",add_a_photo:"Aggiungi una foto!",comments:"Commenti",no_videos:"Non ci sono video.","private":"Privato",upload:"Upload",photos:"Foto",no_events:"Non sono presenti eventi.",videos:"Video",send_message:"Invia",events:"Eventi",no_friends:"Non ci sono ancora amici.",remove:"Rimuovi",stars_count:"Feedback: {{count}}",youtube_hint:"Inserisci un qualsiasi indirizzo di video YouTube o Vimeo, verr\u00e0 mostrato direttamente nel tuo profilo.",
save:"Salva",feedback:"Esprimi un feedback sul PRO:",locations:"Luogo",sports_associated:"Sport associati",services:"Servizi",no_services:"Il PRO non offre alcun servizio.",add_a_video:"Aggiungi un video!",youtube_url:"YouTube o Vimeo URL"},locations:"Luogo",sport:"Sport",sport_hint:"Ricerca PRO in base allo sport!",associations:"Associazioni",nearby:"Vicini",search:"Cerca",search_service_hint:"Ricerca PRO in base al servizio fornito!"},users:{locations_hint:"Cerca sportivi vicini ad un luogo!",users_hint:"Cerca sportivi per nome!",
friends:"Amici",invite:"Invita un amico",no_results:"Non ci sono risultati per questa ricerca.",show:{no_sports:"L'utente non pratica alcuno sport.",no_photos:"Non ci sono foto.",friends:"Amici",add_a_photo:"Aggiungi una foto!",comments:"Commenti",no_videos:"Non ci sono video.",anytime:"In qualsiasi giorno/orario","private":"Privato",upload:"Upload",photos:"Foto",no_events:"Non sono presenti eventi.",videos:"Video",send_message:"Invia",events:"Eventi",no_friends:"Non ci sono ancora amici.",remove:"Rimuovi",
save:"Salva",youtube_hint:"Inserisci un qualsiasi indirizzo di video YouTube o Vimeo, verr\u00e0 mostrato direttamente nel tuo profilo.",add_a_video:"Aggiungi un video!",sports:"Sport",youtube_url:"YouTube o Vimeo URL"},locations:"Luogo",users:"Sportivi",sport:"Sport",sport_hint:"Cerca sportivi in base allo sport praticato!",nearby:"Vicini",search:"Cerca"},abuse:{post:"Invia segnalazione di abuso",warning_hint:"Stai per inviare una richiesta di eliminazione della struttura.",max_500_chars:"max 500 caratteri",
success:"La tua segnalazione \u00e8 stata inviata!",warning:"Attenzione!",post_abuse:"Segnala abuso",insert_motivation:"Inserisci una breve motivazione"},tab:{pro:"PRO",eventi:"Eventi",strutture:"Strutture",sponsor:"Milk & Smile",sportivi:"Sportivi"}},en:{messages:{"delete":"Delete","public":"Public",reply:"Reply","private":"Private",send:"Send"},places:{"new":{photo:"Picture",add:"Add!",my_sports:"Sports you can practice here: *",create_place_hint:"Do you know a public or private sport facility and do you want to share it with other members of We-Sport? Complete data as completely as possible so that everyone can see it on the map correctly. (Remember that all sport facilities are subject to abuse reports from We-Sport users: please do not enter sport facilities with non-existent or inappropriate data. Corrective action will be taken on potential abuses.)",
set:"Search",costs_required:"Costs",hours_required:"Hours",place_description_required:"Sport facility description *",mail:"Email Address",max_500_chars:"max 500 characters",address_hint:"Enter the address (once entered you can move the marker to the exact position where the sport facility is located): *",save:"Save",website:"Website",phone:"Phone Number",place_name_required:"Sport facility name *",edit_place:"Modify a sport facility",create_place:"Create a new sport facility",days_required:"Days",
sport_hint:"Enter the days, times and costs of the sport practiced in this sport facility:",special_sports:"Special Sports",sport:"Sport"},locations_hint:"Search events by address!",been:"Where have you been",search_places:"Sport facility",search_places_hint:"Search sport facility by name!",favorites:"Favorite",show:{flag3:"Payment",no_sports:"__",no_photos:"There are no photos.",back:"Back",flag4:"Free",friends:"Connected to the sport facility",edit:"Edit",flag5:"Qualified personnel",add_a_photo:"Add a photo!",
comments:"Comments",no_videos:"There are no videos.",days:"Days",cleverness_count:"Cleverness: {{count}}","private":"Private",upload:"Upload",photos:"Photos",no_events:"There are no events.",videos:"Videos",send_message:"Send",events:"Events",no_friends:"There are no players connected.",quality_count:"Quality: {{count}}",stars_count:"Feedback: {{count}}",remove:"Remove",feedback:"Give a feedback on the sport facility:",youtube_hint:"Enter any YouTube or Vimeo videos url: the video will be displayed directly in your profile.",
save:"Save",new_event:"New event",costs:"Costs",hours:"Hours",flag1:"Indoor",add_a_video:"Add a video!",sports:"Sport",flag2:"Outdoors",reliability_count:"Reliability: {{count}}",youtube_url:"YouTube or Vimeo URL",abuse:"Report abuse"},locations:"Location",mine:"Created by me",sport:"Sport",sport_hint:"Search events by sport!",nearby:"Nearby",create_new:"New sport facility",search:"Search"},layout:{otherwise_login_with_social_networks:"or connect with",my_home:"Home",change_password:"Change password",
logout:"Logout",messages:{insert_email:"Error: please, enter your email address and try again.",forgot_password:{insert_email:"Error: please, enter your email address and try again.",new_password_was_sent:"A new password has been sent to your email address!",email_not_found:"Error: the email listed is not recorded on We-Sport!",error:"An error occurred during password recovery procedure: check that you correctly typed your email address, or try to log in through a social network present on the right. (Dettaglio errore: {{status_detail}})"},
login:{insert_email:"Error: please, enter your email address and try again.",insert_password:"Error: please, enter your password and try again.",username_or_password_invalid:"Error: email or password are incorrect!"}},forgot_your_password:"Forgot your password?",my_profile:"Profile",welcome:"We-Sport welcomes you to join the community dedicated to sports where you can choose from more than 300 sports and find new and old friends to play with. Lets begin: by entering your data and the name of a city you will find athletes and sporting events nearby the location you entered.",
inbox:{one:"Inbox (1)",other:"Inbox ({{count}})",zero:"Inbox"},settings:"Settings",stay_logged_in:"Keep me logged in",login:"Login",password:"Password",email:"Email"},"static":{contact_us_title:"Contact Us",privacy_title:"Privacy Policy",news_title:"News",press:{view_article:"Go to the article"},news:{news6_text_long:"<p>Preliminary evidence suggests that meditative exercise may have benefits for patients with chronic systolic heart failure (HF); this has not been rigorously tested in a large clinical sample. We sought to investigate whether tai chi, as an adjunct to standard care, improves functional capacity and quality of life in patients with HF.</p> <p>A single-blind, multisite, parallel-group, randomized controlled trial evaluated 100 outpatients with systolic HF (New York Heart Association class I-III, left ventricular ejection fraction \u226440%) who were recruited between May 1, 2005, and September 30, 2008. A group-based 12-week tai chi exercise program (n = 50) or time-matched education (n = 50, control group) was conducted. Outcome measures included exercise capacity (6- minute walk test and peak oxygen uptake) and disease-specific quality of life (Minnesota Living With Heart Failure Questionnaire).</p> <p>Mean (SD) age of patients was 67 (11) years; baseline values were left ventricular ejection fraction, 29% (8%) and peak oxygen uptake, 13.5 mL/kg/min; the median New York Heart Association class of HF was class II. At completion of the study, there were no significant differences in change in 6-minute walk distance and peak oxygen uptake (median change [first quartile, third quartile], 35 [\u20132, 51] vs 2 [\u20137, 54] meters, P = .95; and 1.1 [\u20131.1, 1.5] vs \u20130.5 [\u20131.2, 1.8] mL/kg/min, P = .81) when comparing tai chi and control groups; however, patients in the tai chi group had greater improvements in quality of life (Minnesota Living With Heart Failure Questionnaire, \u201319 [\u201323, \u20133] vs 1 [\u201316, 3], P = .02). Improvements with tai chi were also seen in exercise self-efficacy (Cardiac Exercise Self-efficacy Instrument, 0.1 [0.1, 0.6] vs \u20130.3 [\u20130.5, 0.2], P < .001) and mood (Profile of Mood States total mood disturbance, \u20136 [\u201317, 1] vs \u20131 [\u201313, 10], P = .01).</p> <p>Tai chi exercise may improve quality of life, mood, and exercise self-efficacy in patients with HF.</p> <p><a target='_blank' href=\"http://archinte.ama-assn.org/cgi/content/abstract/171/8/750\">http://archinte.ama-assn.org/cgi/content/abstract/171/8/750</a></p>",
news6_text:"Preliminary evidence suggests that meditative exercise may have benefits for patients with chronic systolic heart failure (HF); this has not been rigorously tested in a large clinical sample. We sought to investigate whether tai chi... ",news6_date:"09/12/2011",news5_text:"Enhancement of lipoprotein lipase (LPL) activity through drug administration has been shown to increase pre-heparin serum LPL concentrations; however, pre-heparin serum LPL responses to exercise training have not been determined. The present study... ",
news5_date:"09/12/2011",news4_text:"Because excessive consumption of sugar-sweetened beverages may reduce the quality of nutritional intake, this study examined the consumption patterns of commercial beverages, lifestyle, dietary habits, and perception of sweet taste. Participants were 407 male university students in Kyeonggido, Korea, and information was collected by self-administered questionnaire.",news4_date:"05/01/2011",news3_text:"Few epidemiological studies have focused on the psychological health of high level athletes. This study aimed to identify the principal psychological problems encountered within French high level athletes, and the variations in their prevalence based on sex and the sport practiced.",
news2_text_long:"<p>The purpose of this study was to examine relationships between weather and outdoor physical activity (PA). An online weather source was used to obtain daily max temperature [DMT], precipitation, and wind speed. An infra-red trail counter provided data on daily trail use along a greenway, over a 2-year period. Multiple regression analysis was used to examine associations between PA and weather, while controlling for day of the week and month of the year. The overall regression model explained 77.0% of the variance in daily PA (p < 0.001). DMT (b = 10.5), max temp-squared (b = \u22124.0), precipitation (b = \u221270.0), and max wind speed (b = 1.9) contributed significantly. Conclusion: Aggregated daily data can detect relationships between weather and outdoor PA.</p>",
news1_text:"Few studies have investigated factors that influence physical activity behavior during the transition from adolescence to adulthood. This study explores the associations of sociodemographic, behavioral, sociocultural, attitudinal and physical factors measured in childhood and adolescence with physical activity behavior during the transition from adolescence to adulthood... ",news1_title:"Childhood and adolescent predictors of leisure time physical activity during the transition from adolescence to adulthood",
news3_date:"05/02/2011",news2_text:"The purpose of this study was to examine relationships between weather and outdoor physical activity (PA). An online weather source was used to obtain daily max temperature [DMT], precipitation, and wind speed. An infra-red trail counter provided data on daily trail use along a greenway, over a 2-year period... ",news2_title:"The Relationships between Weather-Related Factors and Daily Outdoor Physical Activity Counts on an Urban Greenway",news5_title:"Twelve-Week Jogging Training Increases Pre-Heparin Serum Lipoprotein Lipase Concentrations in Overweight/Obese Middle-Aged Men",
news3_title:"Psychological Balance in High Level Athletes: Gender-Based Differences and Sport-Specific Patterns",news2_date:"05/09/2011",news4_title:"Lifestyle, dietary habits and consumption pattern of male university students according to the frequency of commercial beverage consumptions",news3_text_long:"<p><strong>Objectives:</strong> Few epidemiological studies have focused on the psychological health of high level athletes. This study aimed to identify the principal psychological problems encountered within French high level athletes, and the variations in their prevalence based on sex and the sport practiced.</p> <p><strong>Methods:</strong> Multivariate analyses were conducted on nationwide data obtained from the athletes\u2019 yearly psychological evaluations.</p> <p><strong>Results:</strong> A representative sample of 13% of the French athlete population was obtained. 17% of athletes have at least one ongoing or recent disorder, generalized anxiety disorder (GAD) being the most prevalent (6%), followed by non-specific eating disorders (4.2%). Overall, 20.2% of women had at least one psychopathology, against 15.1% in men. This female predominance applied to anxiety and eating disorders, depression, sleep problems and self-harming behaviors. The highest rates of GAD appeared in aesthetic sports (16.7% vs. 6.8% in other sports for men and 38.9% vs. 10.3% for women); the lowest prevalence was found in high risk sports athletes (3.0% vs. 3.5%). Eating disorders are most common among women in racing sports (14% vs. 9%), but for men were found mostly in combat sports (7% vs. 4.8%).</p> <p><strong>Discussion:</strong> This study highlights important differences in psychopathology between male and female athletes, demonstrating that the many sex-based differences reported in the general population apply to elite athletes. While the prevalence of psychological problems is no higher than in the general population, the variations in psychopathology in different sports suggest that specific constraints could influence the development of some disorders.</p>",
news1_text_long:"<p>Few studies have investigated factors that influence physical activity behavior during the transition from adolescence to adulthood. This study explores the associations of sociodemographic, behavioral, sociocultural, attitudinal and physical factors measured in childhood and adolescence with physical activity behavior during the transition from adolescence to adulthood.</p>",news1_date:"05/05/2011",news5_text_long:"<p>Enhancement of lipoprotein lipase (LPL) activity through drug administration has been shown to increase pre-heparin serum LPL concentrations; however, pre-heparin serum LPL responses to exercise training have not been determined. The present study was undertaken to investigate the effects of 12 weeks of supervised aerobic exercise training on pre-heparin serum LPL concentrations in overweight/obese men.</p> <p>Fifteen overweight/obese middle-aged men were assigned to one of two 12-week supervised exercise interventions: a walking group (eight participants gradually increasing brisk walking to 60 min/day 3 days a week) or a jogging group (seven participants gradually increasing jogging to 60 min/day 3 days a week). All participants maintained ad libitum diets. Blood samples were collected at baseline and immediately after 12 weeks. The primary outcome was pre-heparin serum LPL.</p> <p>Pre-heparin serum LPL concentrations were increased in the jogging group after 12 weeks compared with the baseline values (mean\u00b1SEM: 37.6\u00b14.7 vs. 51.0\u00b16.6 ng/mL, respectively, p = 0.033). In the walking group, pre-heparin serum LPL concentrations remained unchanged after 12 weeks.</p> <p>This study demonstrates that 12 weeks of jogging training increases pre-heparin serum LPL concentrations in overweight/obese middle-aged men.</p> <p><a target='_blank' href=\"http://www.ncbi.nlm.nih.gov/pubmed/20075597\">http://www.ncbi.nlm.nih.gov/pubmed/20075597</a></p>",
news4_text_long:"<p>Because excessive consumption of sugar-sweetened beverages may reduce the quality of nutritional intake, this study examined the consumption patterns of commercial beverages, lifestyle, dietary habits, and perception of sweet taste. Participants were 407 male university students in Kyeonggido, Korea, and information was collected by self-administered questionnaire. Among them, 58 nonsmokers volunteered to participate in the taste test. Participants were divided into three groups according to the frequency of commercial beverage consumptions: 120 rare (< 1 serving/week), 227 moderate (1-3 servings/week) and 133 frequent (> 3 servings/week) consumption groups. More subjects from the rare consumption group chose water, tea, and soy milk, and more from the frequent consumption group chose carbonated soft drinks and coffee (P = 0.031) as their favorite drinks. Frequent consumption group consumed fruit juice, coffee, and sports and carbonated soft drinks significantly more often (P = 0.002, P = 0.000, P = 0.000, respectively), but not milk and tea. Frequent consumption group consumed beverages casually without a specific occasion (P = 0.000) than rare consumption group. Frequent drinking of commercial beverages was associated with frequent snacking (P = 0.002), meal skipping (P = 0.006), eating out (P = 0.003), eating delivered foods (P = 0.000), processed foods (P = 0.001), and sweets (P = 0.002), and drinking alcoholic beverages (P = 0.029). Frequent consumption group tended to have a higher threshold of sweet taste without reaching statistical significance. The results provide information for developing strategies for evidence-based nutrition education program focusing on reducing consumption of unnecessary sugar-sweetened commercial beverages.</p>",
download_pdf:"Download PDF",news6_title:"Tai Chi Exercise in Patients With Chronic Heart Failure",more:"More",search:"Search"},tos_title:"Terms of Service",sponsor_title:"Sponsor",press_title:"Press"},events:{"new":{modified:"The event has been successfully modified!",friends:"Friends",users_hint:"Click on athletes you want to invite:",waiting:"Waiting for reply","public":"public",reached_max:"* The minimum number of participants has been reached.",event_description:"Event description",required_fields:"* Required fields",
"private":"private",select_location:"Change the location by selecting one of your locations:",max:"max *",partecipants:"Participants ",hour:"Time *",other_users:"Click on athletes you want to invite:",declined:"Non-participating",sn:"Social Network",event_name:"Event name *",date:"Date *",create_event:"Create event",edit_event:"Edit event",recall_tip:"Recall last event",selected_users:"Selected athletes:",other_emails:"Other athletes email (comma separated)",max_500_chars:"max 500 characters",save:"Save",
resend_message:"Send a reminder email to this athletes!",notify_me:"Notify me when it reaches the minimum number of participants",address_hint:"Enter the meeting place where you will practice the activity: *",min:"min *",general_infos:"General infos",users:"Athletes",create_event_hint:"Create a sporting event, a match or a training session. Enter the required information:",message:"Enter a personal message (optional):",nearby:"Nearby",invited:"Invited athletes",sport:"Sport *",event_type:"Event type *",
recall:"Recall",created:"The event has been successfully created!",create_teams:"Create teams (optional) *",search:"Search",edit_event_hint:"Edit the sporting event, match or training session you've created:"},locations_hint:"Search events by address!",invites:"Invitations",events:"Eventi",events_hint:"Search events by name!",show:{waiting_for_confirmation:"Waiting for confirmation",edit:"Edit","delete":"Delete",comments:"Comments",declined_partecipants:"Declined partecipants",partecipants:"Participants",
waiting_for_acceptation:"Waiting for acceptation",send:"Send"},locations:"Location",sport:"Sport",sport_hint:"Search events by sport!",nearby:"Nearby",create_new:"Create a event",search:"Search",created:"Created by me"},inbox:{wall_message:{title:"{{name}} writes you:",reply_here:"Reply here:",sent_success:"Reply sent successfully!",send:"Send!"},no_message:"No messages",new_pro_message:{location:"Location",intro:"Use this tool for providing information about services you offer. You can reach not only athletes, but also the PROs.",
pro:"Pro",send_message:"Send!",max_500_chars:"max 500 characters",users:"Athletes",block_pro:"This PRO has been blocked",write_message:"Write the message to send:",sport:"Sport",button_label:"New PRO message"},event_message:{title:"{{name}} wrote a message in the event {{event}}:"},friendship_request:{title:"{{name}} has asked your friendship:"},show_more:"Show more",mark_as_read:'Mark as "read"',invite_event:{title:"{{name}} has invited you to the event {{event}}:",declined:"You have declined the invitation to the event.",
accepted:"You have accepted the invitation to the event!"},request_partecipation_event:{title:"{{name}} wants to attend the event {{event}}:",declined:"You have declined the request for participation in the event.",accepted:"You have accepted the request for participation in this event!"},event_feedback:{given_feedback:"You've given a rating of {{feedback}}!",vote:"Vote!",title:"Event {{event}}:",message:"Give us your feedback on the participants and the structure!"}},settings:{step3:{add:"Add",associated_sports_for_place:"Sport you play here",
previous:"<< Previous",your_places:"Your locations",your_main_place:"Your main location",show_my_position:"View my position on the map!",my_sports_for_place:"Sport you play",save:"Save",your_places_hint:"Select all locations where you use to play sport and link them together. This will make easier to find other athletes who share your same interests on We-Sport ... right nearby to you! If you want you can complete this step and modify all the data at a later time by clicking on 'settings' menu.",
address_hint:"Enter the address of a place where you play sport:",sports_for_place:"Click on sports you play in this location:",all_sports:"Link all",other_places:"Your other locations",search:"Search"},step2_pro:{service_sports_error:"Please enter at least one sport for the service.",minor_sports:"Other sports",associated_sports_for_place:"Sports connected with the service",edit:"Edit",previous:"<< Previous","delete":"Delete",click_to_add_service:"Click here to add a new service!",your_services:"Your services",
other_services:"Your other services",main_sports:"Most selected sports",find_service:"Search your service or product in the existing ones, or enter a new one!",save:"Save",general_description:"Enter a general description (max 500 characters)",next:"Next >>",special_sports:"Special sports",choose_sports_for_service:"Offer this service for the following sports:",service_placeholder:"Name of the service or product...",your_main_service:"Your main service",service_name_error:"Please, specify the name of the service.",
your_services_hint:"Specifies the services you can offer to We-Sport users. Be as detailed as possible in linking sports to your services and in describing them so it's easy to find you with the appropriate search tools (for services we don't mean the sport or sports you care, but the services you offer your customers or members). To successfully complete registration you must specify at least one service."},change_pass:{title:"Change password",change:"Change",new_password:"New password:",hint:"Enter your old password and the new one:",
repeat_password:"Repeat new password:",old_password:"Old password:"},step3_pro:{previous:"<< Previous",main_place:"Your main location",add:"Add",edit:"Edit",associated_services:"Services you offer here",your_places:"Your locations",show_my_position:"View my position on the map!",services_for_place:"Click on the services you offer in this place:",save:"Save",address_hint:"Enter the address of a place where you offer your service:",your_places_hint:"Do you own or manage many sport facilities? Do you practice often your business in a certain location? Do you have more a lot of selling point? In this section you can mention these locations.",
all_services:"Link all",services:"Your services",other_places:"Your other locations"},step0:{login_as_user:"Log on as ATHLETE",pro:"PRO?",login_as_pro:"Log on as a PRO",pro_hint:"Register here if you are a sports association, facility, federation, a corporation or a professional who can give help for athletes. If you're not a PRO, sign up as an ATHLETE.",user_hint:"Register here to create a profile as ATHLETE and be able to contact other athletes close to you, attend events and launch challenges!",
user:"ATHLETE?"},notifications:{event_message:"When a message is written on the page of an event to which I was invited.",title:"Notifications",friendship_request:"When a friendship request is received.",change:"Change",event_invite:"When I am invited to an event.",statement:"Send me an e-mail:",hint:"Here you can select which modifications you wish to receive on your e-mail:",we_sport_news:"When there are news from the We-Sport Team.",profile_message:"When a message is written to my profile.",confirm_friendship_request:"When a friendship request is accepted."},
step1:{address_hint_pro:"Enter your main address (once entered you can move the marker to the exact point your office or sport facility is located in): *",phone_required:"Phone number to display *",company:"Corporation",info_mail:"Email to display",structure:"Social sport",association:"Sport association",last_name_required:"Surname *",upload_error:"The maximum photo size must be 500Kb and the format must be JPG or PNG",sex_required:"Sex *",first_name_required:"Name *",info_mail_required:"Email *",
federation:"Sport federation",pro_name_required:"PRO Official Name *",required_fields:"* Required field",sex_female:"Female",upload:"Upload",choose_photo:"Choose photo",infos_hint:"Enter your information in order to find athletes suitable to your level and practicing sports in your own area.",show_my_position:"View my position on the map!",email_required:"Email *",profession_required:"Category *",address_hint:"Enter the address where you practice sports (once entered the address you can move the marker to the exact location you want): *",
website:"Sito web",professional:"Professional",next:"Next >>",sex_male:"Male",personal_infos:"personal details",birth_year:"Year of birth *",limit_upload:"Max. 500KB",search:"Search",contact_required:"Full name of contact person *"},step2:{ability1:"Beginner",minor_sports:"Other sports",your_sports:"Your sports",previous:"<< Previous",ability2:"Amateur",your_sports_warning:"Please, enter at least one sport!",ability3:"Semi-pro",anytime:"Always!",from:"From",days:"Day",ability4:"Professional",special_sports_hint:"Special sports are sports practiced also by athletes with disabilities.",
hour:"Time",to:"To",your_ability_level:"Your skill level in this sport:",main_sports:"Most selected sports",max_500_chars:"max 500 characters",save:"Save",describe_record:"Describe your level and tell us a record:",add_day_hour:"Add a day/time",your_sports_hint:'Select sports that you use to play and your specific skill level. The purple list indicates the most popular sports. If you can not find the sport that you practice on this list, click on "Other sports": you will find 300 sports to choose from! <strong>To successfully complete registration you must select at least one sport.</strong>',
next:"Next >>",days_hours_for_sport:"Days and times to practice this sport:",special_sports:"Special sports"}},homepage:{social_video_head:"The social network for people playing sport",social_video_descr:'30" to discover how We-Sport works and what it is',banner:{popup5:"I am a scuba instructor. I would never have thought there were so many fans of diving in my city. With We-Sport I can easily organize my classes!",popup6:"At 7:30 I'm going jogging in Hide Park. Anyone want to join?",popup1:"I moved and I could not train my team anymore. Thanks to We-Sport, I've been able to find another team in my new city.",
popup2:"Little spare time and unpredictable daily schedules! With We-Sport I can make plan at the last second, without dropping out of a last-minute squash game.",popup3:"I am an expert massage therapist, and with We-Sport I can meet new costumers and answer any possible questions relating to my job.",popup4:"For months, I've been trying to organize a Beach Volley game in the field next to my house. Finally I did it!"},signup:{invalid_email:"Error: email is invalid. Retry.",change_password:"Password changed. Email confirmation sent.",
bad_password:"Password must have at least 5 characters.",accept_tos_error:"You need to accept Terms of Services and Privacy Policy before procedeing",help:"Are you an athlete and want to contact other athletes, attend events and launch challenges? Or you're a PRO, a sports association, facility, federation, a corporation or a professional who can give help for athletes? Sign up here!",equal_passwords:"Password and repeat password are different!",insert_password:"Please, insert password",valid_email:"Insert a valid email!",
accept_tos:"Accept <a href='#/tos' target='_blank'>Terms of Service</a> and <a href='#/privacy' target='_blank'>Privacy Policy</a> before procedeing",register_here:"SIGN UP HERE:",signup:"Sign up!",email_required:"e-mail (required)",password_required:"password (required)",still_not_registered:"ARE YOU AN ATHLETE OR A PRO NOT YET REGISTERED?",general_error:"Error during registration [Error detail: {{status_detail}}]",repeat_password:"repeat password",existing_email:"Error: email has already been used to register!"},
view_archive:"View all"},global:{geocode_fail:"Address not found/recognized!",new_login_required:"Attention: a new login is required",cancel:"Cancel",month:"Month",pro:{company:"Corporation",votes:"{{count}} ({{total}} votes)",request_friendship:"Ask for friendship!",structure:"Social sport",association:"Sport association",federation:"Sport federation",not_existing:"The PRO you have selected doesn't exist any more.",reject_friendship:"Revoke friendship!",professional:"Professional",detail:"Details",
distance:"Far away: {{distance}}"},ie7warning:"Dear User, we noticed that you're using Internet Explorer 7 browser for navigation. This browser is outdated and could be due to malfunction during the use of We-Sport. To avoid annoying problems we suggest you to upgrade your browser <a href='http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8' target='_blank'>here</a>.",days:{day0:"Monday",day1:"Monday",day2:"Tuesday",day3:"Wednesday",day4:"Thursday",day5:"Friday",day6:"Saturday",day7:"Sunday"},
nav:{back:"Back",previous:"Previous",forward:"Forward",select_all:"Select all",next:"Next"},schedule:{errors:{time:"{{time}} is not a valid time."}},not_logged_in:"You have to login to visualize this page",signup:{back:"back",modify_password:"modify password",confirm_delete:"Are you sure you want to delete your account?",messages:{changed_password:"Your password has been changed!",min_one_service:"Please, enter at least one service.",success:"You're in! Check your email and follow the link in the message we sent you.",
min_one_sport:"Please, enter at least one sport.",changed_notifications:"Your notifications preferences have been changed!",min_one_association_between_places_and_services:"To continue you must have associated at least one service to one place."},errors:{invalid_time_range:"Time {{start}}-{{end}} isn't valid."},delete_account:"delete account",notifications:"notifications"},loading:"Loading ...",event:{messages:{declined:"The event was successfully rejected!",reminder_sent:"A reminder was sent successfully!",
accepted:"You attend the event!"},edit:"Modify",confirm_delete:"Are you sure you want to delete this event?","public":"Public event",partecipating:"Is attending the event!","private":"Private event",not_existing:"The event you have selected doesn't exist any more.",closed:"Event closed",invited_public:"Is invited",not_partecipating:"Is not attending the event",errors:{name:"Please, specify the name of the event.",address:"Please, specify a correct address for the event.",notify:"Please, specify if you are interested to be alerted when the event reaches the minimum number of participants to create teams.",
"private":"Please, specify whether an event is public or private.",max:"Please, enter the maximum number of players required.",marker:"Please, enter a marker on the map to indicate the location of the event.",min_max:"The minimum number of players exceeds the maximum number of players required.",date:"Please, specify a correct date for the event.",min:"Please, enter the minimum number of players required.",sport:"Please, specify the sport for the event."},missing_count:{one:"We still lack a player!",
other:"Lack {{count}} player!",zero:"Event complete"},partecipants:"Min: {{min}} - Max: {{max}}",cancel_partecipation:"Decline your participation?",waiting_for_acceptation_public:"Is waiting for acceptation",created_by_prefix:"Created by: ",created_by:"Created by: {{creator}}",waiting_for_acceptation:"Pending acceptance, want to decline?",want_to_partecipate:"Want to join?",delete_success:"The event has been deleted!",reminder_sent:"A reminder was sent successfully!",detail:"Event details",confirmed_count:{one:"1 confirmed",
other:"{{count}} confirmed",zero:"No one confirmed"},no_description:"No description",invited:"Invited, want to participate?",distance:"Far away: {{distance}}",you_created:"You have created this event."},year:"Year",months:{month10:"October",month6:"June",month7:"July",month11:"November",month8:"August",month12:"December",month9:"September",month0:"January",month1:"January",month2:"February",month3:"March",month4:"April",month5:"May"},place_sport:{errors:{days:"Please, specify the days you can play this sport.",
hours:"Please, specify the times when you can play this sport.",costs:"Please, specify the costs that apply to this sport."}},connection_error:"Error communicating with server. Please try again later.",message:{errors:{message:"Please, specify the content of the message."}},user:{votes:"{{count}} ({{total}} votes)",messages:{friendship_declined:"You have rejected the friendship request!",friendship_accepted:"You have accepted the friendship request!"},request_friendship:"Ask for friendship!",friendship_requested:"You asked for friendship successfully!",
details:"Details",female:"female",not_existing:"The user you have selected doesn't exist any more.",errors:{address:"Please, enter a primary address.",business_name:"Please, enter your name PRO, without using special characters.",marker:"Please, enter a marker on the map to indicate your primary address.",contact:"Please, enter your contact person.",last_name:"Please, enter your surname, without using special characters.",phone:"Please, enter your phone number.",age:"Please, enter your year of birth.",
email:"Please, enter an email.",first_name:"Please, enter your name, without using special characters."},reject_friendship:"Revoke friendship!",friendship_rejected:"You removed friendship successfully!",male:"male",distance_short:"Far away: {{distance}}",age:"{{count}} years old",distance:"Far away: {{distance}}"},place:{votes:"{{count}} ({{total}} votes)",request_friendship:"Add to favorite!",edit:"Edit",friendship_requested:"You have added this sport facility to your favorites",abuse_reported:"Data about this facility are in verification process.",
not_existing:"The place you have selected doesn't exist any more.",errors:{name:"Please, specify the sport facility name.",address:"Please, enter the address.",marker:"Please, enter a marker on the map to indicate the location of this sport facility.",min_one_place_sport:"Please specify at least one sport you can play in this sport facility.",description:"Please give us a sport facility description."},reject_friendship:"Delete from favorite!",friendship_rejected:"You have removed this sport facility from your favorites",
detail:"Sport facility details",distance:"Far away: {{distance}}"}},pros:{locations_hint:"Search PRO by address!",been:"__",structures:"Social sport",invite:"Invite a friend",search_category:"Search PRO by category!",pro_categories:"Category",federations:"Sport federations",search_pro_hint:"Search PRO by name!",search_pro:"Name",professionals:"Professionals",companies:"Corporations",favorites:"Favorites",all_categories:"All",search_service:"Service",show:{no_photos:"There are no photos.",friends:"Friends",
add_a_photo:"Add a photo!",comments:"Comments",no_videos:"There are no videos.","private":"Private",upload:"Upload",photos:"Photos",no_events:"There are no events.",videos:"Videos",send_message:"Send",events:"Events",no_friends:"There are no friends.",remove:"Remove",stars_count:"Feedback: {{count}}",youtube_hint:"Enter any YouTube or Vimeo videos url: the video will be displayed directly in your profile.",save:"Save",feedback:"Give a feedback on PRO:",locations:"Location",sports_associated:"Associated sport",
services:"Services",no_services:"The PRO doesn't offer any service.",add_a_video:"Add a video!",youtube_url:"YouTube o Vimeo URL"},locations:"Location",sport:"Sport",sport_hint:"Search PRO by sport!",associations:"Sport associations",nearby:"Nearby",search:"Search",search_service_hint:"Search PRO by service!"},users:{locations_hint:"Search athletes near a location!",users_hint:"Search athletes by name!",friends:"Friends",invite:"Invite a friend",no_results:"There are no results for this research.",
show:{no_sports:"User doesn't play any sport.",no_photos:"There are no photos.",friends:"Friends",add_a_photo:"Add a photo!",comments:"Posts",no_videos:"There are no videos.",anytime:"Anytime","private":"Private",upload:"Upload",photos:"Photos",no_events:"There are no events.",videos:"Videos",send_message:"Send",events:"Events",no_friends:"There are no friends.",remove:"Remove",youtube_hint:"Enter any YouTube or Vimeo videos url: the video will be displayed directly in your profile.",save:"Save",
add_a_video:"Add a video!",sports:"Sport",youtube_url:"YouTube or Vimeo URL"},locations:"Location",users:"Athletes",sport:"Sport",sport_hint:"Search athletes by sport!",nearby:"Nearby",search:"Search"},abuse:{post:"Send report abuse",warning_hint:"You are submitting a request for removing this structure.",max_500_chars:"max 500 characters",success:"Your report has been sent!",warning:"Warning!",post_abuse:"Report abuse",insert_motivation:"Enter a short justification"},tab:{pro:"PRO",eventi:"Events",
strutture:"Places",sponsor:"Milk & Smile",sportivi:"Athletes"}}};

var OldDateParse, Utils;

String.prototype.truncate = function(length, suffix) {
  length || (length = 50);
  suffix || (suffix = "...");
  if (this.length > length) {
    return this.slice(0, length - suffix.length) + suffix;
  } else {
    return this;
  }
};

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

String.prototype.strip = function() {
  var tmp;
  if (this.length === 0) {
    return "";
  } else {
    tmp = document.createElement("DIV");
    tmp.innerHTML = this;
    return tmp.textContent || tmp.innerText;
  }
};

String.prototype.escape = function() {
  return this.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g, '&#x2F;');
};

OldDateParse = Date.parse;

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(obj, start) {
    var i, j;
    i = start || 0;
    j = this.length;
    while (i < j) {
      if (this[i] === obj) return i;
      i++;
    }
    return -1;
  };
}

Date.parse = function(string) {
  var d, date, offset, regexp, regexp2, time, _ref;
  if (string instanceof Date) return string;
  regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
  d = string.match(new RegExp(regexp));
  offset = 0;
  if (d[0] && d[1] && d[2]) {
    offset = 0;
    date = new Date(d[1], 0, 1);
    if (d[3]) date.setMonth(d[3] - 1);
    if (d[5]) date.setDate(d[5]);
    if (d[7]) date.setHours(d[7]);
    if (d[8]) date.setMinutes(d[8]);
    if (d[10]) date.setSeconds(d[10]);
    if (d[12]) date.setMilliseconds(Number("0." + d[12]) * 1000);
    if (d[14]) {
      offset = (Number(d[16]) * 60) + Number(d[17]);
      offset *= (_ref = d[15] === '-') != null ? _ref : {
        1: -1
      };
    }
    offset -= date.getTimezoneOffset();
    time = Number(date) + (offset * 60 * 1000);
    date.setTime(Number(time));
  } else {
    regexp2 = "([0-9]{2})(\/([0-9]{2}))(\/([0-9]{4}))";
    d = string.match(new RegExp(regexp2));
    if (d[1] && d[3] && d[5]) {
      date = new Date();
      date.setDate(d[1]);
      date.setMonth(parseInt(d[3], 10) - 1);
      date.setYear(d[5]);
      offset = 0;
      if (!(date instanceof Date)) return string;
    }
  }
  return date;
};

Date.prototype.set_time_from_string = function(time) {
  var hours, minutes;
  time = time.match(/(\d+)(?::(\d\d))?\s*(p?)/i);
  if (!time) return false;
  hours = parseInt(time[1], 10);
  if (time[3].length > 0) hours += 12;
  minutes = parseInt(time[2], 10) || 0;
  this.setMinutes(minutes);
  this.setHours(hours);
  return this.setSeconds(0);
};

Number.prototype.meters = function() {
  if (this < 1000) {
    return Math.round(this) + " m";
  } else {
    return Math.round(this / 1000) + " km";
  }
};

Utils = {
  pad_time: function(time) {
    time = time + "";
    if (time.length === 1) {
      return "0" + time;
    } else {
      return time;
    }
  },
  pad_total_time: function(time) {
    var times;
    times = time.split(":");
    return "" + (Utils.pad_time(times[0])) + ":" + (Utils.pad_time(times[1]));
  },
  parse_time: function(time) {
    var hours, minutes;
    time = time.match(/(\d+)(?::(\d\d))?\s*(p?)/i);
    if (!time) return false;
    hours = parseInt(time[1], 10);
    if (time[3].length > 0) hours += 12;
    minutes = parseInt(time[2], 10) || 0;
    return "" + (Utils.pad_time(hours)) + ":" + (Utils.pad_time(minutes));
  },
  date_to_iso8601: function(d) {
    return d.getUTCFullYear() + '-' + Utils.pad_time(d.getUTCMonth() + 1) + '-' + Utils.pad_time(d.getUTCDate()) + 'T' + Utils.pad_time(d.getUTCHours()) + ':' + Utils.pad_time(d.getUTCMinutes()) + ':' + Utils.pad_time(d.getUTCSeconds()) + '.000Z';
  },
  is_id: function(s) {
    return (s != null) && (s.toString().search(/^[0-9]+$/ === 0)) && parseInt(s, 10) > 0;
  },
  is_unsigned_int: function(s) {
    return (s != null) && s.toString().search(/^[0-9]+$/) === 0;
  },
  is_number: function(o) {
    return typeof parseFloat(o) === 'number' && isFinite(parseFloat(o));
  },
  is_bool: function(s) {
    return typeof s === "boolean";
  },
  is_date: function(s) {
    return s instanceof Date || ((s != null) && Date.parse(s) instanceof Date);
  },
  is_time: function(s) {
    return (s != null) && s.toString().match(/^[0-9]{1,2}:[0-9]{1,2}/);
  },
  is_nonempty_string: function(s) {
    return typeof s === "string" && s.trim().length > 0;
  },
  is_name: function(s) {
    return Utils.is_nonempty_string(s) && !s.match(/[!"£$%()]/);
  },
  is_email: function(s) {
    return (s != null) && s.toString().match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
  },
  is_numeric: function(s) {
    return (s != null) && s.toString().match(/[0-9 ]+/);
  },
  date_format: function(lang) {
    if (lang === "it") {
      return "%d/%m/%Y %H:%M";
    } else {
      return "%m/%d/%Y %H:%M";
    }
  },
  date_format_short: function(lang) {
    if (lang === "it") {
      return "%d/%m/%Y";
    } else {
      return "%m/%d/%Y";
    }
  },
  geocode: function(address, oncomplete) {
    var _this = this;
    return new google.maps.Geocoder().geocode({
      'address': address
    }, function(results, status) {
      Utils.log(results);
      if (status === google.maps.GeocoderStatus.OK) {
        return oncomplete({
          latitude: results[0].geometry.location.lat(),
          longitude: results[0].geometry.location.lng(),
          latlng: results[0].geometry.location
        });
      } else {
        return oncomplete();
      }
    });
  },
  log: function() {
    return true;
  },
  gup: function(name) {
    var regex, regexS, results;
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    regexS = "[\\?&]" + name + "=([^&#]*)";
    regex = new RegExp(regexS);
    results = regex.exec(window.location.href);
    if (results === null) {
      return "";
    } else {
      return results[1];
    }
  },
  lower_inbox_counter: function() {
    if (window.inbox_counter) window.inbox_counter--;
    return $("#inbox a").text(I18n.t("layout.inbox", {
      count: window.inbox_counter
    }));
  },
  refresh_inbox_counter: function() {
    return $.ajax({
      url: "/api/private/inbox_counter.json",
      success: function(result) {
        var mail_counter;
        mail_counter = result.model.result || 0;
        window.inbox_counter = mail_counter;
        return $("#inbox a").text(I18n.t("layout.inbox", {
          count: parseInt(mail_counter, 10)
        }));
      }
    });
  },
  handle_locale: function() {
    $("#eng").click(function() {
      $.cookie("lang", "en");
      AppController.current_user().set_locale("en");
      return false;
    });
    return $("#ita").click(function() {
      $.cookie("lang", "it");
      AppController.current_user().set_locale("it");
      return false;
    });
  }
};

window.init_dom = function() {
  var $loading_div, attribute, data_attr, gravity, loading_prefilter, _i, _j, _len, _len2, _ref, _ref2;
  var _this = this;
  I18n.locale = $.cookie("lang");
  $.jGrowl.defaults.position = 'center';
  $.jGrowl.defaults.sticky = 'true';
  _ref = [null, "placeholder", "value", "title", "tooltip"];
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    attribute = _ref[_i];
    data_attr = attribute != null ? "data-i18n-" + attribute : "data-i18n";
    $("*[" + data_attr + "]").each(function() {
      var $el, key, opts;
      $el = $(this);
      key = $el.attr(data_attr);
      opts = {};
      _.each($el.listAttributes(), function(attr) {
        if (attr.indexOf("data-i18n-field") === 0) {
          return opts[attr.replace("data-i18n-field-", "")] = $el.attr(attr);
        }
      });
      if (data_attr === "data-i18n") {
        return $el.html(I18n.t(key, opts));
      } else {
        return $el.attr(attribute, I18n.t(key, opts));
      }
    });
  }
  _ref2 = ["nw", "n", "ne", "w", "e", "sw", "s", "se"];
  for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
    gravity = _ref2[_j];
    $(".tipsy-gravity-" + gravity + "[tooltip]").tipsy({
      live: true,
      fade: true,
      gravity: gravity,
      title: 'tooltip'
    });
  }
  $.datepicker.regional['it'] = {
    clearText: 'Svuota',
    clearStatus: '',
    clearStatus: 'Cancella la data corrente',
    closeText: 'Chiudi',
    closeStatus: '',
    closeStatus: 'Chiudi senza cambiamenti',
    prevText: '&lt;Prec',
    prevStatus: '',
    prevStatus: 'Mostra il mese precedente',
    nextText: 'Succ&gt;',
    nextStatus: '',
    nextStatus: 'Mostra il mese successivo',
    currentText: 'Oggi',
    currentStatus: '',
    currentStatus: 'Mostra il mese corrente',
    monthNames: ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'],
    monthNamesShort: ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'],
    monthStatus: 'Mostra un altro mese',
    yearStatus: 'Mostra un altro anno',
    weekHeader: 'Sm',
    weekStatus: '',
    weekStatus: 'Settimana dell\'anno',
    dayNames: ['Domenica', 'Luned&#236', 'Marted&#236', 'Mercoled&#236', 'Gioved&#236', 'Vener d&#236', 'Sabato'],
    dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'],
    dayNamesMin: ['Do', 'Lu', 'Ma', 'Me', 'Gio', 'Ve', 'Sa'],
    dayStatus: 'Imposta DD come primo giorno della settimana',
    dateStatus: 'Seleziona DD, M d',
    dateFormat: 'dd/mm/yy',
    firstDay: 1,
    initStatus: 'Seleziona una data',
    isRTL: false
  };
  $.datepicker.setDefaults($.datepicker.regional["it"]);
  $('*[data-datepicker]').live('focus keypress blur', function(e) {
    return $(this).datepicker({
      dateFormat: 'dd/mm/yy',
      minDate: new Date()
    });
  });
  $('textarea[data-max-length], input[data-max-length]').live('keypress blur', function(e) {
    var max, tval;
    tval = $(this).val();
    max = $(this).attr('data-max-length');
    if (tval.length === max) {
      return e.preventDefault();
    } else if (tval.length > max) {
      e.preventDefault();
      $(this).val(tval.substring(0, max - 1));
      return $.jGrowl("Attenzione: hai raggiunto il limite massimo di caratteri a tua disposizione.");
    }
  });
  $loading_div = $("<div class='ajax-spinner'><div class='inner'><span>" + (I18n.t("global.loading")) + "</span></div></div>").hide().appendTo("body");
  loading_prefilter = function(options, originalOptions, jqXHR) {
    var loading_complete, original_complete, _ref3;
    if (options.disable_loading || (options.url.match(/autocomplete/) || options.url.match(/inbox_counter/))) {
      Utils.log("ajaxPrefilter(): disable_loading = true for " + options.url);
    } else {
      Utils.log("ajaxPrefilter(): disable_loading = false for " + options.url);
      setTimeout(function() {
        if (!window.loading_showing && window.pending_requests) {
          $(".tipsy").remove();
          $loading_div.hide().fadeIn(100);
          return window.loading_showing = true;
        }
      }, 100);
      window.pending_requests++;
      Utils.log("ajaxPrefilter(): pending_requests = " + window.pending_requests + " for " + options.url);
      loading_complete = function(jqXHR, textStatus) {
        window.pending_requests--;
        Utils.log("complete(): pending_requests = " + window.pending_requests + " for " + options.url);
        if (window.loading_showing && !window.pending_requests && !window.lock_loading_counter) {
          $loading_div.fadeOut(100);
          return window.loading_showing = false;
        }
      };
      original_complete = (_ref3 = options.complete) != null ? _ref3 : null;
      if ((original_complete != null) && typeof original_complete === 'function') {
        options.complete = [];
        options.complete.push(original_complete);
        options.complete.push(loading_complete);
      } else if ((original_complete != null) && original_complete instanceof Array) {
        options.complete.push(loading_complete);
      } else {
        options.complete = loading_complete;
      }
    }
    return true;
  };
  $.ajaxPrefilter(loading_prefilter);
  $(document).ajaxSend(function(evt, request, settings) {
    var current_locale;
    Utils.log("ajaxSend(): url = " + settings.url);
    current_locale = $.cookie("lang") || "it";
    if (!settings.url.match(/upload/i)) {
      if (settings.url.match(/\?/)) {
        return settings.url = settings.url + "&languageId=" + current_locale;
      } else {
        return settings.url = settings.url + "?languageId=" + current_locale;
      }
    }
  });
  window.show_loading = function() {
    Utils.log("show_loading() called");
    if (!window.loading_showing) {
      $loading_div.hide().fadeIn(100);
      window.loading_showing = true;
    }
    return window.lock_loading_counter++;
  };
  window.hide_loading = function() {
    Utils.log("hide_loading() called");
    if (window.lock_loading_counter) window.lock_loading_counter--;
    if (window.loading_showing && !window.pending_requests && !window.lock_loading_counter) {
      $loading_div.fadeOut(100);
      return window.loading_showing = false;
    }
  };
  window.pending_requests = 0;
  window.loading_showing = false;
  window.lock_loading_counter = 0;
  return window.inbox_counter = 0;
};

var AppController, JsExternalLogoutDone, JsExternalSessionReady;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

AppController = (function() {

  __extends(AppController, Backbone.Router);

  function AppController() {
    AppController.__super__.constructor.apply(this, arguments);
  }

  AppController.prototype.initialize = function() {
    return this.current_user();
  };

  AppController.prototype.routes = {
    "/login/:social_network": "login",
    "/settings/:step": "settings",
    "/settings/1/change_password": "change_password",
    "/settings/1/notifications": "notifications",
    "/my_home/users": "my_home_users",
    "/my_home/users/:id": "my_home_user",
    "/my_home/users/:id/add_as_friend/:redirect_to": "my_home_user_add_friend",
    "/my_home/users/:id/remove_as_friend/:redirect_to": "my_home_user_remove_friend",
    "/my_home/events/new": "my_home_new_event",
    "/my_home/events/:id": "my_home_show_event",
    "/my_home/events/:id/edit": "my_home_edit_event",
    "/my_home/events/:id/destroy": "my_home_destroy_event",
    "/my_home/events/:id/action/:action": "my_home_event_action",
    "/my_home/events": "my_home_events",
    "/my_home/places": "my_home_places",
    "/my_home/places/new": "my_home_new_place",
    "/my_home/places/:id": "my_home_show_place",
    "/my_home/places/:id/edit": "my_home_edit_place",
    "/my_home/places/:id/abuse": "my_home_abuse_place",
    "/my_home/places/:id/add_as_friend/:redirect_to": "my_home_places_add_friend",
    "/my_home/places/:id/remove_as_friend/:redirect_to": "my_home_places_remove_friend",
    "/my_home/places/:id/events/new": "my_home_place_new_event",
    "/my_home/pros": "my_home_pros",
    "/my_home/pros/:id": "my_home_pro",
    "/my_home/pros/:id/add_as_friend/:redirect_to": "my_home_pro_add_friend",
    "/my_home/pros/:id/remove_as_friend/:redirect_to": "my_home_pro_remove_friend",
    "/my_home/sponsor": "my_home_sponsor",
    "/my_profile": "my_profile",
    "/inbox": "inbox",
    "/inbox/pro_message/new": "new_pro_message",
    "/about": "about",
    "/tos": "tos",
    "/tos/:lang": "tos",
    "/privacy": "privacy",
    "/sponsor": "my_home_sponsor",
    "/sponsor/:page": "my_home_sponsor",
    "/sponsor/:page/:id": "my_home_sponsor",
    "/partner": "partner",
    "/press": "press",
    "/contact": "contact_us",
    "/news": "news",
    "/logout": "logout",
    "": "homepage",
    "/": "homepage"
  };

  AppController.prototype.set_current_page = function(page) {
    var lang;
    if (this.current_page instanceof InboxView) {
      $("#inbox").unbind('click');
      if (this.current_page.inbox.cache_interval != null) {
        clearInterval(this.current_page.inbox.cache_interval);
        this.current_page.inbox.cache_interval = null;
      }
    }
    this.current_page = page;
    Utils.log("Current page:", page);
    lang = $.cookie("lang") || 'it';
    ApplicationScript.SetLanguageTag('/' + lang.toUpperCase());
    return AppView.set_current_page(this.current_page);
  };

  AppController.prototype.about = function() {
    this.about_view = new AboutView;
    return this.set_current_page(this.about_view);
  };

  AppController.prototype.press = function() {
    this.press_view = new PressView;
    return this.set_current_page(this.press_view);
  };

  AppController.prototype.partner = function() {
    this.partner_view = new PartnerView;
    return this.set_current_page(this.partner_view);
  };

  AppController.prototype.tos = function(lang) {
    this.tos_view = new TosView(lang);
    return this.set_current_page(this.tos_view);
  };

  AppController.prototype.contact_us = function() {
    this.contact_us_view = new Contact_UsView;
    return this.set_current_page(this.contact_us_view);
  };

  AppController.prototype.news = function() {
    this.newsview = new NewsView;
    return this.set_current_page(this.newsview);
  };

  AppController.prototype.privacy = function() {
    this.privacy_view = new PrivacyView;
    return this.set_current_page(this.privacy_view);
  };

  AppController.prototype.my_home_new_event = function() {
    Utils.log("my_home_new_event");
    if (!this.authenticated()) return;
    this.new_event_view = new NewEventView;
    return this.set_current_page(this.new_event_view);
  };

  AppController.prototype.my_home_place_new_event = function(place_id) {
    Utils.log("my_home_new_event");
    if (!this.authenticated()) return;
    this.new_event_view = new NewEventView({
      place_id: place_id
    });
    return this.set_current_page(this.new_event_view);
  };

  AppController.prototype.my_home_users = function() {
    if (!this.authenticated()) return;
    this.users_view = new UsersView;
    return this.set_current_page(this.users_view);
  };

  AppController.prototype.my_home_user_add_friend = function(id, redirect_to) {
    return $.ajax({
      url: "/api/private/friendship_add.json?idFriend=" + id,
      success: function(data) {
        $.jGrowl(I18n.t("global.user.friendship_requested"));
        return document.location = base64.decode(redirect_to);
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_user_remove_friend = function(id, redirect_to) {
    return $.ajax({
      url: "/api/private/friendship_decline.json?idFriend=" + id,
      success: function() {
        $.jGrowl(I18n.t("global.user.friendship_rejected"));
        return document.location = base64.decode(redirect_to);
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_pro_add_friend = function(id, redirect_to) {
    return $.ajax({
      url: "/api/private/friendship_add.json?idFriend=" + id,
      success: function(data) {
        $.jGrowl(I18n.t("global.user.friendship_requested"));
        return document.location = base64.decode(redirect_to);
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_pro_remove_friend = function(id, redirect_to) {
    return $.ajax({
      url: "/api/private/friendship_decline.json?idFriend=" + id,
      success: function() {
        $.jGrowl(I18n.t("global.user.friendship_rejected"));
        return document.location = base64.decode(redirect_to);
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_places_add_friend = function(id, redirect_to) {
    return $.ajax({
      url: "/api/private/business_friendship_add/" + id + ".json",
      success: function(data) {
        $.jGrowl(I18n.t("global.place.friendship_requested"));
        return document.location = base64.decode(redirect_to);
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_places_remove_friend = function(id, redirect_to) {
    return $.ajax({
      url: "/api/private/business_friendship_remove/" + id + ".json",
      success: function(data) {
        $.jGrowl(I18n.t("global.place.friendship_rejected"));
        return document.location = base64.decode(redirect_to);
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_user = function(id) {
    if (!this.authenticated()) return;
    this.user_view = new UserView({
      id: id
    });
    return this.set_current_page(this.user_view);
  };

  AppController.prototype.my_home_events = function() {
    if (!this.authenticated()) return;
    this.events_view = new EventsView;
    return this.set_current_page(this.events_view);
  };

  AppController.prototype.my_home_show_event = function(event_id) {
    if (!this.authenticated()) return;
    if (!event_id) {
      this.events_view = new EventsView;
      return this.set_current_page(this.events_view);
    } else {
      this.event_view = new EventView({
        id: event_id
      });
      return this.set_current_page(this.event_view);
    }
  };

  AppController.prototype.my_home_destroy_event = function(event_id) {
    var event;
    event = new Event({
      id: event_id
    });
    return event.destroy({
      success: function() {
        $.jGrowl(I18n.t("global.event.delete_success"));
        return document.location = "#/my_home/events";
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_edit_event = function(event_id) {
    if (!this.authenticated()) return;
    this.edit_event_view = new EditEventView({
      id: event_id
    });
    return this.set_current_page(this.edit_event_view);
  };

  AppController.prototype.my_home_event_action = function(event_id, action) {
    var event;
    if (!this.authenticated()) return;
    event = new Event({
      id: event_id
    });
    return event.perform_action({
      action: action,
      success: function() {
        return document.location = "#/my_home/events/" + event_id;
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  AppController.prototype.my_home_places = function() {
    if (!this.authenticated()) return;
    this.places_view = new PlacesView;
    return this.set_current_page(this.places_view);
  };

  AppController.prototype.my_home_show_place = function(id) {
    if (!this.authenticated()) return;
    this.place_view = new PlaceView({
      id: id
    });
    return this.set_current_page(this.place_view);
  };

  AppController.prototype.my_home_edit_place = function(id) {
    if (!this.authenticated()) return;
    this.place_view = new NewPlaceView({
      place: new Place({
        id: id
      })
    });
    return this.set_current_page(this.place_view);
  };

  AppController.prototype.my_home_abuse_place = function(id) {
    if (!this.authenticated()) return;
    this.place_view = new AbuseView({
      id: id
    });
    return this.set_current_page(this.place_view);
  };

  AppController.prototype.my_home_new_place = function() {
    if (!this.authenticated()) return;
    this.place_view = new NewPlaceView;
    return this.set_current_page(this.place_view);
  };

  AppController.prototype.my_home_sponsor = function(page, id) {
    this.sponsor_view = new SponsorsView({
      page: page,
      news_id: id
    });
    return this.set_current_page(this.sponsor_view);
  };

  AppController.prototype.my_profile = function() {
    var view;
    if (!this.authenticated()) return;
    view = null;
    if (this.current_user().get("category") === 0) {
      view = new UserView({
        id: this.current_user().get("id")
      });
    } else {
      view = new ProView({
        id: this.current_user().get("id")
      });
    }
    return this.set_current_page(view);
  };

  AppController.prototype.new_pro_message = function() {
    if (!(this.authenticated() || this.current_user().get("category") === 0)) {
      return;
    }
    this.new_pro_message = new NewProMessageView;
    return this.set_current_page(this.new_pro_message);
  };

  AppController.prototype.inbox = function() {
    if (!this.authenticated()) return;
    this.inbox_view = new InboxView;
    return this.set_current_page(this.inbox_view);
  };

  AppController.prototype.my_home_pros = function() {
    if (!this.authenticated()) return;
    this.pros_view = new ProsView;
    return this.set_current_page(this.pros_view);
  };

  AppController.prototype.my_home_pro = function(pro_id) {
    if (!this.authenticated()) return;
    this.pro_view = new ProView({
      id: pro_id
    });
    return this.set_current_page(this.pro_view);
  };

  AppController.prototype.current_user = function() {
    return this.user || (this.user = new CurrentUser);
  };

  AppController.prototype.settings = function(step) {
    if (!this.current_user().has_token()) document.location = "#/";
    Utils.log("Category utente: ", this.current_user().get("category"));
    step || (step = 1);
    if (this.current_user().get("category") === null) {
      document.location = "#/settings/0";
    } else if (parseInt(this.current_user().get("category")) > 0 && (parseInt(step) > 1)) {
      step += "Pro";
    }
    this.signup_view = new window["SignupStep" + step + "View"];
    return this.set_current_page(this.signup_view);
  };

  AppController.prototype.homepage = function() {
    if (this.current_user().logged_in()) {
      Utils.log("Redirect to My Home");
      return this.my_home_users();
    } else if (this.current_user().has_token()) {
      Utils.log("Redirect to Settings");
      return this.settings();
    } else {
      Utils.log("Redirect to HomepageView");
      this.home_view = new HomepageView;
      return this.set_current_page(this.home_view);
    }
  };

  AppController.prototype.login = function(social_network) {
    var code;
    code = {
      twitter: "TW",
      google: "GM",
      facebook: "FB"
    };
    code = code[social_network];
    return ApplicationScript.DialogLoginShow("" + code + "/1", code, "popup_cb", "");
  };

  AppController.prototype.logout = function() {
    if (this.current_user().has_token()) {
      document.location = "#/";
      return this.current_user().logout();
    } else {
      return document.location = "#/";
    }
  };

  AppController.prototype.authenticated = function() {
    if (this.current_user().logged_in()) {
      return true;
    } else if (this.current_user().has_token()) {
      Utils.log("Redirect to Settings");
      this.settings(1);
      return false;
    } else {
      Utils.log("Redirect to Homepage");
      $.jGrowl(I18n.t("global.not_logged_in"));
      $.cookie('desired_location', document.location);
      this.homepage();
      return false;
    }
  };

  AppController.prototype.change_password = function() {
    if (!this.current_user().has_token()) document.location = "#/";
    this.change_pass_view = new ChangePassView();
    return this.set_current_page(this.change_pass_view);
  };

  AppController.prototype.notifications = function() {
    if (!this.current_user().has_token()) document.location = "#/";
    this.notifications_view = new NotificationsView();
    return this.set_current_page(this.notifications_view);
  };

  return AppController;

})();

$(document).ready(function() {
  $.ajaxSetup({
    cache: false,
    complete: function(jqXHR, textStatus) {
      if (jqXHR.status === 401) {
        alert(I18n.t("global.new_login_required"));
        $.cookie('user', null);
        $.cookie('JSESSIONID', null);
        return document.location = "index.html";
      }
    }
  });
  window.init_dom();
  window.AppController = new AppController;
  window.AppView = new AppView;
  Backbone.history.start(function() {
    return $(".tipsy").remove();
  });
  return Utils.handle_locale();
});

JsExternalSessionReady = function(dialogId, sk) {
  Utils.log("SocialSuite Callback Token", sk);
  if (sk.length !== 0) {
    AppController.current_user().set({
      token: sk,
      registration_complete: null
    });
    return AppController.current_user().fetch({
      success: function() {
        var mail_counter;
        if (AppController.current_user().get('registration_complete') === true) {
          mail_counter = AppController.current_user().get('counter_new_emails') || 0;
          $("#inbox a").text(I18n.t("layout.inbox", {
            count: parseInt(mail_counter)
          }));
          if ($.cookie('desired_location')) {
            return document.location = $.cookie('desired_location');
          } else {
            return document.location = "#/my_home/users";
          }
        } else {
          return document.location = "#/settings/0";
        }
      },
      error: function() {
        $.jGrowl(I18n.t("global.connection_error"));
        return document.location = "#/";
      }
    });
  } else {
    return document.location = "#/";
  }
};

JsExternalLogoutDone = function(dialogId) {
  Utils.log("Callback logout");
  AppController.homepage();
  $("#email").val("");
  $("#password").val("");
  return window.hide_loading();
};

var EventMessage, EventMessages;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

EventMessage = (function() {

  __extends(EventMessage, Backbone.Model);

  function EventMessage() {
    EventMessage.__super__.constructor.apply(this, arguments);
  }

  EventMessage.prototype.validate = function(attrs) {
    var errors;
    if (!this.isNew()) return null;
    errors = [];
    if (!Utils.is_nonempty_string(attrs.message)) {
      errors.push(I18n.t("global.message.errors.message"));
    }
    if (errors.length !== 0) {
      return errors.join("\n");
    } else {
      return null;
    }
  };

  EventMessage.prototype.url = function() {
    if (this.isNew()) {
      if (this.get("reply_to")) {
        return "/api/private/event_submessage/" + (this.get("reply_to")) + ".json";
      } else {
        return "/api/private/event_message.json";
      }
    } else {
      if (this.get("reply_to")) {
        return "/api/private/event_submessage/" + (this.get("reply_to")) + ".json";
      } else {
        return "/api/private/event_message/" + (this.get("id")) + ".json";
      }
    }
  };

  EventMessage.prototype.fetch = function(opts) {
    Utils.log("Fetching message...");
    return EventMessage.__super__.fetch.call(this, opts);
  };

  EventMessage.prototype.toJSON = function() {
    var attrs;
    attrs = {
      message: this.attributes.message
    };
    if (this.attributes.gameId != null) attrs.gameId = this.attributes.gameId;
    return attrs;
  };

  EventMessage.prototype.parse = function(attrs) {
    if (attrs.playerSender != null) attrs.player = attrs.playerSender;
    return attrs;
  };

  EventMessage.prototype.destroy = function(options) {
    if (this.get("reply_to")) {
      Utils.log(this.attributes);
      return $.ajax({
        url: "/api/private/event_submessage_remove/" + (this.get("reply_to")),
        dataType: 'text',
        type: "POST",
        data: {
          date: this.attributes.date,
          playerIdSender: this.attributes.playerIdSender
        },
        success: options.success,
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    } else {
      return EventMessage.__super__.destroy.apply(this, arguments);
    }
  };

  return EventMessage;

})();

EventMessages = (function() {

  __extends(EventMessages, Backbone.Collection);

  function EventMessages() {
    EventMessages.__super__.constructor.apply(this, arguments);
  }

  EventMessages.prototype.model = EventMessage;

  EventMessages.prototype.fetch = function(opts) {
    Utils.log("Fetching event messages...");
    return EventMessages.__super__.fetch.call(this, opts);
  };

  EventMessages.prototype.initialize = function(models, options) {
    this.filters = {};
    this.event = options.event;
    return EventMessages.__super__.initialize.apply(this, arguments);
  };

  EventMessages.prototype.url = function() {
    return "/api/private/event_messages/" + (this.event.get("id")) + ".json";
  };

  EventMessages.prototype.parse = function(response) {
    return response.event_messages;
  };

  return EventMessages;

})();

var ProfileMessage, ProfileMessages;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

ProfileMessage = (function() {

  __extends(ProfileMessage, Backbone.Model);

  function ProfileMessage() {
    ProfileMessage.__super__.constructor.apply(this, arguments);
  }

  ProfileMessage.prototype.validate = function(attrs) {
    var errors;
    if (!this.isNew()) return null;
    errors = [];
    if (!Utils.is_nonempty_string(attrs.message)) {
      errors.push(I18n.t("global.message.errors.message"));
    }
    if (errors.length !== 0) {
      return errors.join("\n");
    } else {
      return null;
    }
  };

  ProfileMessage.prototype.url = function() {
    if (this.isNew()) {
      if (this.get("reply_to")) {
        return "/api/private/profile_submessage/" + (this.get("reply_to")) + ".json";
      } else {
        return "/api/private/profile_message";
      }
    } else {
      if (this.get("reply_to")) {
        return "";
      } else {
        return "/api/private/profile_message/" + (this.get("id"));
      }
    }
  };

  ProfileMessage.prototype.fetch = function(opts) {
    Utils.log("Fetching message...");
    return ProfileMessage.__super__.fetch.call(this, opts);
  };

  ProfileMessage.prototype.destroy = function(options) {
    if (this.get("reply_to")) {
      Utils.log(this.attributes);
      return $.ajax({
        url: "/api/private/profile_remove_submessage/" + (this.get("reply_to")) + ".json",
        type: "POST",
        data: {
          date: this.attributes.date,
          playerIdSender: this.attributes.playerIdSender
        },
        success: function() {
          Utils.log(options);
          return options.success();
        },
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    } else {
      return ProfileMessage.__super__.destroy.apply(this, arguments);
    }
  };

  ProfileMessage.prototype.toJSON = function() {
    if (this.isNew() && this.get("reply_to")) {
      return {
        message: this.get("message")
      };
    } else {
      return this.attributes;
    }
  };

  return ProfileMessage;

})();

ProfileMessages = (function() {

  __extends(ProfileMessages, Backbone.Collection);

  function ProfileMessages() {
    ProfileMessages.__super__.constructor.apply(this, arguments);
  }

  ProfileMessages.prototype.model = ProfileMessage;

  ProfileMessages.prototype.fetch = function(opts) {
    Utils.log("Fetching profile messages...");
    return ProfileMessages.__super__.fetch.call(this, opts);
  };

  ProfileMessages.prototype.initialize = function(models, options) {
    this.filters = {};
    this.user_id = options.user_id;
    return ProfileMessages.__super__.initialize.apply(this, arguments);
  };

  ProfileMessages.prototype.url = function() {
    if (this.user_id === AppController.current_user().get("id")) {
      return "/api/private/profile_messages.json";
    } else {
      return "/api/private/profile_messages/" + this.user_id + ".json";
    }
  };

  ProfileMessages.prototype.parse = function(response) {
    if (this.user_id === AppController.current_user().get("id")) {
      return response;
    } else {
      return response;
    }
  };

  return ProfileMessages;

})();

var PlaceProfileVideo, ProfilePhoto, ProfilePhotos, ProfileVideo, ProfileVideos;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

ProfilePhoto = (function() {

  __extends(ProfilePhoto, Backbone.Model);

  function ProfilePhoto() {
    ProfilePhoto.__super__.constructor.apply(this, arguments);
  }

  ProfilePhoto.prototype.url = function() {
    return "/api/private/profile_image/" + (this.get("id"));
  };

  return ProfilePhoto;

})();

ProfilePhotos = (function() {

  __extends(ProfilePhotos, Backbone.Collection);

  function ProfilePhotos() {
    ProfilePhotos.__super__.constructor.apply(this, arguments);
  }

  ProfilePhotos.prototype.model = ProfilePhoto;

  ProfilePhotos.prototype.initialize = function(models, options) {
    return this.user_id = options.user_id;
  };

  ProfilePhotos.prototype.url = function() {
    if (AppController.current_user().get('id') === this.user_id) {
      return "/api/private/profile_images.json";
    } else {
      return "/api/private/profile_images/" + this.user_id + ".json";
    }
  };

  ProfilePhotos.prototype.fetch = function(opts) {
    Utils.log("Fetching profile photos...");
    return ProfilePhotos.__super__.fetch.call(this, opts);
  };

  return ProfilePhotos;

})();

ProfileVideo = (function() {

  __extends(ProfileVideo, Backbone.Model);

  function ProfileVideo() {
    ProfileVideo.__super__.constructor.apply(this, arguments);
  }

  ProfileVideo.prototype.url = function() {
    if (this.isNew()) {
      return "/api/private/profile_video";
    } else {
      return "/api/private/profile_video/" + (this.get("id"));
    }
  };

  ProfileVideo.prototype.thumb_url = function(size) {
    var results;
    if (this.get('url') == null) return;
    if (this.get('url').match(/youtube/)) {
      size || (size = "big");
      if (results = this.get('url').match("[\\?&]v=([^&#]*)")) {
        if (size === "small") {
          return "http://img.youtube.com/vi/" + results[1] + "/2.jpg";
        } else {
          return "http://img.youtube.com/vi/" + results[1] + "/0.jpg";
        }
      } else {
        return "";
      }
    } else if (this.get('url').match(/vimeo/)) {
      return this.get('oembed').thumbnail_url.replace(/_.*\./, "_100.");
    } else {
      return "";
    }
  };

  return ProfileVideo;

})();

PlaceProfileVideo = (function() {

  __extends(PlaceProfileVideo, ProfileVideo);

  function PlaceProfileVideo() {
    PlaceProfileVideo.__super__.constructor.apply(this, arguments);
  }

  PlaceProfileVideo.prototype.url = function() {
    if (this.isNew()) {
      return "/api/private/profile_video/business/" + this.place_id;
    } else {
      return "/api/private/profile_video/" + (this.get("id"));
    }
  };

  return PlaceProfileVideo;

})();

ProfileVideos = (function() {

  __extends(ProfileVideos, Backbone.Collection);

  function ProfileVideos() {
    ProfileVideos.__super__.constructor.apply(this, arguments);
  }

  ProfileVideos.prototype.model = ProfileVideo;

  ProfileVideos.prototype.initialize = function(models, options) {
    return this.user_id = options.user_id;
  };

  ProfileVideos.prototype.url = function() {
    if (AppController.current_user().get('id') === this.user_id) {
      return "/api/private/profile_videos.json";
    } else {
      return "/api/private/profile_videos/" + this.user_id + ".json";
    }
  };

  ProfileVideos.prototype.fetch = function(opts) {
    Utils.log("Fetching profile videos...");
    return ProfileVideos.__super__.fetch.call(this, opts);
  };

  ProfileVideos.prototype.parse = function(els) {
    _.each(els, function(el) {
      try {
        el.oembed = JSON.parse(el.oembed.value);
      } catch (e) {
        el.oembed = "";
      }
      return el;
    });
    return els;
  };

  return ProfileVideos;

})();

var Event, MyEvents, PlaceEvents, ProEvents, UserEvents;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Event = (function() {

  __extends(Event, Backbone.Model);

  function Event() {
    this.perform_action = __bind(this.perform_action, this);
    Event.__super__.constructor.apply(this, arguments);
  }

  Event.prototype.url = function() {
    if (this.get("id")) {
      return "/api/private/event/" + (this.get("id")) + ".json";
    } else {
      return "/api/private/event.json";
    }
  };

  Event.prototype.validate = function(attrs) {
    var errors;
    errors = [];
    if (!Utils.is_bool(attrs.flagPrivate)) {
      errors.push(I18n.t("global.event.errors.private"));
    }
    if (!Utils.is_id(attrs.sportId)) {
      errors.push(I18n.t("global.event.errors.sport"));
    }
    if (!(Utils.is_unsigned_int(attrs.minPlayersReq) && parseInt(attrs.minPlayersReq) > 0)) {
      errors.push(I18n.t("global.event.errors.min"));
    }
    if (!(Utils.is_unsigned_int(attrs.maxPlayersReq) && parseInt(attrs.maxPlayersReq) >= parseInt(attrs.minPlayersReq))) {
      errors.push(I18n.t("global.event.errors.max"));
    }
    if (!(attrs.minPlayersReq <= attrs.maxPlayersReq)) {
      errors.push(I18n.t("global.event.errors.min_max"));
    }
    if (!Utils.is_nonempty_string(attrs.name)) {
      errors.push(I18n.t("global.event.errors.name"));
    }
    if (!Utils.is_nonempty_string(attrs.location.address)) {
      errors.push(I18n.t("global.event.errors.address"));
    }
    if (!(Utils.is_number(attrs.location.longitude) && Utils.is_number(attrs.location.latitude))) {
      errors.push(I18n.t("global.event.errors.marker"));
    }
    if (!Utils.is_bool(attrs.flagNotificationStatusChange)) {
      errors.push(I18n.t("global.event.errors.notify"));
    }
    if (errors.length > 0) {
      return errors[0];
    } else {
      return null;
    }
  };

  Event.prototype.messages = function() {
    return this._messages || (this._messages = new EventMessages([], {
      event: this
    }));
  };

  Event.prototype.missing_players = function() {
    return Math.max(0, this.get('maxPlayersReq') - this.get('acceptedPlayersCounter'));
  };

  Event.prototype.fetch = function(opts) {
    Utils.log("Fetching event...");
    return Event.__super__.fetch.call(this, opts);
  };

  Event.prototype.sport = function() {
    return this.get('sportName');
  };

  Event.prototype.message = function() {
    return this.get('description') || "";
  };

  Event.prototype.date = function() {
    return this.get('date');
  };

  Event.prototype.latlng = function() {
    if (this.get('location')) {
      return new google.maps.LatLng(this.get('location').latitude, this.get('location').longitude);
    }
  };

  Event.prototype.marker = function(map) {
    return new google.maps.Marker({
      map: map,
      title: this.sport(),
      position: this.latlng()
    });
  };

  Event.prototype.parse = function(attrs) {
    if (attrs) {
      return attrs.event_detail || attrs;
    } else {
      return false;
    }
  };

  Event.prototype.my_status = function() {
    if (!this.get("organizerDetail")) return;
    if (false && parseInt(this.get("organizerDetail").id) === parseInt(AppController.current_user().id)) {
      return "owner";
    }
    if (this.get("accepted") === true) {
      return "accepted";
    } else if (this.get("declined") === true) {
      return "declined";
    } else if (this.get("requestPartecipate") === true) {
      return "requested";
    } else if (this.get("newForThisEvent") === false) {
      return "waiting";
    } else {
      return "none";
    }
  };

  Event.prototype.perform_action = function(opts) {
    var url;
    url = (function() {
      switch (opts.action) {
        case "decline":
          return "/api/private/event_decline.json?eventId=" + (this.get('id'));
        case "accept":
          return "/api/private/event_accept.json?eventId=" + (this.get('id'));
        case "partecipate":
          return "/api/private/event_request_participate.json?eventId=" + (this.get('id'));
        case "undo_partecipate":
          return "/api/private/event_decline.json?eventId=" + (this.get('id'));
        case "undo_accept":
          return "/api/private/event_decline.json?eventId=" + (this.get('id'));
      }
    }).call(this);
    return $.ajax({
      url: url,
      success: opts.success,
      error: opts.error
    });
  };

  Event.prototype.distance_from = function(latlng) {
    return google.maps.geometry.spherical.computeDistanceBetween(this.latlng(), latlng);
  };

  Event.prototype.data_for_render = function(opts) {
    var ask, distance, distance_value, no_style, no_url, old_event, private_show, public_status, si_style, si_url;
    opts = _.extend({
      image_size: 48
    }, opts);
    si_style = no_style = "display:none;";
    public_status = "";
    switch (this.my_status()) {
      case "none":
        si_style = "";
        si_url = "#/my_home/events/" + (this.get("id")) + "/action/partecipate";
        ask = I18n.t("global.event.want_to_partecipate");
        break;
      case "accepted":
        no_style = "";
        no_url = "#/my_home/events/" + (this.get("id")) + "/action/undo_accept";
        ask = I18n.t("global.event.cancel_partecipation");
        public_status = I18n.t("global.event.partecipating");
        break;
      case "declined":
        si_style = "";
        si_url = "#/my_home/events/" + (this.get("id")) + "/action/accept";
        ask = I18n.t("global.event.want_to_partecipate");
        public_status = I18n.t("global.event.not_partecipating");
        break;
      case "requested":
        no_style = "";
        no_url = "#/my_home/events/" + (this.get("id")) + "/action/undo_partecipate";
        ask = I18n.t("global.event.waiting_for_acceptation");
        public_status = I18n.t("global.event.waiting_for_acceptation_public");
        break;
      case "waiting":
        no_style = si_style = "";
        no_url = "#/my_home/events/" + (this.get("id")) + "/action/decline";
        si_url = "#/my_home/events/" + (this.get("id")) + "/action/accept";
        ask = I18n.t("global.event.invited");
        public_status = I18n.t("global.event.invited_public");
    }
    if (this.missing_players() === 0) {
      if (this.my_status() === "accepted") {
        no_style = "";
        ask = I18n.t("global.event.cancel_partecipation");
      } else {
        si_style = no_style = "display:none;";
        ask = "";
      }
    }
    private_show = !this.get("flagPrivate") || (!this.get("newForThisEvent") && this.get("flagPrivate"));
    old_event = new Date(this.date()) < new Date();
    if (this.get('distance') != null) {
      distance_value = this.get('distance') * 1000;
    } else {
      distance_value = this.distance_from(AppController.current_user().latlng());
    }
    distance = I18n.t("global.event.distance", {
      distance: distance_value.meters()
    });
    return {
      sport: this.sport(),
      distance: distance,
      confirmed: !old_event ? I18n.t("global.event.confirmed_count", {
        count: this.get('acceptedPlayersCounter') || 0
      }) + " - " : void 0,
      missing_players: !old_event ? I18n.t("global.event.missing_count", {
        count: this.missing_players()
      }) : I18n.t("global.event.closed"),
      message: this.message().length > 0 ? "\"" + (this.message().strip().truncate(100)) + "\"" : I18n.t("global.event.no_description"),
      long_message: this.message().length > 0 ? "\"" + (this.message()) + "\"" : I18n.t("global.event.no_description"),
      has_long_message: this.message().length > 100 ? true : false,
      date: Date.parse(this.date()).strftime(Utils.date_format($.cookie("lang"))),
      short_date: Date.parse(this.date()).strftime(Utils.date_format_short($.cookie("lang"))),
      name: this.get("name"),
      short_name: this.get("name").length > 40 ? this.get("name").strip().truncate(40) : this.get("name"),
      partecipants: I18n.t("global.event.partecipants", {
        min: this.get("minPlayersReq"),
        max: this.get("maxPlayersReq")
      }),
      creator_image: this.get("organizerDetail").urlImg + ("=s" + opts.image_size + "-c?imgmax=" + opts.image_size + "&crop=1"),
      creator: I18n.t("global.event.created_by", {
        creator: this.get("organizerDetail").name
      }),
      creator_prefix: I18n.t("global.event.created_by_prefix"),
      creator_name: this.get("organizerDetail").name,
      creator_path: this.get("organizerDetail").category === 0 ? "#/my_home/users/" + (this.get("organizerDetail").id) : "#/my_home/pros/" + (this.get("organizerDetail").id),
      address: this.get("location").address,
      'public': this.get("flagPrivate") ? I18n.t("global.event.private") : I18n.t("global.event.public"),
      details_path: "#/my_home/events/" + (this.get("id")),
      edit_path: "#/my_home/events/" + (this.get("id")) + "/edit",
      destroy_path: "#/my_home/events/" + (this.get("id")) + "/destroy",
      edit_style: (this.get("organizerDetail").id === AppController.current_user().get("id")) && !old_event ? "" : "display:none;",
      si_style: si_style,
      no_style: no_style,
      si_url: si_url,
      no_url: no_url,
      private_actions_style: private_show ? "" : "display:none;",
      ask: ask,
      public_status: public_status
    };
  };

  return Event;

})();

MyEvents = (function() {

  __extends(MyEvents, Backbone.Collection);

  function MyEvents() {
    MyEvents.__super__.constructor.apply(this, arguments);
  }

  MyEvents.prototype.model = Event;

  MyEvents.prototype.fetch = function(opts) {
    Utils.log("Fetching events...");
    return MyEvents.__super__.fetch.call(this, opts);
  };

  MyEvents.prototype.initialize = function() {
    return this.filters = {};
  };

  MyEvents.prototype.set_filters = function(options) {
    return this.filters = options;
  };

  MyEvents.prototype.next_page = function() {
    return this.filters.page++;
  };

  MyEvents.prototype.previous_page = function() {
    return this.filters.page--;
  };

  MyEvents.prototype.url = function() {
    var url;
    if (!this.filters.name) this.filters.name = "";
    url = "";
    if (this.filters.nearby) {
      url = "/api/private/events_nearby.json?lat=" + this.filters.latitude + "&lon=" + this.filters.longitude + "&name=" + this.filters.name;
      if (this.filters.sport_id != null) {
        url += "&sportId=" + this.filters.sport_id;
      }
      url;
    } else if (this.filters.mine) {
      url = "/api/private/my_events.json?";
    } else {
      url = "/api/private/my_other_events.json?";
    }
    url += "&rangeFrom=" + (this.filters.page * this.filters.per_page) + "&rangeTo=" + ((this.filters.page + 1) * this.filters.per_page);
    if (this.filters.sport_name) url += "&sportName=" + this.filters.sport_name;
    return url;
  };

  MyEvents.prototype.parse = function(response) {
    if (this.filters.nearby) {
      return response.events_nearby;
    } else if (this.filters.mine) {
      return response;
    } else if (this.filters.accepted) {
      return response;
    } else {
      return response;
    }
  };

  return MyEvents;

})();

UserEvents = (function() {

  __extends(UserEvents, Backbone.Collection);

  function UserEvents() {
    UserEvents.__super__.constructor.apply(this, arguments);
  }

  UserEvents.prototype.model = Event;

  UserEvents.prototype.initialize = function(models, options) {
    return this.user_id = options.user_id;
  };

  UserEvents.prototype.fetch = function(opts) {
    Utils.log("Fetching events...");
    return UserEvents.__super__.fetch.call(this, opts);
  };

  UserEvents.prototype.url = function() {
    if (AppController.current_user().get('id') === this.user_id) {
      return "/api/private/user_events.json?userId=" + this.user_id;
    } else {
      return "/api/private/user_events.json?userId=" + this.user_id;
    }
  };

  UserEvents.prototype.parse = function(response) {
    return response;
  };

  return UserEvents;

})();

ProEvents = (function() {

  __extends(ProEvents, Backbone.Collection);

  function ProEvents() {
    ProEvents.__super__.constructor.apply(this, arguments);
  }

  ProEvents.prototype.model = Event;

  ProEvents.prototype.initialize = function(models, options) {
    return this.pro_id = options.pro_id;
  };

  ProEvents.prototype.fetch = function(opts) {
    Utils.log("Fetching pro events...");
    return ProEvents.__super__.fetch.call(this, opts);
  };

  ProEvents.prototype.url = function() {
    return "/api/private/pro_events.json?proId=" + this.pro_id;
  };

  ProEvents.prototype.parse = function(response) {
    return response;
  };

  return ProEvents;

})();

PlaceEvents = (function() {

  __extends(PlaceEvents, Backbone.Collection);

  function PlaceEvents() {
    PlaceEvents.__super__.constructor.apply(this, arguments);
  }

  PlaceEvents.prototype.model = Event;

  PlaceEvents.prototype.initialize = function(models, options) {
    return this.place_id = options.place_id;
  };

  PlaceEvents.prototype.fetch = function(opts) {
    Utils.log("Fetching place events...");
    return PlaceEvents.__super__.fetch.call(this, opts);
  };

  PlaceEvents.prototype.url = function() {
    return "/api/private/business_events/" + this.place_id + ".json";
  };

  PlaceEvents.prototype.parse = function(response) {
    return response;
  };

  return PlaceEvents;

})();

var Friend, Friends, Friendship, Friendships;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Friend = (function() {

  __extends(Friend, Backbone.Model);

  function Friend() {
    Friend.__super__.constructor.apply(this, arguments);
  }

  Friend.prototype.latlng = function() {
    if (!this.get('location') && this.get('player')) {
      this.set({
        'location': this.get('player').location
      });
    }
    if (this.get('location')) {
      return new google.maps.LatLng(this.get('location').latitude, this.get('location').longitude);
    } else {
      return new google.maps.LatLng(0, 0);
    }
  };

  Friend.prototype.marker = function(map) {
    return new google.maps.Marker({
      map: map,
      title: this.name(),
      position: this.latlng()
    });
  };

  Friend.prototype.name = function() {
    if ((this.get('player').name != null) && this.get('player').name.length > 0) {
      return this.get('player').name;
    } else if ((this.get('player').businessName != null) && this.get('player').businessName.length > 0 && this.get('player').category > 0) {
      return this.get('player').businessName;
    } else {
      return this.get('player').firstName + " " + this.get('player').lastName;
    }
  };

  Friend.prototype.age = function() {
    return new Date().getFullYear() - this.get('player').age;
  };

  Friend.prototype.sex = function() {
    if (this.get('player').gender === 'M') {
      return I18n.t("global.user.male");
    } else {
      return I18n.t("global.user.female");
    }
  };

  Friend.prototype.distance_from = function(latlng) {
    return google.maps.geometry.spherical.computeDistanceBetween(this.latlng(), latlng);
  };

  Friend.prototype.data_for_render = function(opts) {
    var distance, distance_short, distance_value, force_distance_from, id, image, _ref, _ref2;
    opts = _.extend({
      image_size: 48
    }, opts);
    id = this.get('playerId') || this.get('player').id || this.get('id');
    if (this.get('player').localUri != null) {
      distance = "";
      distance_short = "";
      image = this.get('player').urlImg;
      if (image === "") {
        image = "http://social.we-sport.com/social/img/blank_profile.png";
      }
    } else {
      force_distance_from = (_ref = opts.force_distance_from) != null ? _ref : false;
      if ((this.get('distance') != null) && !force_distance_from) {
        distance_value = this.get('distance') * 1000;
      } else {
        distance_value = this.distance_from((_ref2 = opts.distance_from) != null ? _ref2 : AppController.current_user().latlng());
      }
      distance = I18n.t("global.user.distance", {
        distance: distance_value.meters()
      });
      distance_short = I18n.t("global.user.distance_short", {
        distance: distance_value.meters()
      });
      image = this.get('player').urlImg + ("=s" + opts.image_size + "-c?imgmax=" + opts.image_size + "&crop=1");
    }
    return {
      playerId: id,
      image: image,
      imageTeam: this.get('team') || "",
      name: this.name() || "Nessun nome",
      distance: distance,
      distance_short: distance_short,
      age: I18n.t("global.user.age", {
        count: this.age()
      }),
      sex: this.sex(),
      add_friendship_path: ("#/my_home/users/" + id + "/add_as_friend/") + base64.encode(document.location),
      add_friendship_style: this.get("player").showRequestFriendship && id !== AppController.current_user().get("id") ? "" : "display:none;",
      remove_friendship_path: ("#/my_home/users/" + id + "/remove_as_friend/") + base64.encode(document.location),
      remove_friendship_style: !this.get("player").showRequestFriendship && id !== AppController.current_user().get("id") ? "" : "display:none;",
      details_path: parseInt(this.get('player').category) === 0 ? "#/my_home/users/" + id : "#/my_home/pros/" + id,
      reliability: I18n.t("global.user.votes", {
        count: this.get("player").rating || 0,
        total: this.get("player").ratingReliabilityTotal || 0
      }),
      ratingSport: I18n.t("global.user.votes", {
        count: this.get("player").ratingSport || 0,
        total: this.get("player").ratingSportTotal || 0
      })
    };
  };

  return Friend;

})();

Friends = (function() {

  __extends(Friends, Backbone.Collection);

  function Friends() {
    Friends.__super__.constructor.apply(this, arguments);
  }

  Friends.prototype.model = Friend;

  Friends.prototype.initialize = function() {
    return this.filters = {
      name: ""
    };
  };

  Friends.prototype.set_filters = function(options) {
    return this.filters = options;
  };

  Friends.prototype.next_page = function() {
    return this.filters.page++;
  };

  Friends.prototype.previous_page = function() {
    if (this.filters.page > 0) return this.filters.page--;
  };

  Friends.prototype.url = function() {
    var url;
    if (!this.filters.name) this.filters.name = "";
    url = "";
    if (this.filters.is_friend) {
      url = "/api/private/friends_nearby.json?";
    } else {
      url = "/api/private/users_nearby.json?lat=" + this.filters.latitude + "&lon=" + this.filters.longitude + "&name=" + this.filters.name;
      if (this.filters.sport_id) {
        url += "&sportId=" + this.filters.sport_id;
      } else if (this.filters.sport_name) {
        url += "&sportName=" + this.filters.sport_name;
      }
    }
    url += "&rangeFrom=" + (this.filters.page * this.filters.per_page) + "&rangeTo=" + ((this.filters.page + 1) * this.filters.per_page);
    return url;
  };

  Friends.prototype.fetch = function(opts) {
    Utils.log("Fetching friends...");
    return Friends.__super__.fetch.call(this, opts);
  };

  Friends.prototype.parse = function(response) {
    if (this.filters.is_friend) {
      return response.result;
    } else {
      return response.users_nearby;
    }
  };

  return Friends;

})();

Friendship = (function() {

  __extends(Friendship, Backbone.Model);

  function Friendship() {
    Friendship.__super__.constructor.apply(this, arguments);
  }

  Friendship.prototype.detail_path = function() {
    if (this.get("friend")) {
      switch (this.get("category") || this.get("friend").category) {
        case 0:
          return "index.html#/my_home/users/" + (this.get("friend").id);
        default:
          return "index.html#/my_home/pros/" + (this.get("friend").id);
      }
    }
  };

  return Friendship;

})();

Friendships = (function() {

  __extends(Friendships, Backbone.Collection);

  function Friendships() {
    Friendships.__super__.constructor.apply(this, arguments);
  }

  Friendships.prototype.model = Friendship;

  Friendships.prototype.initialize = function(models, options) {
    this.user_id = options.user_id;
    return Friendships.__super__.initialize.apply(this, arguments);
  };

  Friendships.prototype.url = function() {
    return "/api/private/friendship.json?userId=" + this.user_id;
  };

  Friendships.prototype.parse = function(r) {
    return r.result || r;
  };

  return Friendships;

})();

var Location, Locations, UserLocations;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Location = (function() {

  __extends(Location, Backbone.Model);

  function Location() {
    Location.__super__.constructor.apply(this, arguments);
  }

  Location.prototype.url = function() {
    if (this.get("id")) {
      return "/api/private/user_sport_location/" + (this.get('id')) + ".json";
    } else {
      return "/api/private/user_sport_location.json";
    }
  };

  Location.prototype.sport_ids = function() {
    var ids, sportIdsList;
    if (this.get("sportIdsList") && this.get("sportIdsList").length > 0) {
      sportIdsList = $.grep(this.get("sportIdsList"), function(value) {
        return !isNaN(value) && value;
      });
      this.set({
        "sportIdsList": sportIdsList
      });
      ids = _.map(this.get("sportIdsList") || [], function(id) {
        return parseInt(id);
      });
      return _.uniq(ids);
    } else {
      return [];
    }
  };

  Location.prototype.add_sport_id = function(id) {
    var ids;
    ids = this.sport_ids();
    ids.push(id);
    return this.set({
      sportIdsList: _.uniq(ids)
    });
  };

  Location.prototype.remove_sport_id = function(id) {
    var ids, idx;
    ids = this.sport_ids();
    if ((idx = ids.indexOf(id)) !== -1) ids.splice(idx, 1);
    return this.set({
      sportIdsList: ids
    });
  };

  Location.prototype.latlng = function() {
    return new google.maps.LatLng(this.get('location').latitude, this.get('location').longitude);
  };

  Location.prototype.marker = function(map) {
    return new google.maps.Marker({
      map: map,
      title: "Posizione",
      position: this.latlng()
    });
  };

  return Location;

})();

Locations = (function() {

  __extends(Locations, Backbone.Collection);

  function Locations() {
    Locations.__super__.constructor.apply(this, arguments);
  }

  Locations.prototype.model = Location;

  Locations.prototype.fetch = function(opts) {
    Utils.log("Fetching locations...");
    return Locations.__super__.fetch.call(this, opts);
  };

  Locations.prototype.url = function() {
    return "/api/private/user_sport_locations.json";
  };

  Locations.prototype.parse = function(els) {
    Utils.log(els);
    return els;
  };

  return Locations;

})();

UserLocations = (function() {

  __extends(UserLocations, Backbone.Collection);

  function UserLocations() {
    UserLocations.__super__.constructor.apply(this, arguments);
  }

  UserLocations.prototype.model = Location;

  UserLocations.prototype.initialize = function(models, options) {
    return this.user_id = options.user_id;
  };

  UserLocations.prototype.fetch = function(opts) {
    Utils.log("Fetching user locations...");
    return UserLocations.__super__.fetch.apply(this, arguments);
  };

  UserLocations.prototype.url = function() {
    if (AppController.current_user().get('id') === this.user_id) {
      return "/api/private/user_sport_locations.json";
    } else {
      return "/api/private/user_sport_locations/" + this.user_id + ".json";
    }
  };

  return UserLocations;

})();

var LocationPro, MyProLocations, ProLocations;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

LocationPro = (function() {

  __extends(LocationPro, Backbone.Model);

  function LocationPro() {
    LocationPro.__super__.constructor.apply(this, arguments);
  }

  LocationPro.prototype.url = function() {
    if (this.get("id")) {
      return "/api/pro_services_location/" + (this.get('id')) + ".json";
    } else {
      return "/api/private/pro_services_location.json";
    }
  };

  LocationPro.prototype.service_ids = function() {
    var ids, serviceIdsList;
    serviceIdsList = this.get("serviceIdsList") || [];
    ids = _.map(serviceIdsList, function(id) {
      return parseInt(id);
    });
    Utils.log(_.uniq(ids));
    return _.uniq(_.compact(ids));
  };

  LocationPro.prototype.add_service_id = function(id) {
    var ids;
    ids = this.service_ids();
    ids.push(id);
    return this.set({
      serviceIdsList: _.uniq(ids)
    });
  };

  LocationPro.prototype.remove_service_id = function(id) {
    var ids, idx;
    ids = this.service_ids();
    if (ids.length > 0 && ((idx = ids.indexOf(id)) !== -1)) ids.splice(idx, 1);
    return this.set({
      serviceIdsList: ids
    });
  };

  LocationPro.prototype.latlng = function() {
    if (this.get('location')) {
      return new google.maps.LatLng(this.get('location').latitude, this.get('location').longitude);
    }
  };

  return LocationPro;

})();

MyProLocations = (function() {

  __extends(MyProLocations, Backbone.Collection);

  function MyProLocations() {
    MyProLocations.__super__.constructor.apply(this, arguments);
  }

  MyProLocations.prototype.model = LocationPro;

  MyProLocations.prototype.fetch = function(opts) {
    Utils.log("Fetching locations...");
    return MyProLocations.__super__.fetch.call(this, opts);
  };

  MyProLocations.prototype.url = function() {
    return "/api/private/pro_services_locations.json";
  };

  MyProLocations.prototype.parse = function(els) {
    Utils.log(els);
    return els;
  };

  return MyProLocations;

})();

ProLocations = (function() {

  __extends(ProLocations, Backbone.Collection);

  function ProLocations() {
    ProLocations.__super__.constructor.apply(this, arguments);
  }

  ProLocations.prototype.model = LocationPro;

  ProLocations.prototype.initialize = function(models, options) {
    return this.pro_id = options.pro_id;
  };

  ProLocations.prototype.fetch = function(opts) {
    Utils.log("Fetching pro locations...");
    return ProLocations.__super__.fetch.call(this, opts);
  };

  ProLocations.prototype.url = function() {
    return "/api/pro_services_locations/" + this.pro_id + ".json";
  };

  ProLocations.prototype.parse = function(els) {
    Utils.log(els);
    return els;
  };

  return ProLocations;

})();

var Place, PlaceSport, PlaceSports, Places;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Place = (function() {

  __extends(Place, Backbone.Model);

  function Place() {
    Place.__super__.constructor.apply(this, arguments);
  }

  Place.prototype.latlng = function() {
    return new google.maps.LatLng(this.get('location').latitude, this.get('location').longitude);
  };

  Place.prototype.marker = function(map) {
    return new google.maps.Marker({
      map: map,
      title: "Position",
      position: this.latlng()
    });
  };

  Place.prototype.validate = function(attrs) {
    var errors;
    if (!this.isNew()) return null;
    errors = [];
    if (!Utils.is_nonempty_string(attrs.businessName)) {
      errors.push(I18n.t("global.place.errors.name"));
    }
    if (!Utils.is_nonempty_string(attrs.description)) {
      errors.push(I18n.t("global.place.errors.description"));
    }
    if (!Utils.is_nonempty_string(attrs.location.address)) {
      errors.push(I18n.t("global.place.errors.address"));
    }
    if (!(Utils.is_number(attrs.location.longitude) && Utils.is_number(attrs.location.latitude))) {
      errors.push(I18n.t("global.place.errors.marker"));
    }
    if (errors.length !== 0) {
      return errors.join("\n");
    } else {
      return null;
    }
  };

  Place.prototype.url = function() {
    if (this.isNew()) {
      return "/api/private/business.json";
    } else if (_.size(this.attributes) === 1) {
      return "/api/private/business/" + (this.get('id')) + ".json";
    } else {
      return "/api/private/business/" + (this.get('id')) + ".json";
    }
  };

  Place.prototype.toJSON = function() {
    var prop, props, _i, _len, _ref;
    props = {};
    _ref = ["businessName", "description", "phone", "email", "website", "location"];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      prop = _ref[_i];
      props[prop] = this.attributes[prop];
    }
    return props;
  };

  Place.prototype.distance_from = function(latlng) {
    return google.maps.geometry.spherical.computeDistanceBetween(this.latlng(), latlng);
  };

  Place.prototype.data_for_render = function(opts) {
    var distance, distance_value;
    opts = _.extend({
      image_size: 48
    }, opts);
    if (this.get('distance') != null) {
      distance_value = this.get('distance') * 1000;
    } else {
      distance_value = this.distance_from(AppController.current_user().latlng());
    }
    distance = I18n.t("global.place.distance", {
      distance: distance_value.meters()
    });
    return {
      placeId: this.get('id'),
      name: this.get('businessName'),
      email: this.get('email'),
      mailto: "mailto:" + (this.get('email')),
      website: this.get('website') ? this.get('website').match(/^http/) ? this.get('website') : "http://" + this.get('website') : "",
      votes: I18n.t("global.place.votes", {
        count: Math.round(parseFloat(this.get("rating")) * 10) / 10,
        total: this.get("ratingReliabilityTotal")
      }),
      address: this.get('location').address,
      phone: this.get('phone'),
      description: this.get('description'),
      image: this.get('urlImg') + ("=s" + opts.image_size + "-c?imgmax=" + opts.image_size + "&crop=1"),
      distance: distance,
      details_path: "index.html#/my_home/places/" + (this.get('id')),
      abuse_path: "index.html#/my_home/places/" + (this.get('id')) + "/abuse",
      abuse_style: this.get("reportedForAbuse") ? "" : "display: none;",
      edit_path: "index.html#/my_home/places/" + (this.get('id')) + "/edit",
      create_event_path: "index.html#/my_home/places/" + (this.get('id')) + "/events/new",
      edit_style: this.get("allowModify") ? "" : "display:none;",
      add_friendship_path: ("index.html#/my_home/places/" + (this.get('id')) + "/add_as_friend/") + base64.encode(document.location),
      add_friendship_style: this.get("showRequestFriendship") ? "" : "display:none;",
      remove_friendship_path: ("#/my_home/places/" + (this.get('id')) + "/remove_as_friend/") + base64.encode(document.location),
      remove_friendship_style: !this.get("showRequestFriendship") ? "" : "display:none;"
    };
  };

  return Place;

})();

Places = (function() {

  __extends(Places, Backbone.Collection);

  function Places() {
    Places.__super__.constructor.apply(this, arguments);
  }

  Places.prototype.model = Place;

  Places.prototype.initialize = function() {
    return this.filters = {};
  };

  Places.prototype.set_filters = function(options) {
    return this.filters = options;
  };

  Places.prototype.next_page = function() {
    return this.filters.page++;
  };

  Places.prototype.previous_page = function() {
    return this.filters.page--;
  };

  Places.prototype.url = function() {
    var url;
    if (!this.filters.name) this.filters.name = "";
    url = "";
    if (this.filters.mine) {
      url = "/api/private/business_inserted?";
    } else if (this.filters.favorites_nearby) {
      url = "/api/private/business_friendship?";
    } else if (this.filters.been) {
      url = "/api/private/business_known?";
    } else {
      url = "/api/private/business_nearby.json?lat=" + this.filters.latitude + "&lon=" + this.filters.longitude + "&name=" + this.filters.name;
      if (this.filters.sport_id) {
        url += "&sportId=" + this.filters.sport_id;
      } else if (this.filters.sport_name) {
        url += "&sportName=" + this.filters.sport_name;
      }
    }
    url += "&rangeFrom=" + (this.filters.page * this.filters.per_page) + "&rangeTo=" + ((this.filters.page + 1) * this.filters.per_page);
    return url;
  };

  Places.prototype.fetch = function(opts) {
    Utils.log("Fetching places...");
    return Places.__super__.fetch.call(this, opts);
  };

  Places.prototype.parse = function(response) {
    return _.map(response, function(el) {
      if (el.businessName != null) {
        return el;
      } else {
        el.business.distance = el.distance;
        return el.business;
      }
    });
  };

  return Places;

})();

PlaceSport = (function() {

  __extends(PlaceSport, Backbone.Model);

  function PlaceSport() {
    PlaceSport.__super__.constructor.apply(this, arguments);
  }

  PlaceSport.prototype.validate = function(attrs) {
    var errors;
    if (!this.isNew()) return null;
    errors = [];
    if (errors.length !== 0) {
      return errors[0];
    } else {
      return null;
    }
  };

  PlaceSport.prototype.url = function() {
    if (this.isNew()) {
      return "/api/private/business_sport_location";
    } else {
      return "/api/private/business_sport_location/" + (this.get('id'));
    }
  };

  return PlaceSport;

})();

PlaceSports = (function() {

  __extends(PlaceSports, Backbone.Collection);

  function PlaceSports() {
    PlaceSports.__super__.constructor.apply(this, arguments);
  }

  PlaceSports.prototype.model = PlaceSport;

  PlaceSports.prototype.initialize = function(models, options) {
    this.place_id = options.place_id;
    return PlaceSports.__super__.initialize.apply(this, arguments);
  };

  PlaceSports.prototype.url = function() {
    return "/api/private/business_sport_locations.json?businessId=" + this.place_id;
  };

  return PlaceSports;

})();

var Pro, Pros;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Pro = (function() {

  __extends(Pro, Backbone.Model);

  function Pro() {
    Pro.__super__.constructor.apply(this, arguments);
  }

  Pro.prototype.latlng = function() {
    if (!(this.get('location') && this.get('location').latitude && this.get('location').longitude)) {
      return false;
    } else {
      return new google.maps.LatLng(this.get('location').latitude, this.get('location').longitude);
    }
  };

  Pro.prototype.marker = function(map) {
    return new google.maps.Marker({
      map: map,
      title: (this.get('pro') && this.get('pro').name) || "",
      position: this.latlng()
    });
  };

  Pro.prototype.url = function() {
    return "/api/private/pro/" + (this.get('id')) + ".json";
  };

  Pro.prototype.distance_from = function(latlng) {
    return google.maps.geometry.spherical.computeDistanceBetween(this.latlng(), latlng);
  };

  Pro.prototype.data_for_render = function(opts) {
    var category, distance, distance_value;
    opts = _.extend({
      image_size: 48
    }, opts);
    category = (function() {
      switch (this.get("category")) {
        case 2:
          return I18n.t("global.pro.professional");
        case 1:
          return I18n.t("global.pro.association");
        case 3:
          return I18n.t("global.pro.structure");
        case 4:
          return I18n.t("global.pro.federation");
        case 5:
          return I18n.t("global.pro.company");
      }
    }).call(this);
    if (this.get('distance') != null) {
      distance_value = this.get('distance') * 1000;
    } else {
      distance_value = this.distance_from(AppController.current_user().latlng());
    }
    distance = I18n.t("global.place.distance", {
      distance: distance_value.meters()
    });
    return {
      proId: this.get('id'),
      name: this.get('businessName'),
      category_label: category,
      image: this.get('urlImg') + ("=s" + opts.image_size + "-c?imgmax=" + opts.image_size + "&crop=1"),
      address: this.get('location').address,
      email: this.get('email'),
      mailto: "mailto:" + (this.get('email')),
      phone: this.get('phone'),
      votes: I18n.t("global.pro.votes", {
        count: this.get("rating"),
        total: this.get("ratingReliabilityTotal")
      }),
      description: this.get('description'),
      distance: distance,
      website: this.get('website') ? this.get('website').match(/^http/) ? this.get('website') : "http://" + this.get('website') : "",
      details_path: "index.html#/my_home/pros/" + (this.get('id')),
      add_friendship_path: ("#/my_home/pros/" + (this.get('id')) + "/add_as_friend/") + base64.encode(document.location),
      add_friendship_style: this.get("showRequestFriendship") && this.get('id') !== AppController.current_user().get("id") ? "" : "display:none;",
      remove_friendship_path: ("#/my_home/pros/" + (this.get('id')) + "/remove_as_friend/") + base64.encode(document.location),
      remove_friendship_style: !this.get("showRequestFriendship") && this.get('id') !== AppController.current_user().get("id") ? "" : "display:none;"
    };
  };

  return Pro;

})();

Pros = (function() {

  __extends(Pros, Backbone.Collection);

  function Pros() {
    Pros.__super__.constructor.apply(this, arguments);
  }

  Pros.prototype.model = Pro;

  Pros.prototype.initialize = function() {
    return this.filters = {};
  };

  Pros.prototype.set_filters = function(options) {
    return this.filters = options;
  };

  Pros.prototype.next_page = function() {
    return this.filters.page++;
  };

  Pros.prototype.previous_page = function() {
    return this.filters.page--;
  };

  Pros.prototype.url = function() {
    var url;
    if (this.filters.favorites_nearby) {
      url = "/api/private/pro_friends_nearby.json?lat=" + this.filters.latitude + "&lon=" + this.filters.longitude + "&rangeFrom=" + (this.filters.page * this.filters.per_page) + "&rangeTo=" + ((this.filters.page + 1) * this.filters.per_page);
    } else {
      url = "/api/private/pro_nearby.json?lat=" + this.filters.latitude + "&lon=" + this.filters.longitude + "&rangeFrom=" + (this.filters.page * this.filters.per_page) + "&rangeTo=" + ((this.filters.page + 1) * this.filters.per_page);
      if (this.filters.sport_id) url += "&sportId=" + this.filters.sport_id;
    }
    if (this.filters.name) url += "&name=" + this.filters.name;
    if (this.filters.sport_name) url += "&sportName=" + this.filters.sport_name;
    if (parseInt(this.filters.category) > 0) {
      url += "&categoryId=" + this.filters.category;
    }
    if (this.filters.service_id) {
      url += "&serviceId=" + this.filters.service_id;
    } else if (this.filters.service_name) {
      url += "&serviceName=" + this.filters.service_name;
    }
    return url;
  };

  Pros.prototype.fetch = function(opts) {
    Utils.log("Fetching pros...");
    return Pros.__super__.fetch.call(this, opts);
  };

  Pros.prototype.parse = function(response) {
    if (this.filters.favorites_nearby) {
      return response;
    } else {
      return response.result;
    }
  };

  return Pros;

})();

var CurrentUser, User;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

CurrentUser = (function() {

  __extends(CurrentUser, Backbone.Model);

  function CurrentUser() {
    CurrentUser.__super__.constructor.apply(this, arguments);
  }

  CurrentUser.prototype.initialize = function() {
    var _this = this;
    this._friends = new Friends;
    this._events = new MyEvents;
    this._places = new Places;
    this._sports = new MyUserSports;
    this._locations = new Locations;
    this._services = new MyProServices;
    this.load_from_cookie();
    this.bind("reset", function() {
      return _this.save_to_cookie();
    });
    this.bind("change", function() {
      return _this.save_to_cookie();
    });
    return this.attributes.languageId = "it";
  };

  CurrentUser.prototype.registration_complete = function() {
    return "/api/private/user_registration_complete";
  };

  CurrentUser.prototype.url = function() {
    if (this.get('pro')) {
      return "/api/private/pro?token=" + this.get("token");
    } else {
      return "/api/private/user?token=" + this.get("token");
    }
  };

  CurrentUser.prototype.friends = function() {
    return this._friends;
  };

  CurrentUser.prototype.places = function() {
    return this._places;
  };

  CurrentUser.prototype.events = function() {
    return this._events;
  };

  CurrentUser.prototype.services = function() {
    return this._services;
  };

  CurrentUser.prototype.sports = function() {
    return this._sports;
  };

  CurrentUser.prototype.locations = function() {
    return this._locations;
  };

  CurrentUser.prototype.fetch = function(opts) {
    Utils.log("Fetching user...");
    return CurrentUser.__super__.fetch.call(this, opts);
  };

  CurrentUser.prototype.latlng = function() {
    return new google.maps.LatLng(this.get("latitude") || 45, this.get("longitude") || 7.5);
  };

  CurrentUser.prototype.distance_from = function(latlng) {
    return google.maps.geometry.spherical.computeDistanceBetween(this.latlng(), latlng);
  };

  CurrentUser.prototype.parse = function(response) {
    return $.extend({}, this.attributes, {
      id: response.id,
      name: response.name,
      first_name: response.firstName,
      last_name: response.lastName,
      business_name: response.businessName,
      contact_name: response.contactName,
      category: response.category,
      email: response.email,
      description: response.description,
      phone: response.phone,
      website: response.website,
      age: response.age,
      gender: response.gender,
      address: response.location && response.location.address,
      img: response.urlImg,
      latitude: response.location && response.location.latitude,
      longitude: response.location && response.location.longitude,
      geo_hash: response.location && response.location.geoHash,
      registration_complete: response.registrationComplete,
      counter_new_emails: response.counterNewEmails,
      flag_email_event: response.flagEmailEvent,
      flag_email_friendship_request: response.flagEmailFriendshipRequest,
      flag_email_confirm_friendship_request: response.flagEmailConfirmFriendshipRequest,
      flag_email_message_event: response.flagEmailMessageEvent,
      flag_email_message_profile: response.flagEmailMessageProfile,
      flag_email_newsletter: response.flagEmailNewsletter
    });
  };

  CurrentUser.prototype.toJSON = function() {
    return {
      firstName: this.attributes.first_name,
      lastName: this.attributes.last_name,
      businessName: this.attributes.business_name,
      contactName: this.attributes.contact_name,
      category: this.attributes.category,
      age: this.attributes.age,
      description: this.attributes.description,
      gender: this.attributes.gender,
      email: this.attributes.email,
      phone: this.attributes.phone,
      website: this.attributes.website,
      registrationComplete: this.attributes.registration_complete,
      location: {
        address: this.attributes.address,
        longitude: this.attributes.longitude,
        latitude: this.attributes.latitude,
        geoHash: this.attributes.geo_hash
      },
      flagEmailEvent: this.attributes.flag_email_event,
      flagEmailConfirmFriendshipRequest: this.attributes.flag_email_confirm_friendship_request,
      flagEmailFriendshipRequest: this.attributes.flag_email_friendship_request,
      flagEmailMessageEvent: this.attributes.flag_email_message_event,
      flagEmailMessageProfile: this.attributes.flag_email_message_profile,
      flagEmailNewsletter: this.attributes.flag_email_newsletter
    };
  };

  CurrentUser.prototype.save_to_cookie = function() {
    Utils.log("Salvataggio cookie", JSON.stringify(this.attributes), "expire: ", this.get("cookie_expire_time") || 1);
    $.cookie('user', JSON.stringify(this.attributes), {
      expire: this.get("cookie_expire_time") || 1
    });
    return $.cookie('lang', this.get('locale'));
  };

  CurrentUser.prototype.load_from_cookie = function() {
    Utils.log("Caricamento da cookie", $.cookie('user'));
    this.set($.parseJSON($.cookie('user')));
    return $.cookie('lang', this.get('locale'));
  };

  CurrentUser.prototype.logged_in = function() {
    return this.has_token() && this.get('registration_complete') === true && this.get('category') !== null;
  };

  CurrentUser.prototype.has_token = function() {
    return this.get('token') && this.get('token').length !== 0;
  };

  CurrentUser.prototype.login = function(email, password) {
    if (email.trim().length === 0) {
      $.jGrowl(I18n.t("layout.messages.login.insert_email"));
      return;
    }
    if (password.trim().length === 0) {
      $.jGrowl(I18n.t("layout.messages.login.insert_password"));
      return;
    }
    window.show_loading();
    return $.ajax({
      url: ApplicationScript.RestUrl("user.login", ""),
      type: "get",
      dataType: "jsonp",
      data: {
        Email: email,
        Password: password
      },
      success: function(data) {
        window.hide_loading();
        if (data._responseStatus === "") {
          AppController.current_user().set({
            token: data.sk,
            registration_complete: null
          });
          return AppController.current_user().fetch({
            success: function(result) {
              var mail_counter;
              Utils.log("Fetched User");
              mail_counter = AppController.current_user().get('counter_new_emails') || 0;
              $("#inbox a").text(I18n.t("layout.inbox", {
                count: parseInt(mail_counter)
              }));
              if ($.cookie('desired_location')) {
                return document.location = $.cookie('desired_location');
              } else {
                return document.location = "#/my_home/users";
              }
            },
            error: function() {
              return $.jGrowl(I18n.t("global.connection_error"));
            }
          });
        } else {
          $.jGrowl(I18n.t("layout.messages.login.username_or_password_invalid"));
          return $("#login #password").val("");
        }
      },
      error: function() {
        window.hide_loading();
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  CurrentUser.prototype.logout = function() {
    this.set({
      'token': ''
    });
    return $.ajax({
      url: '/api/logout',
      success: function(data, textStatus, jqXHR) {
        $.cookie('user', null);
        $.cookie('JSESSIONID', null);
        $.cookie('desired_location', null);
        window.show_loading();
        return ApplicationScript.Logout("Logout/1", "");
      }
    });
  };

  CurrentUser.prototype.logout_nosocial = function() {
    this.set({
      'token': ''
    });
    return $.ajax({
      url: '/api/logout',
      success: function(data, textStatus, jqXHR) {
        $.cookie('user', null);
        return $.cookie('JSESSIONID', null);
      }
    });
  };

  CurrentUser.prototype.infer_attributes = function(success) {
    var inferred_attrs;
    var _this = this;
    inferred_attrs = [
      {
        attr: "first_name",
        data: (function(d) {
          return d.user.FirstName;
        })
      }, {
        attr: "last_name",
        data: (function(d) {
          return d.user.LastName;
        })
      }, {
        attr: "age",
        data: (function(d) {
          return new Date(d.user.BirthdayTs).getFullYear();
        })
      }, {
        attr: "gender",
        data: (function(d) {
          return d.user.Gender;
        })
      }, {
        attr: "email",
        data: (function(d) {
          return d.user.Email;
        })
      }, {
        attr: "business_name",
        data: (function(d) {
          return d.user.DisplayName;
        })
      }, {
        attr: "website",
        data: (function(d) {
          return d.user.Link;
        })
      }, {
        attr: "phone",
        data: (function(d) {
          return d.user.Tel || d.user.Mobile;
        })
      }
    ];
    return $.getJSON(ApplicationScript.RestUrl('user.data', this.get("token")) + "&callback=?", function(data, textStatus, jqXHR) {
      var a, x, _i, _len;
      for (_i = 0, _len = inferred_attrs.length; _i < _len; _i++) {
        a = inferred_attrs[_i];
        if (!_this.get(a.attr)) {
          x = {};
          x[a.attr] = a.data(data);
          Utils.log("Inferring " + a.attr, a.data(data));
          _this.set(x);
        }
      }
      return success();
    });
  };

  CurrentUser.prototype.delete_account = function() {
    if (confirm(I18n.t("global.signup.confirm_delete"))) {
      return $.ajax({
        url: '/api/private/delete_account.json',
        type: "get",
        dataType: "jsonp",
        success: function(data, textStatus, jqXHR) {
          AppController.current_user().logout();
          return document.location = "#/";
        },
        error: function(jqXHR, textStatus, errorThrown) {
          AppController.current_user().logout();
          return document.location = "#/";
        }
      });
    }
  };

  CurrentUser.prototype.set_locale = function(locale) {
    this.set({
      locale: locale
    });
    if (this.logged_in()) {
      $.ajax({
        url: "/api/private/user_locale/" + this.locale,
        type: "POST",
        data: {
          locale: this.get('locale')
        },
        success: function() {
          return location.reload();
        },
        error: function() {
          return location.reload();
        }
      });
    } else {
      location.reload();
    }
    return false;
  };

  return CurrentUser;

})();

User = (function() {

  __extends(User, Backbone.Model);

  function User() {
    User.__super__.constructor.apply(this, arguments);
  }

  User.prototype.latlng = function() {
    return new google.maps.LatLng(this.get('location').latitude, this.get('location').longitude);
  };

  User.prototype.marker = function(map) {
    return new google.maps.Marker({
      map: map,
      title: this.get('pro').name,
      position: this.latlng()
    });
  };

  User.prototype.url = function() {
    if (AppController.current_user().get('id') === this.get('id')) {
      return "/api/private/user.json";
    } else {
      return "/api/private/user/" + (this.get('id')) + ".json";
    }
  };

  User.prototype.name = function() {
    return this.get('name');
  };

  User.prototype.age = function() {
    return new Date().getFullYear() - this.get('age');
  };

  User.prototype.sex = function() {
    if (this.get('gender') === 'M') {
      return I18n.t("global.user.male");
    } else {
      return I18n.t("global.user.female");
    }
  };

  User.prototype.data_for_render = function(opts) {
    return new Friend({
      player: this.attributes
    }).data_for_render(opts);
  };

  return User;

})();

var Schedule, Schedules;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Schedule = (function() {

  __extends(Schedule, Backbone.Model);

  function Schedule() {
    Schedule.__super__.constructor.apply(this, arguments);
  }

  Schedule.prototype.url = function() {
    if (this.get("id")) {
      return "/api/private/user_sport/" + (this.get("id"));
    } else {
      return "/api/private/user_sport";
    }
  };

  Schedule.prototype.validate = function(attrs) {
    var errors;
    errors = [];
    _.each(attrs.listSchedule, function(timeslot) {
      if (!timeslot.startTime) timeslot.startTime = "0:00";
      if (!timeslot.endTime) timeslot.endTime = "23:59";
      if (!Utils.is_time(timeslot.startTime)) {
        errors.push(I18n.t("global.schedule.errors.time", {
          time: timeslot.startTime
        }));
      }
      if (!Utils.is_time(timeslot.endTime)) {
        return errors.push(I18n.t("global.schedule.errors.time", {
          time: timeslot.endTime
        }));
      }
    });
    if (errors.length !== 0) {
      return errors.join("\n");
    } else {
      return null;
    }
  };

  return Schedule;

})();

Schedules = (function() {

  __extends(Schedules, Backbone.Collection);

  function Schedules() {
    Schedules.__super__.constructor.apply(this, arguments);
  }

  Schedules.prototype.model = Schedule;

  Schedules.prototype.userId = "";

  Schedules.prototype.fetch = function(opts) {
    Utils.log("Fetching schedules...");
    return Schedules.__super__.fetch.call(this, opts);
  };

  Schedules.prototype.url = function() {
    return "/api/private/user_sports.json";
  };

  Schedules.prototype.parse = function(response) {
    return response;
  };

  return Schedules;

})();

var MyProServices, ProServices, Service;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Service = (function() {

  __extends(Service, Backbone.Model);

  function Service() {
    Service.__super__.constructor.apply(this, arguments);
  }

  Service.prototype.url = function() {
    if (this.is_destroying) {
      return "/api/private/pro_service/" + (this.get('id')) + ".json";
    } else {
      return "/api/private/pro_service.json";
    }
  };

  Service.prototype.validate = function(attrs) {
    var errors;
    errors = [];
    if (!Utils.is_name(attrs.serviceName)) {
      errors.push(I18n.t("settings.step2_pro.service_name_error"));
    }
    if (errors.length > 0) {
      return errors[0];
    } else {
      return null;
    }
  };

  return Service;

})();

MyProServices = (function() {

  __extends(MyProServices, Backbone.Collection);

  function MyProServices() {
    MyProServices.__super__.constructor.apply(this, arguments);
  }

  MyProServices.prototype.model = Service;

  MyProServices.prototype.url = function() {
    return "/api/private/pro_services.json";
  };

  MyProServices.prototype.fetch = function(opts) {
    Utils.log("Fetching services...");
    return MyProServices.__super__.fetch.call(this, opts);
  };

  return MyProServices;

})();

ProServices = (function() {

  __extends(ProServices, Backbone.Collection);

  function ProServices() {
    ProServices.__super__.constructor.apply(this, arguments);
  }

  ProServices.prototype.model = Service;

  ProServices.prototype.initialize = function(models, options) {
    return this.pro_id = options.pro_id;
  };

  ProServices.prototype.url = function() {
    return "/api/pro_services/" + this.pro_id + ".json";
  };

  ProServices.prototype.fetch = function(opts) {
    Utils.log("Fetching pro services...");
    return ProServices.__super__.fetch.call(this, opts);
  };

  return ProServices;

})();

var Inbox, InboxMessage;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

InboxMessage = (function() {

  __extends(InboxMessage, Backbone.Model);

  function InboxMessage() {
    InboxMessage.__super__.constructor.apply(this, arguments);
  }

  InboxMessage.prototype.url = function() {
    if (this.isNew()) {
      return "/api/private/inbox/new.json";
    } else {
      return "/api/private/inbox/" + (this.get("id")) + ".json";
    }
  };

  InboxMessage.prototype.mark_as_read = function(opts) {
    return $.ajax({
      url: "/api/private/inbox_mark_as_read/" + (this.get('id')) + ".json",
      success: opts.success,
      error: opts.error
    });
  };

  InboxMessage.prototype.message = function() {
    if (this.get("message").value.length > 0) {
      return "\"" + (this.get("message").value.strip().truncate(100)) + "\"";
    }
  };

  InboxMessage.prototype.long_message = function() {
    return "\"" + (this.get("message").value) + "\"";
  };

  InboxMessage.prototype.has_long_message = function() {
    if (this.get("message").value.length > 100) {
      return true;
    } else {
      return false;
    }
  };

  return InboxMessage;

})();

Inbox = (function() {

  __extends(Inbox, Backbone.Collection);

  function Inbox() {
    this.more_messages = __bind(this.more_messages, this);
    this.load_more = __bind(this.load_more, this);
    this.load_one = __bind(this.load_one, this);
    this.fill_cache = __bind(this.fill_cache, this);
    this.reload = __bind(this.reload, this);
    Inbox.__super__.constructor.apply(this, arguments);
  }

  Inbox.prototype.initialize = function() {
    this.inbox_size = 5;
    this.cache_size = this.inbox_size * 2 + 1;
    this.reload();
    return this.bind('destroy', this.load_one);
  };

  Inbox.prototype.model = InboxMessage;

  Inbox.prototype.url = function() {
    return "/api/private/inbox_new.json?next=" + this.inbox_size;
  };

  Inbox.prototype.parse = function(objs) {
    return _.map(objs, function(attrs) {
      if (attrs.event != null) attrs.event = JSON.parse(attrs.event.value);
      return attrs;
    });
  };

  Inbox.prototype.reload = function() {
    var _this = this;
    this.cache = [];
    this.caching = false;
    this.no_more_messages = false;
    return this.fill_cache({
      disable_loading: false,
      min_size: this.inbox_size * 2,
      success: function() {
        if (_this.cache.length < _this.cache_size) {
          _this.no_more_messages = true;
        } else {
          _this.no_more_messages = false;
        }
        _this.reset();
        _this.load_more();
        if (_this.cache_interval != null) {
          clearInterval(_this.cache_interval);
          _this.cache_interval = null;
        }
        return _this.cache_interval = setInterval(function() {
          if (!_this.caching) return _this.fill_cache();
        }, 250);
      }
    });
  };

  Inbox.prototype.fill_cache = function(options) {
    var cache_amount, default_options, disable_loading, last_message, success, timestamp, url;
    var _this = this;
    default_options = {
      min_size: this.inbox_size + 1,
      disable_loading: true,
      success: function() {}
    };
    options = $.extend(default_options, options);
    disable_loading = options.disable_loading;
    success = options.success;
    if (this.caching) {
      if (!disable_loading) window.show_loading();
      setTimeout(function() {
        _this.fill_cache(options);
        if (!disable_loading) return window.hide_loading();
      }, 100);
      return;
    }
    if (this.no_more_messages || this.cache.length >= options.min_size) {
      success();
      return;
    }
    if (this.cache.length) {
      last_message = _.last(this.cache);
    } else if (this.models.length) {
      last_message = _.last(this.models);
    }
    if (last_message != null) timestamp = last_message.timestamp;
    this.caching = true;
    cache_amount = this.cache_size - this.cache.length;
    if (timestamp != null) {
      url = "/api/private/inbox_new.json?timestamp=" + timestamp + "&next=" + cache_amount;
    } else {
      url = "/api/private/inbox_new.json?next=" + cache_amount;
    }
    return $.ajax({
      url: url,
      disable_loading: disable_loading,
      success: function(raw_messages) {
        var message_count, messages;
        messages = _this.parse(raw_messages);
        if (messages.length < cache_amount) _this.no_more_messages = true;
        message_count = messages.length;
        while (message_count) {
          _this.cache.push(messages.shift());
          message_count--;
        }
        _this.caching = false;
        return success();
      }
    });
  };

  Inbox.prototype.load_one = function() {
    var _this = this;
    return this.fill_cache({
      min_size: 2,
      disable_loading: false,
      success: function() {
        if (_this.cache.length) return _this.add(_this.cache.shift());
      }
    });
  };

  Inbox.prototype.load_more = function() {
    var _this = this;
    return this.fill_cache({
      disable_loading: false,
      success: function() {
        var message_count, _results;
        if (_this.cache.length > _this.inbox_size) {
          message_count = _this.inbox_size;
        } else {
          message_count = _this.cache.length;
        }
        _results = [];
        while (message_count > 0) {
          _this.add(_this.cache.shift());
          _results.push(message_count--);
        }
        return _results;
      }
    });
  };

  Inbox.prototype.more_messages = function() {
    if (this.no_more_messages && !this.cache.length) {
      return false;
    } else {
      return true;
    }
  };

  return Inbox;

})();

var MyUserSports, Sport, Sports, UserSports;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Sport = (function() {

  __extends(Sport, Backbone.Model);

  function Sport() {
    Sport.__super__.constructor.apply(this, arguments);
  }

  return Sport;

})();

Sports = (function() {

  __extends(Sports, Backbone.Collection);

  function Sports() {
    Sports.__super__.constructor.apply(this, arguments);
  }

  Sports.prototype.model = Sport;

  Sports.prototype.fetch = function(opts) {
    Utils.log("Fetching sports...");
    return Sports.__super__.fetch.call(this, opts);
  };

  Sports.prototype.url = function() {
    return "/api/sport.json?all=true";
  };

  Sports.prototype.parse = function(response) {
    return response.allsports;
  };

  return Sports;

})();

MyUserSports = (function() {

  __extends(MyUserSports, Backbone.Collection);

  function MyUserSports() {
    MyUserSports.__super__.constructor.apply(this, arguments);
  }

  MyUserSports.prototype.model = Sport;

  MyUserSports.prototype.fetch = function(opts) {
    Utils.log("Fetching user sports...");
    return MyUserSports.__super__.fetch.apply(this, arguments);
  };

  MyUserSports.prototype.url = function() {
    return "/api/private/user_sports.json";
  };

  return MyUserSports;

})();

UserSports = (function() {

  __extends(UserSports, Backbone.Collection);

  function UserSports() {
    UserSports.__super__.constructor.apply(this, arguments);
  }

  UserSports.prototype.model = Sport;

  UserSports.prototype.initialize = function(models, options) {
    return this.user_id = options.user_id;
  };

  UserSports.prototype.fetch = function(opts) {
    Utils.log("Fetching user sports...");
    return UserSports.__super__.fetch.apply(this, arguments);
  };

  UserSports.prototype.url = function() {
    if (AppController.current_user().get('id') === this.user_id) {
      return "/api/private/user_sports.json";
    } else {
      return "/api/private/user_sports/" + this.user_id + ".json";
    }
  };

  return UserSports;

})();

var AppView;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

AppView = (function() {

  __extends(AppView, Backbone.View);

  function AppView() {
    this.refresh_inbox_enter = __bind(this.refresh_inbox_enter, this);
    this.refresh_inbox_click = __bind(this.refresh_inbox_click, this);
    this.refresh_inbox = __bind(this.refresh_inbox, this);
    AppView.__super__.constructor.apply(this, arguments);
  }

  AppView.prototype.initialize = function() {
    var _this = this;
    this.user = AppController.current_user();
    $("#login .go").click(function() {
      return _this.login();
    });
    $("#forgot-pass").click(function() {
      return _this.forgot_password();
    });
    $("#email,#password").keyup(function(e) {
      if (e.keyCode === 13) return _this.login();
    });
    $("#inbox a").text(I18n.t("layout.inbox", {
      count: 0
    }));
    if (AppController.current_user().logged_in()) window.inbox_counter_requests--;
    this.inbox_refreshed = false;
    this.refresh_inbox_enter();
    this.refresh_inbox_click();
    this.user.bind("change", function() {
      return _this.update_header();
    });
    return this.update_header();
  };

  AppView.prototype.refresh_inbox = function() {
    var _this = this;
    if (AppController.current_user().logged_in() && !this.inbox_refreshed) {
      Utils.refresh_inbox_counter();
      this.inbox_refreshed = true;
      return setTimeout(function() {
        return _this.inbox_refreshed = false;
      }, 30 * 1000);
    }
  };

  AppView.prototype.refresh_inbox_click = function() {
    var _this = this;
    $('body').unbind("click.refresh_inbox");
    this.refresh_inbox();
    return setTimeout(function() {
      return $('body').bind("click.refresh_inbox", _this.refresh_inbox_click);
    }, 60 * 1000);
  };

  AppView.prototype.refresh_inbox_enter = function() {
    var _this = this;
    $('body').unbind("mouseenter.refresh_inbox");
    this.refresh_inbox();
    return setTimeout(function() {
      return $('body').bind("mouseenter.refresh_inbox", _this.refresh_inbox_enter);
    }, 30 * 1000);
  };

  AppView.prototype.update_header = function() {
    Utils.log("Update header!");
    $("#container-header #badge > div").hide();
    if (this.user.logged_in()) {
      $("#container-header #settings").show();
      $("#container-header #badge #logged-in").show();
      $("#container-header #badge #logged-in img").attr("src", this.user.get('img') + "=s44-c?imgmax=44&crop=1");
      $("#container-header #badge #logged-in .name").text(this.user.get('name'));
      return $("#container-header #badge #logged-in .profile_url").attr("href", (parseInt(this.user.get("category")) === 0 ? "#/my_home/users/" + (this.user.get('id')) : "#/my_home/pros/" + (this.user.get('id'))));
    } else if (this.user.has_token()) {
      $("#container-header #settings").hide();
      return $("#container-header #badge #in-registration").show();
    } else {
      return $("#container-header #badge #login").show();
    }
  };

  AppView.prototype.set_logged_user = function(user) {
    $("#profile img").attr("src", user.get("img"));
    $("#profile img").attr("alt", user.get("name"));
    return $("#profile").append(user.get("name"));
  };

  AppView.prototype.set_current_page = function(page) {
    this.current_page = page;
    $("#header #menu a").removeClass("menu-selected");
    $("body").attr("id", page.slug());
    if (this.current_page.hide_header()) {
      $("#container-header").hide();
    } else {
      $("#container-header").show();
    }
    if (this.current_page instanceof MyHomeTabView) {
      $("#header #menu #myhome a").addClass("menu-selected");
    } else if (this.current_page instanceof InboxView) {
      $("#header #menu #inbox a").addClass("menu-selected");
    }
    $("#container").empty().append(this.current_page.el);
    this.current_page.render();
    return scroll(0, 0);
  };

  AppView.prototype.login = function() {
    AppController.current_user().logout_nosocial();
    AppController.current_user().set({
      cookie_expire_time: $("#stay-logged").is(":checked") ? 100 : 1
    });
    AppController.current_user().login($("#login #email").val(), $("#login #password").val());
    return false;
  };

  AppView.prototype.forgot_password = function() {
    if ($("#email").val().trim().length === 0) {
      $.jGrowl(I18n.t("layout.messages.insert_email"));
      return;
    }
    return $.ajax({
      url: ApplicationScript.RestUrl("user.reset.password", ""),
      type: "get",
      dataType: "jsonp",
      data: {
        Email: $("#email").val()
      },
      success: function(data) {
        if (data._responseStatus === "") {
          return $.jGrowl(I18n.t("layout.messages.forgot_password.new_password_was_sent"));
        } else if (data._responseStatus.match(/CurrentUser\.Not\.Found/)) {
          return $.jGrowl(I18n.t("layout.messages.forgot_password.email_not_found"));
        } else {
          return $.jGrowl(I18n.t("layout.messages.forgot_password.error", {
            status_detail: data._responseStatus
          }));
        }
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  return AppView;

})();

var PageView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

PageView = (function() {

  __extends(PageView, Backbone.View);

  function PageView() {
    PageView.__super__.constructor.apply(this, arguments);
  }

  PageView.prototype.slug = function() {
    return "my-home-page";
  };

  PageView.prototype.hide_header = function() {
    return false;
  };

  PageView.prototype.render = function() {
    $('span.hasPlaceHolder').remove();
    return $('.hasPlaceHolder').addPlaceholder();
  };

  return PageView;

})();

var MyHomeTabView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

MyHomeTabView = (function() {

  __extends(MyHomeTabView, PageView);

  function MyHomeTabView() {
    MyHomeTabView.__super__.constructor.apply(this, arguments);
  }

  MyHomeTabView.prototype.slug = function() {
    return "tab-view";
  };

  MyHomeTabView.prototype.initialize = function() {
    var _this = this;
    document.title = "We-Sport.com";
    this.collection.filters.per_page_multiplier = 1;
    this.luoghi = [];
    $.getJSON('/api/private/user_sport_locations', function(data) {
      var l, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = data.length; _i < _len; _i++) {
        l = data[_i];
        _results.push(_this.luoghi.push({
          label: l.location.address,
          id: l.id
        }));
      }
      return _results;
    });
    this.sports = [];
    $.getJSON('/api/private/user_sports.json', function(data) {
      var sport, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = data.length; _i < _len; _i++) {
        sport = data[_i];
        _results.push(_this.sports.push({
          label: sport.sportName,
          id: sport.sportId
        }));
      }
      return _results;
    });
    this.categories = ["all_categories", "associations", "professionals", "structures", "federations", "companies"];
    this.categories = _.map(this.categories, function(category, id) {
      return {
        label: I18n.t("pros." + category),
        categoryId: id
      };
    });
    this.$("#pro_categorie").val(I18n.t("pros.all_categories"));
    return this.pro_category_id = 0;
  };

  MyHomeTabView.prototype.setup_autocompletes = function() {
    var _this = this;
    this.$("#luoghi").autocomplete({
      source: function(request, response) {
        var luoghi;
        luoghi = _.filter(_this.luoghi, function(luogo) {
          return luogo.label.length === 0 || luogo.label.toLowerCase().indexOf(this.$("#luoghi").val().toLowerCase()) !== -1;
        });
        return response(luoghi);
      },
      minChars: 0
    });
    this.$("#luoghi").focus(function(e) {
      var search_string;
      if (!_this.$("#luoghi").val()) {
        search_string = ' ';
        if (_this.$("#luoghi").val()) search_string = _this.$("#luoghi").val();
        return _this.$("#luoghi").autocomplete('search', search_string);
      }
    });
    this.$("#sport").autocomplete({
      source: function(request, response) {
        if (_this.$("#sport").val().length > 0) {
          return $.getJSON('/api/autocomplete_sport.json?prefix=' + request.term, function(data) {
            var sport, sports, _i, _len, _ref;
            sports = [];
            _ref = data.list;
            for (_i = 0, _len = _ref.length; _i < _len; _i++) {
              sport = _ref[_i];
              sports.push({
                label: sport.name,
                id: sport.id
              });
            }
            return response(sports);
          });
        } else {
          return response(_this.sports);
        }
      },
      select: function(event, ui) {
        return _this.selected_sport_id = ui.item.id;
      }
    });
    this.$("#sport").focus(function(e) {
      return _this.$("#sport").autocomplete('search', ' ');
    });
    this.$("#sportivi-form").autocomplete({
      source: function(request, response) {
        var query, requestSplit;
        requestSplit = request.term.split(" ");
        query = 'prefix1=' + requestSplit[0];
        if (requestSplit.length > 1) query += '&prefix2=' + requestSplit[1];
        return $.getJSON('/api/private/autocomplete_player.json?' + query, function(data) {
          var player, players, _i, _len, _ref;
          players = [];
          _ref = data.list;
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            player = _ref[_i];
            players.push({
              label: player.name,
              playerId: player.id,
              location: player.location,
              player: player
            });
          }
          return response(players);
        });
      },
      select: function(event, ui) {
        return _this.selected_user_id = ui.item.id;
      }
    });
    this.$("#cerca_pro").autocomplete({
      source: function(request, response) {
        return $.getJSON('/api/autocomplete_pro.json?prefix=' + request.term, function(data) {
          var pro, pros, _i, _len, _ref;
          pros = [];
          _ref = data.list;
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            pro = _ref[_i];
            pros.push({
              label: pro.businessName,
              proId: pro.id,
              location: pro.location,
              pro: pro
            });
          }
          return response(pros);
        });
      },
      select: function(event, ui) {
        return _this.selected_user_id = ui.item.proId;
      }
    });
    this.$("#eventi-form").autocomplete({
      source: function(request, response) {
        return $.getJSON('/api/autocomplete_event.json?prefix=' + request.term, function(data) {
          var events, id, label, _ref;
          events = [];
          _ref = data.result;
          for (id in _ref) {
            label = _ref[id];
            events.push({
              label: label,
              eventId: id
            });
          }
          return response(events);
        });
      },
      select: function(event, ui) {
        event = new Event({
          id: ui.item.eventId
        });
        return event.fetch;
      }
    });
    this.$("#cerca_servizio").autocomplete({
      source: function(request, response) {
        return $.getJSON('/api/autocomplete_service.json?prefix=' + request.term, function(data) {
          var obj, services, _i, _len, _ref;
          services = [];
          _ref = data.result;
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            obj = _ref[_i];
            services.push({
              label: obj.description,
              serviceId: obj.id
            });
          }
          return response(services);
        });
      },
      select: function(event, ui) {
        return _this.selected_service_id = ui.item.serviceId;
      }
    });
    this.$("#cerca_strutture").autocomplete({
      source: function(request, response) {
        return $.getJSON('/api/autocomplete_business.json?prefix=' + request.term, function(data) {
          var id, label, places;
          places = [];
          for (id in data) {
            label = data[id];
            places.push({
              label: label,
              placeId: id
            });
          }
          return response(places);
        });
      },
      select: function(event, ui) {
        var place;
        place = new Place({
          id: ui.item.placeId
        });
        return place.fetch;
      }
    });
    this.$("#pro_categorie  ").autocomplete({
      source: function(request, response) {
        return response(_this.categories);
      },
      select: function(event, ui) {
        return _this.pro_category_id = ui.item.categoryId;
      }
    });
    return this.$("#pro_categorie").click(function(e) {
      return _this.$("#pro_categorie").autocomplete('search', ' ');
    });
  };

  MyHomeTabView.prototype.render = function() {
    Utils.log("Render di " + (this.slug()));
    this.setup_autocompletes();
    this.setup_map();
    if (this.collection.filters.page === 0) {
      this.$('.indietro').hide();
    } else {
      this.$('.indietro').show();
    }
    if (!this.collection.filters.per_page_multiplier) {
      this.collection.filters.per_page_multiplier = 1;
    }
    if ((this.collection.filters.per_page * this.collection.filters.per_page_multiplier) > this.collection.length) {
      this.$('.avanti').hide();
    } else {
      this.$('.avanti').show();
    }
    return this;
  };

  MyHomeTabView.prototype.openTooltip = function(object, marker) {
    var bubble_content;
    if (this.infoWindow != null) this.infoWindow.close();
    bubble_content = this.bubble_view().clone().removeClass('hidden').autoRender(this.data_for_object(object));
    this.infoWindow = new google.maps.InfoWindow({
      content: bubble_content.html()
    });
    google.maps.event.addListener(this.infoWindow, 'domready', function() {
      return $('.baloon').parent().css('overflow', 'visible');
    });
    return this.infoWindow.open(this.map, marker);
  };

  MyHomeTabView.prototype.setup_map = function() {
    var bounds;
    var _this = this;
    this.map = new google.maps.Map(this.$("#map").get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    this.$('#box-risultati').empty();
    bounds = new google.maps.LatLngBounds();
    this.collection.each(function(object) {
      var marker;
      marker = object.marker(_this.map);
      bounds.extend(object.latlng());
      google.maps.event.addListener(marker, 'click', function() {
        return _this.openTooltip(object, marker);
      });
      return _this.detail_view().clone().removeClass('hidden').autoRender(_this.data_for_object(object)).click(function() {
        return _this.openTooltip(object, marker);
      }).appendTo(_this.$('#box-risultati'));
    });
    if (this.collection.length > 1) {
      this.map.fitBounds(bounds);
    } else if (this.collection.length === 1) {
      this.map.setCenter(this.collection.at(0).latlng());
    }
    if (this.collection.length === 0) {
      return this.$('.no-results').clone().removeClass('hidden').appendTo('#box-risultati');
    }
  };

  return MyHomeTabView;

})();

var EventsView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

EventsView = (function() {

  __extends(EventsView, MyHomeTabView);

  function EventsView() {
    EventsView.__super__.constructor.apply(this, arguments);
  }

  EventsView.prototype.initialize = function() {
    var _this = this;
    this.current_user = AppController.current_user();
    this.collection = this.current_user.events();
    this.current_user.bind('change:lon', function() {
      if (_this.current_user.get("lat") && _this.current_user.get("lon")) {
        return _this.search_nearby();
      }
    });
    this.collection.unbind("reset");
    this.collection.bind("reset", function() {
      return _this.render();
    });
    this.el = $("#template_events-view-page").clone().removeClass("hidden").get(0);
    this.events = {
      "click #navigation .avanti": "next_page",
      "click #navigation .indietro": "previous_page",
      "click #search-nearby a": "search_nearby",
      "click #search-accepted a": "search_accepted",
      "click #search-mine a": "search_mine",
      "click #content-eventi .go": "search",
      "keyup #luoghi": "search_key",
      "keyup #sport": "search_key",
      "keyup #eventi-form": "search_key"
    };
    this.delegateEvents();
    this.search_nearby();
    return EventsView.__super__.initialize.apply(this, arguments);
  };

  EventsView.prototype.slug = function() {
    return "tab-eventi";
  };

  EventsView.prototype.search_key = function(e) {
    if (e.keyCode === 13) return this.search();
  };

  EventsView.prototype.next_page = function() {
    this.collection.next_page();
    return this.collection.fetch();
  };

  EventsView.prototype.previous_page = function() {
    this.collection.previous_page();
    this.collection.fetch();
    return false;
  };

  EventsView.prototype.search_accepted = function() {
    this.collection.set_filters({
      accepted: true,
      page: 0,
      per_page: 12
    });
    this.collection.fetch();
    return false;
  };

  EventsView.prototype.search_mine = function() {
    this.reset_form();
    this.collection.set_filters({
      mine: true,
      page: 0,
      per_page: 12
    });
    this.collection.fetch();
    return false;
  };

  EventsView.prototype.search_nearby = function() {
    this.reset_form();
    this.collection.set_filters({
      nearby: true,
      latitude: this.current_user.get("latitude"),
      longitude: this.current_user.get("longitude"),
      page: 0,
      per_page: 12
    });
    this.collection.fetch();
    return false;
  };

  EventsView.prototype.reset_form = function() {
    this.$("#luoghi").val("");
    this.$("#eventi-form").val("");
    return this.$("#sport").val("");
  };

  EventsView.prototype.search = function() {
    var address, filters;
    var _this = this;
    filters = {
      page: 0,
      per_page: 12
    };
    if (this.$("#sport").val().length) filters.sport_id = this.selected_sport_id;
    filters.name = this.$("#eventi-form").val();
    if (this.$("#sport").val().length) filters.sport_name = this.$("#sport").val();
    address = $("#luoghi").val();
    if (address.length) {
      Utils.geocode(address, function(coords) {
        if (coords != null) {
          filters.nearby = true;
          filters.latitude = coords.latitude;
          filters.longitude = coords.longitude;
          _this.collection.set_filters(filters);
          return _this.collection.fetch();
        } else {
          return $.jGrowl("Indirizzo non trovato!");
        }
      });
    } else {
      filters.nearby = true;
      filters.latitude = this.current_user.get("latitude");
      filters.longitude = this.current_user.get("longitude");
      this.collection.set_filters(filters);
      this.collection.fetch();
    }
    return false;
  };

  EventsView.prototype.render = function() {
    this.$("#search-nearby a, #search-accepted a, #search-mine a").removeClass("selected");
    if (this.collection.filters.mine) {
      this.$("#search-mine a").addClass('selected');
    } else if (this.collection.filters.accepted) {
      this.$("#search-accepted a").addClass('selected');
    } else {
      this.$("#search-nearby a").addClass('selected');
    }
    return EventsView.__super__.render.apply(this, arguments);
  };

  EventsView.prototype.detail_view = function() {
    return $("#template_events-view-results");
  };

  EventsView.prototype.bubble_view = function() {
    return $("#template_events-view-maps-bubble");
  };

  EventsView.prototype.data_for_object = function(event) {
    return event.data_for_render();
  };

  return EventsView;

})();

var PlacesView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

PlacesView = (function() {

  __extends(PlacesView, MyHomeTabView);

  function PlacesView() {
    PlacesView.__super__.constructor.apply(this, arguments);
  }

  PlacesView.prototype.initialize = function() {
    var _this = this;
    this.current_user = AppController.current_user();
    this.collection = new Places();
    this.current_user.bind('change:longitude', function() {
      if (_this.current_user.get("latitude") && _this.current_user.get("longitude")) {
        return _this.search_nearby();
      }
    });
    this.collection.bind("reset", function() {
      return _this.render();
    });
    this.el = $("#template_places-view-page").clone().removeClass("hidden").get(0);
    this.events = {
      "click #navigation .avanti": "next_page",
      "click #navigation .indietro": "previous_page",
      "click #search-nearby a": "search_nearby",
      "click #search-been a": "search_been",
      "click #search-favorites a": "search_favorites",
      "click #search-mine a": "search_mine",
      "click #go": "search",
      "click #invita": "invite_friends",
      "click .add_friendship_path": "add_friend",
      "click .remove_friendship_path": "remove_friend"
    };
    this.delegateEvents();
    this.search_nearby();
    return PlacesView.__super__.initialize.apply(this, arguments);
  };

  PlacesView.prototype.slug = function() {
    return "tab-places";
  };

  PlacesView.prototype.next_page = function() {
    this.collection.next_page();
    return this.collection.fetch();
  };

  PlacesView.prototype.previous_page = function() {
    this.collection.previous_page();
    return this.collection.fetch();
  };

  PlacesView.prototype.search_been = function() {
    this.collection.set_filters({
      been: true,
      page: 0,
      per_page: 8
    });
    this.collection.fetch();
    return false;
  };

  PlacesView.prototype.search_mine = function() {
    this.collection.set_filters({
      mine: true,
      page: 0,
      per_page: 8
    });
    this.collection.fetch();
    return false;
  };

  PlacesView.prototype.search_favorites = function() {
    this.collection.set_filters({
      favorites_nearby: true,
      page: 0,
      per_page: 8,
      latitude: this.current_user.get("latitude"),
      longitude: this.current_user.get("longitude")
    });
    this.collection.fetch();
    return false;
  };

  PlacesView.prototype.search_nearby = function() {
    this.collection.set_filters({
      latitude: this.current_user.get("latitude"),
      longitude: this.current_user.get("longitude"),
      page: 0,
      per_page: 8
    });
    this.collection.fetch();
    return false;
  };

  PlacesView.prototype.search = function() {
    var address, filters;
    var _this = this;
    filters = {
      page: 0,
      per_page: 8
    };
    if (this.$("#sport").val().length) filters.sport_id = this.selected_sport_id;
    if (this.$("#sport").val().length) filters.sport_name = this.$("#sport").val();
    filters.name = this.$("#cerca_strutture").val();
    address = $("#luoghi").val();
    if (address.length) {
      Utils.geocode(address, function(coords) {
        if (coords != null) {
          filters.latitude = coords.latitude;
          filters.longitude = coords.longitude;
          _this.collection.set_filters(filters);
          return _this.collection.fetch();
        } else {
          return $.jGrowl("Indirizzo non trovato!");
        }
      });
    } else {
      filters.latitude = this.current_user.get("latitude");
      filters.longitude = this.current_user.get("longitude");
      this.collection.set_filters(filters);
      this.collection.fetch();
    }
    return false;
  };

  PlacesView.prototype.render = function() {
    this.$("#search-nearby a, #search-been a, #search-favorites a, #search-mine a").removeClass("selected");
    if (this.collection.filters.been) {
      this.$("#search-been a").addClass('selected');
    } else if (this.collection.filters.mine) {
      this.$("#search-mine a").addClass('selected');
    } else if (this.collection.filters.favorites_nearby) {
      this.$("#search-favorites a").addClass('selected');
    } else {
      this.$("#search-nearby a").addClass('selected');
    }
    return PlacesView.__super__.render.apply(this, arguments);
  };

  PlacesView.prototype.detail_view = function() {
    return $("#template_places-view-results");
  };

  PlacesView.prototype.bubble_view = function() {
    return $("#template_places-view-maps-bubble");
  };

  PlacesView.prototype.data_for_object = function(place) {
    return place.data_for_render();
  };

  PlacesView.prototype.invite_friends = function() {
    return ApplicationScript.DialogInviteShow('INVITE/1', this.current_user.get('token'), '', 'full');
  };

  PlacesView.prototype.add_friend = function(e) {
    var _this = this;
    $.ajax({
      url: "/api/private/business_friendship_add/" + ($(e.currentTarget).attr('placeId')) + ".json",
      success: function(data) {
        $.jGrowl(I18n.t("global.place.friendship_requested"));
        return _this.collection.fetch();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  PlacesView.prototype.remove_friend = function(e) {
    var _this = this;
    $.ajax({
      url: "/api/private/business_friendship_remove/" + ($(e.currentTarget).attr('placeId')) + ".json",
      success: function(data) {
        $.jGrowl(I18n.t("global.place.friendship_rejected"));
        return _this.collection.fetch();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  return PlacesView;

})();

var NewPlaceSportView, NewPlaceView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

NewPlaceSportView = (function() {

  __extends(NewPlaceSportView, Backbone.View);

  function NewPlaceSportView() {
    NewPlaceSportView.__super__.constructor.apply(this, arguments);
  }

  NewPlaceSportView.prototype.initialize = function(ops) {
    this.place_sport = ops.place_sport;
    this.place = ops.place;
    this.place_view = ops.place_view;
    Utils.log(this.place_sport.attributes);
    this.el = $("#template-sport-place-view").clone().removeAttr("id").removeClass("hidden").get(0);
    this.$(".expand").hide();
    return this.delegateEvents({
      "click .dettagli a": "toggle",
      "click .flag1": "toggle_selection",
      "click .flag2": "toggle_selection",
      "click .flag3": "toggle_selection",
      "click .flag4": "toggle_selection",
      "click .flag5": "toggle_selection",
      "click #save-place-sport": "save_place_sport"
    });
  };

  NewPlaceSportView.prototype.toggle_selection = function(e) {
    var $el;
    $el = $(e.target);
    if ($el.attr("class").indexOf("dese") === -1) {
      $el.attr("class", $el.attr("class").replace("sele", "dese"));
    } else {
      $el.attr("class", $el.attr("class").replace("dese", "sele"));
    }
    return false;
  };

  NewPlaceSportView.prototype.toggle = function(e) {
    this.$(".dettagli a").toggleClass("open").toggleClass("closed");
    this.$(".expand").toggle();
    return false;
  };

  NewPlaceSportView.prototype.save_place_sport = function() {
    var _this = this;
    if (this.place.get('id')) {
      this._save_place_sport();
    } else {
      this.place.save(this.place_view.data_from_form(), {
        success: function() {
          return _this._save_place_sport();
        },
        error: function(model, errors) {
          return $.jGrowl(errors);
        }
      });
    }
    return false;
  };

  NewPlaceSportView.prototype._save_place_sport = function() {
    var _this = this;
    return this.place_sport.save({
      businessId: this.place.get('id'),
      infoDays: this.$("#giorni").val(),
      infoSchedule: this.$("#orari").val(),
      infoCosts: this.$("#costi").val(),
      flag1: this.$(".flag1").attr("class").indexOf("sele") >= 0,
      flag2: this.$(".flag2").attr("class").indexOf("sele") >= 0,
      flag3: this.$(".flag3").attr("class").indexOf("sele") >= 0,
      flag4: this.$(".flag4").attr("class").indexOf("sele") >= 0,
      flag5: this.$(".flag5").attr("class").indexOf("sele") >= 0
    }, {
      success: function() {
        _this.toggle();
        return _this.$('.removeSport').attr({
          'placeSportId': _this.place_sport.get('id')
        });
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
  };

  NewPlaceSportView.prototype.render = function() {
    var $el, i;
    for (i = 1; i <= 5; i++) {
      if (this.place_sport.get("flag" + i)) {
        $el = this.$(".flag" + i);
        $el.attr("class", $el.attr("class").replace("dese", "sele"));
      }
    }
    this.$("#giorni").val(this.place_sport.get("infoDays"));
    this.$("#orari").val(this.place_sport.get("infoSchedule"));
    this.$("#costi").val(this.place_sport.get("infoCosts"));
    this.$(".sportName").text(this.place_sport.get("sportName"));
    this.$(".removeSport").attr('placeSportId', this.place_sport.get('id'));
    return this;
  };

  return NewPlaceSportView;

})();

NewPlaceView = (function() {

  __extends(NewPlaceView, PageView);

  function NewPlaceView() {
    this.remove_sport_deferred = __bind(this.remove_sport_deferred, this);
    NewPlaceView.__super__.constructor.apply(this, arguments);
  }

  NewPlaceView.prototype.initialize = function(opts) {
    var _this = this;
    this.place = opts != null ? opts.place : new Place;
    this.place_sports = new PlaceSports([], {
      place_id: this.place.get('id')
    });
    this.remove_sport_queue = [];
    this.current_user = AppController.current_user();
    this.address_latlng = {};
    this.el = $("#template_new-place-view-page").clone().removeClass("hidden").get(0);
    if (opts) {
      this.$("h2.create").hide();
    } else {
      this.$("h2.edit").hide();
    }
    if (!this.place.isNew()) {
      this.place.fetch({
        success: function() {
          return _this.render();
        }
      });
      this.place_sports.fetch({
        success: function() {
          return _this.render();
        }
      });
    }
    this.sports = new Sports;
    this.sports.fetch({
      success: function() {
        _this.render();
        _this.$("#common-sports").css("display", "inline");
        return _this.$("#special-sports").css("display", "inline");
      }
    });
    return this.delegateEvents({
      "click #set_address": "geolocalize",
      "keyup #address": "geolocalize_key",
      "click #geolocalizzami": "geolocate_html5",
      "click #create-place": "save",
      "click #add-common-sport": "add_common_sport",
      "click #add-special-sport": "add_special_sport",
      "click .removeSport": "remove_sport"
    });
  };

  NewPlaceView.prototype.slug = function() {
    return "tab-new-place";
  };

  NewPlaceView.prototype.geolocalize_key = function(e) {
    if (e.keyCode === 13) return this.geolocalize();
  };

  NewPlaceView.prototype.geolocalize = function() {
    var _this = this;
    return Utils.geocode(this.$("#address").val(), function(geoResult) {
      if (geoResult) {
        _this.map.setCenter(geoResult.latlng);
        _this.marker.setPosition(geoResult.latlng);
        return _this.address_latlng = geoResult;
      } else {
        return $.jGrowl(I18n.t("global.geocode_fail"));
      }
    });
  };

  NewPlaceView.prototype.geolocate_html5 = function() {
    var _this = this;
    if (navigator.geolocation == null) return;
    return navigator.geolocation.getCurrentPosition(function(position) {
      var location;
      location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      _this.map.setCenter(location);
      _this.marker || (_this.marker = new google.maps.Marker({
        map: _this.map,
        title: 'Posizione',
        position: location
      }));
      _this.marker.setPosition(location);
      _this.user_location = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude
      };
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return this.$("#address").val(results[0].formatted_address);
        }
      });
    }, function(error) {
      return $.jGrowl(error);
    });
  };

  NewPlaceView.prototype.change_map_location = function(e) {
    var coords, latlng;
    coords = $(e.target).val().split("|");
    latlng = new google.maps.LatLng(coords[0], coords[1]);
    this.$("#address").val(coords[2]);
    this.address_latlng = {
      latitude: coords[0],
      longitude: coords[1]
    };
    this.map.setCenter(latlng);
    this.marker || (this.marker = new google.maps.Marker({
      map: this.map,
      title: 'Posizione',
      position: this.current_user.latlng()
    }));
    return this.marker.setPosition(latlng);
  };

  NewPlaceView.prototype.setup_map = function() {
    var self;
    this.map = new google.maps.Map(this.$("#map").get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    this.marker = new google.maps.Marker({
      map: this.map,
      title: 'Mia posizione',
      position: this.current_user.latlng()
    });
    this.marker.setDraggable(true);
    self = this;
    return google.maps.event.addListener(this.marker, 'dragend', function() {
      var location;
      location = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
      self.address_latlng = {
        latitude: this.getPosition().lat(),
        longitude: this.getPosition().lng()
      };
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return this.$("#address").val(results[0].formatted_address);
        }
      });
    });
  };

  NewPlaceView.prototype.render = function() {
    var _this = this;
    this.setup_map();
    this.$("#special-sports, #common-sports, #sport-praticabili").empty();
    Utils.log("Render di " + (this.slug()));
    this.$("#businessName").val(this.place.get("businessName"));
    this.$("#description").val(this.place.get("description"));
    this.$("#phone").val(this.place.get("phone"));
    this.$("#email").val(this.place.get("email"));
    this.$("#website").val(this.place.get("website"));
    this.sports.each(function(sport) {
      var $el;
      $el = $("<option value='" + (sport.get('id')) + "'>" + (sport.get('name')) + "</option>");
      if (sport.get('flagImportance') === 3) {
        return $el.appendTo(_this.$("#special-sports"));
      } else {
        return $el.appendTo(_this.$("#common-sports"));
      }
    });
    if (this.place.get("location") != null) {
      this.address_latlng = this.place.get("location");
      this.$("#address").val(this.place.get("location").address);
      this.marker || (this.marker = new google.maps.Marker({
        map: this.map,
        title: 'Posizione',
        position: this.place.latlng()
      }));
      this.marker.setPosition(this.place.latlng());
      this.map.setCenter(this.place.latlng());
    }
    this.place_sports.each(function(place_sport) {
      var view;
      view = new NewPlaceSportView({
        place_sport: place_sport,
        place: _this.place,
        place_view: _this
      });
      return _this.$("#sport-praticabili").append(view.render().el);
    });
    return this;
  };

  NewPlaceView.prototype.add_dropbox_sport = function(dropbox) {
    var selected;
    selected = $(dropbox).find("option:selected");
    return this.add_place_sport({
      sportName: selected.text(),
      sportId: selected.val()
    });
  };

  NewPlaceView.prototype.add_special_sport = function() {
    this.add_dropbox_sport("#special-sports");
    return false;
  };

  NewPlaceView.prototype.add_common_sport = function() {
    this.add_dropbox_sport("#common-sports");
    return false;
  };

  NewPlaceView.prototype.add_place_sport = function(place_sport) {
    var view;
    if (!(place_sport instanceof PlaceSport)) {
      place_sport.businessId = this.place.get('id');
      place_sport = new PlaceSport(place_sport);
    }
    view = new NewPlaceSportView({
      place_sport: place_sport,
      place: this.place,
      place_view: this
    });
    view.toggle();
    return this.$("#sport-praticabili").append(view.render().el);
  };

  NewPlaceView.prototype.remove_sport = function(e) {
    var place_sport;
    place_sport = new PlaceSport();
    place_sport.set({
      'id': $(e.currentTarget).attr('placeSportId')
    }, {
      silent: true
    });
    this.remove_sport_queue.push(place_sport);
    return $(e.currentTarget).parent().parent().remove();
  };

  NewPlaceView.prototype.remove_sport_deferred = function(success) {
    var place_sport;
    var _this = this;
    if (this.remove_sport_queue.length) {
      place_sport = this.remove_sport_queue.shift();
      return place_sport.destroy({
        success: function() {
          if (_this.remove_sport_queue.length === 0) {
            return success();
          } else {
            return _this.remove_sport_deferred(success);
          }
        },
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    } else {
      return success();
    }
  };

  NewPlaceView.prototype.data_from_form = function() {
    return {
      businessName: this.$("#businessName").val(),
      description: this.$("#description").val(),
      phone: this.$("#phone").val(),
      email: this.$("#email").val(),
      website: this.$("#website").val(),
      location: {
        address: this.$("#address").val(),
        longitude: this.address_latlng.longitude,
        latitude: this.address_latlng.latitude
      }
    };
  };

  NewPlaceView.prototype.validate = function(success) {
    var _this = this;
    if (this.place.isNew()) {
      return $.jGrowl(I18n.t("global.place.errors.min_one_place_sport"));
    } else {
      this.place_sports = new PlaceSports([], {
        place_id: this.place.get('id')
      });
      return this.place_sports.fetch({
        success: function() {
          if (_this.place_sports.length === 0) {
            return $.jGrowl(I18n.t("global.place.errors.min_one_place_sport"));
          } else {
            return success();
          }
        },
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    }
  };

  NewPlaceView.prototype.save = function() {
    var _this = this;
    this.remove_sport_deferred(function() {
      return _this.validate(function() {
        return _this.place.save(_this.data_from_form(), {
          success: function() {
            return _this.save_profile_photo(function() {
              return document.location = "#/my_home/places/" + (_this.place.get('id'));
            });
          },
          error: function(model, errors) {
            return $.jGrowl(errors);
          }
        });
      });
    });
    return false;
  };

  NewPlaceView.prototype.save_profile_photo = function(success) {
    var _this = this;
    if (this.$('input[name="upload_picture"]').val().length > 0) {
      return $.ajax({
        url: "/api/private/createUploadBusinessProfilePicture.json",
        dataType: 'text',
        success: function(data) {
          var url;
          url = data.replace(/http:\/\/.*?\//, '/');
          return _this.$('#upload-picture').attr('action', url).ajaxForm({
            dataType: 'text',
            data: {
              businessId: _this.place.get('id'),
              defaultImg: true
            },
            iframe: true,
            success: function(data, status, xhr) {
              var oldUrl;
              Utils.log("Inviato con successo!");
              oldUrl = _this.place.get("urlImg");
              return _this.place.fetch({
                success: function() {
                  if (oldUrl === _this.place.get("urlImg")) {
                    Utils.log("Inviato con errore! oldUrl = " + oldUrl);
                    $.jGrowl(I18n.t("settings.step1.upload_error"));
                    return document.location = "#/my_home/places/" + (_this.place.get('id'));
                  } else {
                    if ($.isFunction(success)) return success();
                  }
                }
              });
            },
            error: function(data, status, xhr) {
              Utils.log("Inviato con errore!");
              $.jGrowl(I18n.t("settings.step1.upload_error"));
              return document.location = "#/my_home/places/" + (_this.place.get('id'));
            }
          }).submit();
        },
        error: function() {
          $.jGrowl(I18n.t("settings.step1.upload_error"));
          return document.location = "#/my_home/places/" + (this.place.get('id'));
        }
      });
    } else {
      if ($.isFunction(success)) return success();
    }
  };

  return NewPlaceView;

})();

var EventPlaceView, PlaceView, SportPlaceView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SportPlaceView = (function() {

  __extends(SportPlaceView, Backbone.View);

  function SportPlaceView() {
    SportPlaceView.__super__.constructor.apply(this, arguments);
  }

  SportPlaceView.prototype.initialize = function(ops) {
    this.sport = ops.sport;
    this.el = $("#template-profilo-struttura-sport-show").clone().removeAttr("id").removeClass("hidden").autoRender(this.sport.attributes).get(0);
    this.$(".expand").hide();
    return this.delegateEvents({
      "click .dettagli a": "toggle"
    });
  };

  SportPlaceView.prototype.toggle = function(e) {
    $(e.target).toggleClass("open").toggleClass("closed");
    this.$(".expand").toggle();
    return false;
  };

  SportPlaceView.prototype.render = function() {
    var $el, i;
    for (i = 1; i <= 5; i++) {
      if (this.sport.get("flag" + i)) {
        $el = this.$(".flag" + i);
        $el.attr("class", $el.attr("class").replace("dese", "sele"));
      }
    }
    return this;
  };

  return SportPlaceView;

})();

EventPlaceView = (function() {

  __extends(EventPlaceView, Backbone.View);

  function EventPlaceView() {
    EventPlaceView.__super__.constructor.apply(this, arguments);
  }

  EventPlaceView.prototype.initialize = function(ops) {
    this.event = ops.event;
    this.el = $("#template-profilo-event-user-show").clone().removeAttr("id").removeClass("hidden").autoRender(this.event.data_for_render()).get(0);
    this.$(".expand").hide();
    return this.delegateEvents({
      "click .dettagli-eventi a": "toggle"
    });
  };

  EventPlaceView.prototype.toggle = function(e) {
    var $mapContainer, bubble_content;
    $(e.target).toggleClass("open").toggleClass("closed");
    this.$(".expand").toggle();
    if (this.$(".expand").is(":visible")) {
      $mapContainer = $("<div/>").css({
        height: 300
      }).appendTo(this.$(".expand"));
      this.map = new google.maps.Map($mapContainer.get(0), {
        zoom: 14,
        center: this.event.latlng(),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      this.marker = new google.maps.Marker({
        map: this.map,
        title: 'Posizione',
        position: this.event.latlng()
      });
      bubble_content = $("#template_events-view-maps-bubble").clone().removeClass('hidden').autoRender(this.event.data_for_render());
      this.infoWindow = new google.maps.InfoWindow({
        content: bubble_content.html()
      });
      this.infoWindow.open(this.map, this.marker);
    } else {
      this.$(".expand").empty();
    }
    return false;
  };

  EventPlaceView.prototype.render = function() {
    if (this.event.my_status() === "owner") {
      $("<a class='modifica'/>").attr("href", "#/my_home/events/" + (this.event.get("id")) + "/edit").appendTo(this.$(".risposte"));
    } else {
      $("<span class='modifica-disattivato'/>").appendTo(this.$(".risposte"));
    }
    return this;
  };

  return EventPlaceView;

})();

PlaceView = (function() {

  __extends(PlaceView, PageView);

  function PlaceView() {
    PlaceView.__super__.constructor.apply(this, arguments);
  }

  PlaceView.prototype.tagName = "div";

  PlaceView.prototype.initialize = function(options) {
    var _this = this;
    this.place_id = options.id;
    this.place = new Place({
      id: this.place_id
    });
    this.sports = new PlaceSports([], {
      place_id: this.place_id
    });
    this.events = new PlaceEvents([], {
      place_id: this.place_id
    });
    this.messages = new ProfileMessages([], {
      user_id: this.place_id
    });
    this.friends = new Friendships([], {
      user_id: this.place_id
    });
    this.locations = new UserLocations([], {
      user_id: this.place_id
    });
    this.photos = new ProfilePhotos([], {
      user_id: this.place_id
    });
    this.videos = new ProfileVideos([], {
      user_id: this.place_id
    });
    this.fetch_count = 0;
    this.place.fetch({
      success: function() {
        if (!_this.place.attributes.location) {
          $.jGrowl(I18n.t("global.place.not_existing"));
          document.location = "#/my_home/places";
          return;
        }
        return _this.fetch_count++ && _this.render();
      }
    });
    this.sports.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.events.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.messages.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.friends.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.locations.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.photos.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.videos.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    $('#save-picture-photo').hide();
    this.current_user = AppController.current_user();
    return this.delegateEvents({
      "click #send-new-message": "post_message",
      "click .back": "back",
      "click #add-photo-button": "toggle_photo_form",
      "click #add-video-button": "toggle_video_form",
      "click #cancel-photo-button": "toggle_photo_form",
      "click #cancel-video-button": "toggle_video_form",
      "click #save-video": "save_video",
      "click #save-photo": "save_photo",
      "hover #stairs span": "hover_stars",
      "mouseout #stairs span": "mouse_out",
      "click #stairs span": "give_feedback",
      "click #upload-picture": "show_upload_button"
    });
  };

  PlaceView.prototype.show_upload_button = function() {
    return $('#save-picture-photo').show();
  };

  PlaceView.prototype.hover_stars = function(e) {
    this.$("#stairs span").removeClass("selected");
    return $(e.target).prevAll().add(e.target).addClass("selected");
  };

  PlaceView.prototype.mouse_out = function(e) {
    var $el;
    this.$("#stairs span").removeClass("selected");
    $el = this.$("#stairs span:nth(" + (this.feedback - 1) + ")");
    return $el.prevAll().add($el[0]).addClass("selected");
  };

  PlaceView.prototype.give_feedback = function(e) {
    var _this = this;
    this.feedback = $(e.target).prevAll().length + 1;
    return $.ajax({
      type: "post",
      url: "/api/private/feedback.json",
      data: {
        userId: this.place_id,
        rating: this.feedback
      },
      success: function() {
        return $.jGrowl("E' stato dato un punteggio di " + _this.feedback + "!");
      }
    });
  };

  PlaceView.prototype.toggle_video_form = function() {
    this.$("#add-video, #add-video-button}").toggle();
    return false;
  };

  PlaceView.prototype.toggle_photo_form = function() {
    this.$("#add-photo, #add-photo-button").toggle();
    return false;
  };

  PlaceView.prototype.save_photo = function() {
    var _this = this;
    if (this.$('#photo-upload input[name="profile_picture"]').val().length > 0) {
      $.ajax({
        url: "/api/private/createUploadBusinessProfilePicture.json",
        dataType: 'text',
        success: function(data) {
          var url;
          url = data.replace(/http:\/\/.*?\//, '/');
          return _this.$('#photo-upload').append("<input type='hidden' name='businessId' value='" + _this.place_id + "'/>").attr('action', url).ajaxForm({
            dataType: 'text',
            iframe: true,
            success: function(data, status, xhr) {
              Utils.log("Inviato con successo!");
              _this.photos.fetch({
                success: function() {
                  return _this.render();
                }
              });
              return _this.toggle_photo_form();
            }
          }).submit();
        },
        error: function() {
          return $.jGrowl(I18n.t("settings.step1.upload_error"));
        }
      });
    }
    return false;
  };

  PlaceView.prototype.save_video = function() {
    var video;
    var _this = this;
    if (this.$("#video-url").val().trim().length > 0 && this.$("#video-url").val() !== I18n.t('users.show.youtube_url')) {
      video = new PlaceProfileVideo;
      video.place_id = this.place_id;
      return video.save({
        url: this.$("#video-url").val(),
        type: 0
      }, {
        success: function() {
          return _this.videos.fetch({
            success: function() {
              return _this.render();
            }
          });
        }
      });
    }
  };

  PlaceView.prototype.back = function() {
    return document.location = "#/my_home/users";
  };

  PlaceView.prototype.slug = function() {
    return "tab-place-show";
  };

  PlaceView.prototype.data = function() {
    return this.place.data_for_render({
      image_size: 105
    });
  };

  PlaceView.prototype.render = function() {
    var sport;
    var _this = this;
    if (this.fetch_count >= 8) {
      this.owner = true;
      $(this.el).empty().append($("#template_show_place_view-page").clone().removeClass("hidden").autoRender(this.data()));
      if (!this.data().website) this.$('p.website_container').hide();
      this.init_map();
      this.map.setCenter(this.place.latlng());
      this.marker = new google.maps.Marker({
        map: this.map,
        title: 'Posizione',
        position: this.place.latlng()
      });
      sport = this.sports.detect(function(sport) {
        return sport.get('levelDescription') && sport.get('levelDescription').length > 0;
      });
      if (sport != null) {
        this.$("#messaggio").empty().append($("<span/>").addClass("sport").text(sport.get('sportName') + ": ")).append($("<span/>").text(sport.get('levelDescription')));
      }
      this.sports.each(function(sport) {
        var view;
        view = new SportPlaceView({
          sport: sport
        });
        return _this.$("#sports-list").append(view.render().el);
      });
      this.events.each(function(event) {
        var view;
        view = new EventUserView({
          event: event,
          from_place: true
        });
        return _this.$("#events-list").append(view.render().el);
      });
      if (this.events.length === 0) {
        this.$("#events-list").text(I18n.t("places.show.no_events"));
      }
      this.comments_container = this.$("#commenti");
      this.messages.each(function(message) {
        var view;
        view = new ProfileMessageView({
          message: message
        });
        return _this.comments_container.append(view.render().el);
      });
      this.friends = new Friendships(this.friends.filter(function(friend) {
        return friend.get('accepted');
      }), {
        user_id: this.place_id
      });
      this.friends.each(function(friend) {
        return $("<li class='tipsy-n'><a href='" + (friend.detail_path()) + "'><img src='" + (friend.get('friend').urlImg) + "=s50-c?imgmax=50&crop=1'/></a></li>").attr("title", friend.get('friend').name).appendTo(_this.$("#amici ul"));
      });
      if (this.friends.length === 0) {
        this.$("#amici ul").text(I18n.t("places.show.no_friends"));
      }
      this.photos.each(function(image) {
        var $el;
        $el = $("<li><a href='" + (image.get('url')) + "' class='highslide' onclick='return hs.expand(this)'><img src='" + (image.get('url')) + "=s70-c' height='70'/></a></li>").appendTo(_this.$("#foto ul"));
        if (_this.owner) {
          return $("<a href='#' class='delete'></a>").text(I18n.t("places.show.remove")).appendTo($el).click(function() {
            image.destroy({
              success: function() {
                return $el.remove();
              }
            });
            return false;
          });
        }
      });
      if (this.photos.length === 0) {
        this.$("#foto ul").text(I18n.t("places.show.no_photos"));
      }
      this.videos.each(function(video) {
        var $el, video_url;
        if (video.get('oembed') && video.get('oembed').title) {
          if (video.get('url').match(/youtube/)) {
            video_url = video.get('url').replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/") + "?rel=0&amp;wmode=transparent";
          }
          if (video.get('url').match(/vimeo/)) {
            video_url = video.get('url').replace("http://vimeo.com/", "http://vimeo.com/moogaloop.swf?&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&amp;clip_id=");
          }
          $el = $("<li class='tipsy-n'><a href='" + video_url + "' onclick=\"return hs.htmlExpand(this, {objectType: 'iframe', width: 480, height: 385, allowSizeReduction: false, wrapperClassName: 'draggable-header no-footer', preserveContent: false, objectLoadTime: 'after'})\" class='highslide'><img src='" + (video.thumb_url()) + "' width='93' height='70'/></a></li>").attr("title", video.get('oembed').title).appendTo(_this.$("#video ul"));
          if (_this.owner) {
            return $("<a href='#' class='delete'></a>").text(I18n.t("places.show.remove")).appendTo($el).click(function() {
              video.destroy({
                success: function() {
                  return $el.remove();
                }
              });
              return false;
            });
          } else {
            return _this.videos.length -= 1;
          }
        }
      });
      if (this.videos.length === 0) {
        this.$("#video ul").text(I18n.t("places.show.no_videos"));
      }
      if (this.owner) return this.$("#add-photo-button, #add-video-button").show();
    }
  };

  PlaceView.prototype.post_message = function(e) {
    var message;
    var _this = this;
    message = new ProfileMessage;
    Utils.log({
      message: this.$("#new-message").val(),
      playerIdReceiver: this.place_id,
      privateMessage: this.$("#private-message").is(":checked")
    });
    message.save({
      message: this.$("#new-message").val(),
      playerIdReceiver: this.place_id,
      privateMessage: this.$("#private-message").is(":checked")
    }, {
      success: function() {
        var view;
        _this.$("#new-message").val("");
        view = new ProfileMessageView({
          message: message
        }).render();
        return _this.comments_container.prepend(view.el);
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
    return false;
  };

  PlaceView.prototype.init_map = function() {
    var height;
    height = this.$("#cs").height();
    return this.map = new google.maps.Map(this.$("#map").css({
      height: height
    }).get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  };

  return PlaceView;

})();

var EventProView, ProView, ProfileMessageView, ServiceProView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

ProfileMessageView = (function() {

  __extends(ProfileMessageView, Backbone.View);

  function ProfileMessageView() {
    ProfileMessageView.__super__.constructor.apply(this, arguments);
  }

  ProfileMessageView.prototype.tagName = "div";

  ProfileMessageView.prototype.events = {
    "click .reply": "toggle_reply_box",
    "click .delete": "delete_comment",
    "submit #post-comment": "post_comment"
  };

  ProfileMessageView.prototype.initialize = function(opts) {
    this.message = opts.message;
    return this.owner = opts.owner;
  };

  ProfileMessageView.prototype.render = function() {
    var $inner, message, view, _i, _len, _ref;
    $inner = $("#template_show_event_view-message-page").clone().removeAttr("id").removeClass("hidden").autoRender({
      message: this.message.get("message"),
      date: Date.parse(this.message.get("date")).strftime(Utils.date_format($.cookie("lang"))),
      name: this.message.get("playerSender").name,
      image: this.message.get("playerSender").urlImg + "=s48-c?imgmax=48&crop=1",
      id: this.message.get("id"),
      user_details_path: this.message.get("playerSender").category === 0 ? "#/my_home/users/" + (this.message.get("playerIdSender")) : "#/my_home/pros/" + (this.message.get("playerIdSender")),
      'private': this.message.get("privateMessage") ? " (" + (I18n.t("messages.private")) + ")" : "",
      privateClass: this.message.get("privateMessage") ? " message-private " : ""
    });
    this.comments_container = $("#commenti", $inner);
    $(this.el).empty().append($inner);
    if (this.message.get("reply_to") != null) {
      this.$(".reply, .reply-box").remove();
    }
    if (this.message.get("playerSender").id !== AppController.current_user().get("id") && !this.owner) {
      this.$(".delete").remove();
    }
    if (this.message.get("playerSubMessageList") != null) {
      _ref = this.message.get("playerSubMessageList");
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        message = _ref[_i];
        message = new ProfileMessage(_.extend(ProfileMessage.prototype.parse(message), {
          reply_to: this.message.get("id")
        }));
        view = new ProfileMessageView({
          message: message,
          owner: this.owner
        }).render();
        Utils.log(message, this.comments_container.length, view.el);
        this.comments_container.append(view.el);
      }
    }
    return this;
  };

  ProfileMessageView.prototype.toggle_reply_box = function() {
    this.$(".reply-box").toggle();
    return false;
  };

  ProfileMessageView.prototype.post_comment = function() {
    var message;
    var _this = this;
    message = new ProfileMessage({
      reply_to: this.message.get("id")
    });
    message.save({
      message: this.$(".comment").val()
    }, {
      success: function() {
        var view;
        _this.$(".comment").val("");
        view = new ProfileMessageView({
          message: message,
          owner: _this.owner
        }).render();
        return _this.comments_container.append(view.el);
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
    return false;
  };

  ProfileMessageView.prototype.delete_comment = function() {
    var _this = this;
    this.message.destroy({
      success: function() {
        return $(_this.el).remove();
      }
    });
    return false;
  };

  ProfileMessageView.prototype.toJSON = function() {
    return {
      message: this.attributes.message
    };
  };

  return ProfileMessageView;

})();

EventProView = (function() {

  __extends(EventProView, Backbone.View);

  function EventProView() {
    EventProView.__super__.constructor.apply(this, arguments);
  }

  EventProView.prototype.initialize = function(ops) {
    this.event = ops.event;
    this.pro_id = ops.pro_id;
    this.el = $("#template-profilo-event-pro-show").clone().removeAttr("id").removeClass("hidden").autoRender(this.event.data_for_render()).get(0);
    this.$(".expand").hide();
    return this.delegateEvents({
      "click .dettagli-eventi a": "toggle"
    });
  };

  EventProView.prototype.toggle = function(e) {
    var $mapContainer, bubble_content;
    $(e.target).toggleClass("open").toggleClass("closed");
    this.$(".expand").toggle();
    if (this.$(".expand").is(":visible")) {
      $mapContainer = $("<div/>").css({
        height: 300
      }).appendTo(this.$(".expand"));
      this.map = new google.maps.Map($mapContainer.get(0), {
        zoom: 14,
        center: this.event.latlng(),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      this.marker = new google.maps.Marker({
        map: this.map,
        title: 'Posizione',
        position: this.event.latlng()
      }, bubble_content = $("#template_events-view-maps-bubble").clone().removeClass('hidden').autoRender(this.event.data_for_render()), parseInt(this.pro_id) !== parseInt(AppController.current_user().get("id")) ? ($(".private_actions", bubble_content).hide(), $(".public_view", bubble_content).removeClass('hidden')) : void 0);
      this.infoWindow = new google.maps.InfoWindow({
        content: bubble_content.html()
      });
      this.infoWindow.open(this.map, this.marker);
    } else {
      this.$(".expand").empty();
    }
    return false;
  };

  EventProView.prototype.render = function() {
    if (this.event.my_status() === "owner") {
      $("<a class='modifica'/>").attr("href", "#/my_home/events/" + (this.event.get("id")) + "/edit").appendTo(this.$(".risposte"));
    } else {
      $("<span class='modifica-disattivato'/>").appendTo(this.$(".risposte"));
    }
    return this;
  };

  return EventProView;

})();

ServiceProView = (function() {

  __extends(ServiceProView, Backbone.View);

  function ServiceProView() {
    this.openTooltip = __bind(this.openTooltip, this);
    ServiceProView.__super__.constructor.apply(this, arguments);
  }

  ServiceProView.prototype.initialize = function(ops) {
    this.service = ops.service;
    this.el = $("#template-profilo-sport-pro-show").clone().removeAttr("id").removeClass("hidden").autoRender(this.service.attributes, {
      ".serviceName": "serviceName",
      ".sportName": {
        "sportName <- sportNames": {
          '.': function(a) {
            return "" + (a.item.name.escape());
          }
        }
      }
    }).get(0);
    return this.delegateEvents({
      "click .dettagli a": "toggle"
    });
  };

  ServiceProView.prototype.toggle = function(e) {
    var $mapContainer, bounds, locations, name;
    var _this = this;
    $(e.target).toggleClass("open").toggleClass("closed");
    this.$(".expand").toggle();
    if (this.$(".expand").is(":visible")) {
      $mapContainer = this.$(".expand .map").css({
        width: 455
      }).css({
        marginTop: 5
      });
      this.map = new google.maps.Map($mapContainer.get(0), {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      locations = this.service.get('locations');
      bounds = new google.maps.LatLngBounds();
      name = "" + (this.service.get('serviceName'));
      _.each(locations, function(location) {
        var data, location_pro, marker;
        location_pro = new LocationPro(location);
        data = {
          name: name,
          address: location_pro.get("location").address
        };
        marker = new google.maps.Marker({
          map: _this.map,
          position: location_pro.latlng()
        });
        bounds.extend(location_pro.latlng());
        _this.map.setCenter(location_pro.latlng());
        return google.maps.event.addListener(marker, 'click', function() {
          return _this.openTooltip(data, marker);
        });
      });
      if (locations.length > 1) this.map.fitBounds(bounds);
    } else {
      this.$(".expand .map").empty();
    }
    return false;
  };

  ServiceProView.prototype.openTooltip = function(data, marker) {
    var bubble_content;
    bubble_content = $("#template-profilo-service-bubble-pro-show").clone().removeClass('hidden').autoRender(data);
    bubble_content.find('.baloon').css({
      paddingTop: 10
    });
    if (this.infoWindow != null) this.infoWindow.close();
    this.infoWindow = new google.maps.InfoWindow({
      content: bubble_content.html()
    });
    return this.infoWindow.open(this.map, marker);
  };

  ServiceProView.prototype.render = function() {
    this.$(".expand").hide();
    return this;
  };

  return ServiceProView;

})();

ProView = (function() {

  __extends(ProView, PageView);

  function ProView() {
    ProView.__super__.constructor.apply(this, arguments);
  }

  ProView.prototype.tagName = "div";

  ProView.prototype.hover_stars = function(e) {
    this.$("#stairs span").removeClass("selected");
    return $(e.target).prevAll().add(e.target).addClass("selected");
  };

  ProView.prototype.give_feedback = function(e) {
    var voto;
    var _this = this;
    voto = $(e.target).prevAll().length + 1;
    return $.ajax({
      type: "post",
      url: "/api/private/feedback.json",
      data: {
        userId: this.pro_id,
        rating: voto
      },
      success: function(data, textStatus, jqXHR) {
        _this.pro.set({
          rating: data.rating
        });
        _this.pro.set({
          ratingReliabilityTotal: data.ratingReliabilityTotal
        });
        $.jGrowl("E' stato dato un punteggio di " + voto + "!");
        return _this.render();
      }
    });
  };

  ProView.prototype.initialize = function(options) {
    var _this = this;
    this.pro_id = options.id;
    this.owner = parseInt(this.pro_id) === parseInt(AppController.current_user().get("id"));
    this.pro = new Pro({
      id: this.pro_id
    });
    this.locations = new ProLocations([], {
      pro_id: this.pro_id
    });
    this.services = new ProServices([], {
      pro_id: this.pro_id
    });
    this.events = new ProEvents([], {
      pro_id: this.pro_id
    });
    this.messages = new ProfileMessages([], {
      user_id: this.pro_id
    });
    this.friends = new Friendships([], {
      user_id: this.pro_id
    });
    this.photos = new ProfilePhotos([], {
      user_id: this.pro_id
    });
    this.videos = new ProfileVideos([], {
      user_id: this.pro_id
    });
    this.fetch_count = 0;
    this.pro.fetch({
      success: function() {
        if (!(_this.pro.attributes && _this.pro.attributes.registrationComplete)) {
          $.jGrowl(I18n.t("global.pro.not_existing"));
          document.location = "#/my_home/pros";
          return;
        }
        return _this.fetch_count++ && _this.render();
      }
    });
    this.services.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.locations.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.events.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.messages.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.friends.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.photos.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.videos.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.current_user = AppController.current_user();
    return this.delegateEvents({
      "submit #post-comment": "post_message",
      "hover #stairs span": "hover_stars",
      "click #stairs span": "give_feedback",
      "click #send-new-message": "post_message",
      "click #add-photo-button": "toggle_photo_form",
      "click #add-video-button": "toggle_video_form",
      "click #cancel-photo-button": "toggle_photo_form",
      "click #cancel-video-button": "toggle_video_form",
      "click #save-video": "save_video",
      "click #save-photo": "save_photo"
    });
  };

  ProView.prototype.toggle_video_form = function() {
    return this.$("#add-video, #add-video-button}").toggle();
  };

  ProView.prototype.toggle_photo_form = function() {
    return this.$("#add-photo, #add-photo-button").toggle();
  };

  ProView.prototype.save_photo = function() {
    var _this = this;
    if (this.$('input[name="profile_picture"]').val().length > 0) {
      $.ajax({
        url: "/api/private/createUploadProfilePicture",
        dataType: 'text',
        success: function(data) {
          var url;
          url = data.replace(/http:\/\/.*?\//, '/');
          return _this.$('#photo-upload').attr('action', url).ajaxForm({
            dataType: 'text',
            iframe: true,
            success: function(data, status, xhr) {
              Utils.log("Inviato con successo!");
              _this.photos.fetch({
                success: function() {
                  return _this.render();
                }
              });
              return _this.toggle_photo_form();
            }
          }).submit();
        },
        error: function() {
          return $.jGrowl(I18n.t("settings.step1.upload_error"));
        }
      });
    }
    return false;
  };

  ProView.prototype.save_video = function() {
    var video;
    var _this = this;
    if (this.$("#video-url").val().trim().length > 0 && this.$("#video-url").val() !== I18n.t('users.show.youtube_url')) {
      video = new ProfileVideo;
      return video.save({
        url: this.$("#video-url").val()
      }, {
        success: function() {
          return _this.videos.fetch({
            success: function() {
              return _this.render();
            }
          });
        }
      });
    }
  };

  ProView.prototype.slug = function() {
    return "tab-pro-show";
  };

  ProView.prototype.data = function() {
    return this.pro.data_for_render({
      image_size: 105
    });
  };

  ProView.prototype.render = function() {
    var bounds, has_services;
    var _this = this;
    if (this.owner) $("#header #menu #myprofile a").addClass("menu-selected");
    if (this.fetch_count >= 8) {
      $(this.el).empty().append($("#template_show_pro_view-page").clone().removeClass("hidden").autoRender(this.data()));
      if (!this.data().website) this.$('p.website_container').hide();
      this.init_map();
      if (this.owner) this.$("#c1 .aggiungi, #c3 .distance").remove();
      this.$("#services-list").empty();
      bounds = new google.maps.LatLngBounds();
      this.map.setCenter(this.pro.latlng());
      this.locations.each(function(location) {
        var marker, services, title;
        location.attributes.address = location.attributes.location.address;
        location.attributes.services = [];
        _.each(location.get("serviceIdsList"), function(serviceId) {
          var locations, service;
          service = _this.services.detect(function(service) {
            return service.get("serviceId") === serviceId;
          });
          if (service != null) {
            service.set({
              sportNames: _.map(service.get('sportsMap'), function(sport) {
                return {
                  name: sport
                };
              })
            });
            locations = service.get('locations') || [];
            location.attributes.services.push(service.escape('serviceName'));
            if (!_.contains(locations, location.attributes)) {
              locations.push(location.attributes);
            }
            return service.set({
              locations: locations
            });
          }
        });
        services = location.get('services');
        if (services.length) {
          title = _.reduce(_.rest(services), function(memo, service) {
            return memo + ", " + service;
          }, _.first(services));
        } else {
          title = "";
        }
        marker = new google.maps.Marker({
          map: _this.map,
          position: location.latlng(),
          title: title
        });
        return bounds.extend(location.latlng());
      });
      if (this.locations.length > 1) this.map.fitBounds(bounds);
      has_services = false;
      this.services.each(function(service) {
        var view;
        view = new ServiceProView({
          service: service
        });
        if ((service.get("locations") != null) && service.get("locations").length > 0) {
          _this.$("#services-list").append(view.render().el);
          return has_services = true;
        }
      });
      if (!has_services) {
        this.$("#services-list").text(I18n.t("pros.show.no_services"));
      }
      this.events.each(function(event) {
        var view;
        view = new EventProView({
          event: event,
          pro_id: _this.pro_id
        });
        return _this.$("#events-list").append(view.render().el);
      });
      if (this.events.length === 0) {
        this.$("#events-list").text(I18n.t("pros.show.no_events"));
      }
      this.comments_container = this.$("#commenti");
      this.messages.each(function(message) {
        var view;
        view = new ProfileMessageView({
          message: message,
          owner: _this.owner
        });
        return _this.comments_container.append(view.render().el);
      });
      this.friends = new Friendships(this.friends.filter(function(friend) {
        return friend.get('accepted');
      }), {
        user_id: this.pro_id
      });
      this.friends.each(function(friend) {
        return $("<li class='tipsy-n'><a href='" + (friend.detail_path()) + "'><img src='" + (friend.get('friend').urlImg) + "=s50-c?imgmax=50&crop=1'/></a></li>").attr("title", friend.get('friend').name).appendTo(_this.$("#amici ul"));
      });
      if (this.friends.length === 0) {
        this.$("#amici ul").text(I18n.t("pros.show.no_friends"));
      }
      this.photos.each(function(image) {
        var $el;
        $el = $("<li><a href='" + (image.get('url')) + "' class='highslide' onclick='return hs.expand(this)'><img src='" + (image.get('url')) + "=s70-c' height='70'/></a></li>").appendTo(_this.$("#foto ul"));
        if (_this.owner) {
          return $("<a href='#' class='delete'></a>").text(I18n.t("pros.show.remove")).appendTo($el).click(function() {
            image.destroy({
              success: function() {
                return $el.remove();
              }
            });
            return false;
          });
        }
      });
      if (this.photos.length === 0) {
        this.$("#foto ul").text(I18n.t("pros.show.no_photos"));
      }
      this.videos.each(function(video) {
        var $el, video_url;
        if (video.get('oembed') && video.get('oembed').title) {
          if (video.get('url').match(/youtube/)) {
            video_url = video.get('url').replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/") + "?rel=0&amp;wmode=transparent";
          }
          if (video.get('url').match(/vimeo/)) {
            video_url = video.get('url').replace("http://vimeo.com/", "http://vimeo.com/moogaloop.swf?&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&amp;clip_id=");
          }
          $el = $("<li class='tipsy-n'><a href='" + video_url + "' onclick=\"return hs.htmlExpand(this, {objectType: 'iframe', width: 480, height: 385, allowSizeReduction: false, wrapperClassName: 'draggable-header no-footer', preserveContent: false, objectLoadTime: 'after'})\" class='highslide'><img src='" + (video.thumb_url()) + "' width='93' height='70'/></a></li>").attr("title", video.get('oembed').title).appendTo(_this.$("#video ul"));
          if (_this.owner) {
            return $("<a href='#' class='delete'></a>").text(I18n.t("pros.show.remove")).appendTo($el).click(function() {
              video.destroy({
                success: function() {
                  return $el.remove();
                }
              });
              return false;
            });
          }
        } else {
          return _this.videos.length -= 1;
        }
      });
      if (this.videos.length === 0) {
        this.$("#video ul").text(I18n.t("pros.show.no_videos"));
      }
      if (this.owner) this.$("#add-photo-button, #add-video-button").show();
      this.$("#video-url").placeholder();
      return this.$("#video-url").live('focus blur', function() {
        return $(this).placeholder();
      });
    }
  };

  ProView.prototype.init_map = function() {
    var height;
    height = this.$('#cs').height();
    return this.map = new google.maps.Map(this.$("#map").css({
      height: height
    }).get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  };

  ProView.prototype.post_message = function(e) {
    var message;
    var _this = this;
    message = new ProfileMessage;
    message.save({
      message: this.$("#new-message").val(),
      playerIdReceiver: this.pro_id,
      privateMessage: this.$("#private-message").is(":checked")
    }, {
      success: function() {
        var view;
        _this.$("#new-message").val("");
        view = new ProfileMessageView({
          message: message,
          owner: _this.owner
        }).render();
        return _this.comments_container.prepend(view.el);
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
    return false;
  };

  return ProView;

})();

var ProsView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

ProsView = (function() {

  __extends(ProsView, MyHomeTabView);

  function ProsView() {
    ProsView.__super__.constructor.apply(this, arguments);
  }

  ProsView.prototype.initialize = function() {
    var _this = this;
    this.current_user = AppController.current_user();
    this.collection = new Pros();
    this.current_user.bind('change:longitude', function() {
      if (_this.current_user.get("latitude") && _this.current_user.get("longitude")) {
        return _this.search_nearby();
      }
    });
    this.collection.bind("reset", function() {
      return _this.render();
    });
    this.el = $("#template_pros-view-page").clone().removeClass("hidden").get(0);
    this.events = {
      "click #navigation .avanti": "next_page",
      "click #navigation .indietro": "previous_page",
      "click #search-nearby a": "search_nearby",
      "click #search-been a": "search_been",
      "click #search-favorites a": "search_favorites",
      "click #content-pros .go": "search",
      "click #aggiungi-pro": "invite_friends",
      "click .add_friendship_path": "add_friend",
      "click .remove_friendship_path": "remove_friend"
    };
    this.delegateEvents();
    this.search_nearby();
    return ProsView.__super__.initialize.apply(this, arguments);
  };

  ProsView.prototype.slug = function() {
    return "tab-pros";
  };

  ProsView.prototype.next_page = function() {
    this.collection.next_page();
    this.collection.fetch();
    return false;
  };

  ProsView.prototype.previous_page = function() {
    this.collection.previous_page();
    this.collection.fetch();
    return false;
  };

  ProsView.prototype.search_been = function() {
    this.collection.set_filters({
      been: true,
      page: 0,
      per_page: 8
    });
    this.collection.fetch();
    return false;
  };

  ProsView.prototype.search_favorites = function() {
    this.collection.set_filters({
      favorites_nearby: true,
      page: 0,
      per_page: 8,
      latitude: this.current_user.get("latitude"),
      longitude: this.current_user.get("longitude")
    });
    this.collection.fetch();
    return false;
  };

  ProsView.prototype.search_nearby = function() {
    this.collection.set_filters({
      latitude: this.current_user.get("latitude"),
      longitude: this.current_user.get("longitude"),
      page: 0,
      per_page: 8
    });
    this.collection.fetch();
    return false;
  };

  ProsView.prototype.reset_form = function() {
    this.$("#luoghi").val("");
    return this.$("#sport").val("");
  };

  ProsView.prototype.search = function() {
    var address, filters;
    var _this = this;
    filters = {
      page: 0,
      per_page: 8
    };
    if (this.$("#sport").val().length) filters.sport_id = this.selected_sport_id;
    if (this.$("#sport").val().length) filters.sport_name = this.$("#sport").val();
    filters.name = this.$("#cerca_pro").val();
    filters.category = this.pro_category_id;
    if (this.$("#cerca_servizio").val().length) {
      filters.service_id = this.selected_service_id;
    }
    filters.service_name = this.$("#cerca_servizio").val();
    address = $("#luoghi").val();
    if (address.length) {
      Utils.geocode(address, function(coords) {
        if (coords != null) {
          filters.latitude = coords.latitude;
          filters.longitude = coords.longitude;
          _this.collection.set_filters(filters);
          return _this.collection.fetch();
        } else {
          return $.jGrowl("Indirizzo non trovato!");
        }
      });
    } else {
      filters.latitude = this.current_user.get("latitude");
      filters.longitude = this.current_user.get("longitude");
      this.collection.set_filters(filters);
      this.collection.fetch();
    }
    return false;
  };

  ProsView.prototype.render = function() {
    this.$("#search-nearby a, #search-been a, #search-favorites a").removeClass("selected");
    if (this.collection.filters.been) {
      this.$("#search-been a").addClass('selected');
    } else if (this.collection.filters.favorites_nearby) {
      this.$("#search-favorites a").addClass('selected');
    } else {
      this.$("#search-nearby a").addClass('selected');
    }
    return ProsView.__super__.render.apply(this, arguments);
  };

  ProsView.prototype.detail_view = function() {
    return $("#template_pros-view-results");
  };

  ProsView.prototype.bubble_view = function() {
    return $("#template_pros-view-maps-bubble");
  };

  ProsView.prototype.data_for_object = function(pro_json) {
    var pro;
    pro = new Pro(pro_json.get('pro'));
    pro.set({
      location: pro_json.get('location')
    });
    pro.set({
      distance: pro_json.get('distance')
    });
    return pro.data_for_render();
  };

  ProsView.prototype.invite_friends = function() {
    return ApplicationScript.DialogInviteShow('INVITE/1', this.current_user.get('token'), '', 'full');
  };

  ProsView.prototype.add_friend = function(e) {
    var _this = this;
    $.ajax({
      url: "/api/private/friendship_add.json?idFriend=" + ($(e.currentTarget).attr('proId')),
      success: function(data) {
        $.jGrowl(I18n.t("global.user.friendship_requested"));
        return _this.collection.fetch();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  ProsView.prototype.remove_friend = function(e) {
    var _this = this;
    $.ajax({
      url: "/api/private/friendship_decline.json?idFriend=" + ($(e.currentTarget).attr('proId')),
      success: function(data) {
        $.jGrowl(I18n.t("global.user.friendship_rejected"));
        return _this.collection.fetch();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  return ProsView;

})();

var UsersView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

UsersView = (function() {

  __extends(UsersView, MyHomeTabView);

  function UsersView() {
    UsersView.__super__.constructor.apply(this, arguments);
  }

  UsersView.prototype.initialize = function() {
    var _this = this;
    this.current_user = AppController.current_user();
    this.collection = this.current_user.friends();
    this.current_user.bind('change:longitude', function() {
      if (_this.current_user.get("latitude") && _this.current_user.get("longitude")) {
        return _this.search_nearby();
      }
    });
    this.collection.unbind("reset");
    this.collection.bind("reset", function() {
      return _this.render();
    });
    this.el = $("#template_users-view-page").clone().removeClass("hidden").get(0);
    this.events = {
      "click #navigation .avanti": "next_page",
      "click #navigation .indietro": "previous_page",
      "click #search-nearby a": "search_nearby",
      "click #search-friends a": "search_friends",
      "click #content-sportivi .go": "search",
      "click #invita": "invite_friends",
      "click .add_friendship_path": "add_friend",
      "click .remove_friendship_path": "remove_friend",
      "keyup #luoghi": "search_key",
      "keyup #sport": "search_key",
      "keyup #sportivi-form": "search_key"
    };
    this.delegateEvents();
    this.search_nearby();
    UsersView.__super__.initialize.apply(this, arguments);
    return this.collection.filters.per_page_multiplier = 2;
  };

  UsersView.prototype.slug = function() {
    return "tab-sportivi";
  };

  UsersView.prototype.next_page = function() {
    this.collection.next_page();
    return this.collection.fetch();
  };

  UsersView.prototype.previous_page = function() {
    this.collection.previous_page();
    return this.collection.fetch();
  };

  UsersView.prototype.search_key = function(e) {
    if (e.keyCode === 13) return this.search();
  };

  UsersView.prototype.search_friends = function() {
    this.reset_form();
    this.collection.set_filters({
      is_friend: true,
      page: 0,
      per_page: 18
    });
    this.collection.fetch();
    return false;
  };

  UsersView.prototype.search_nearby = function() {
    this.reset_form();
    this.collection.set_filters({
      latitude: this.current_user.get("latitude"),
      longitude: this.current_user.get("longitude"),
      page: 0,
      per_page: 9
    });
    this.collection.fetch();
    return false;
  };

  UsersView.prototype.reset_form = function() {
    this.$("#luoghi").val("");
    this.$("#sportivi-form").val("");
    return this.$("#sport").val("");
  };

  UsersView.prototype.search = function() {
    var address, filters;
    var _this = this;
    filters = {
      page: 0,
      per_page: 9
    };
    if (this.$("#sport").val().length) filters.sport_id = this.selected_sport_id;
    if (this.$("#sport").val().length) filters.sport_name = this.$("#sport").val();
    filters.name = this.$("#sportivi-form").val();
    address = $("#luoghi").val();
    if (address.length) {
      return Utils.geocode(address, function(coords) {
        if (coords != null) {
          filters.latitude = coords.latitude;
          filters.longitude = coords.longitude;
          _this.collection.set_filters(filters);
          return _this.collection.fetch();
        } else {
          return $.jGrowl("Indirizzo non trovato!");
        }
      });
    } else {
      filters.latitude = this.current_user.get("latitude");
      filters.longitude = this.current_user.get("longitude");
      this.collection.set_filters(filters);
      return this.collection.fetch();
    }
  };

  UsersView.prototype.render = function() {
    this.$("#search-friends a, #search-nearby a").removeClass("selected");
    if (this.collection.filters.is_friend) {
      this.$("#search-friends a").addClass('selected');
    } else {
      this.$("#search-nearby a").addClass('selected');
    }
    return UsersView.__super__.render.apply(this, arguments);
  };

  UsersView.prototype.detail_view = function() {
    return $("#template_users-view-results");
  };

  UsersView.prototype.bubble_view = function() {
    return $("#template_users-view-maps-bubble");
  };

  UsersView.prototype.data_for_object = function(friend) {
    return friend.data_for_render();
  };

  UsersView.prototype.invite_friends = function() {
    return ApplicationScript.DialogInviteShow('INVITE/1', this.current_user.get('token'), '', 'full');
  };

  UsersView.prototype.add_friend = function(e) {
    var _this = this;
    $.ajax({
      url: "/api/private/friendship_add.json?idFriend=" + ($(e.currentTarget).attr('playerId')),
      success: function(data) {
        $.jGrowl(I18n.t("global.user.friendship_requested"));
        return _this.collection.fetch();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  UsersView.prototype.remove_friend = function(e) {
    var _this = this;
    $.ajax({
      url: "/api/private/friendship_decline.json?idFriend=" + ($(e.currentTarget).attr('playerId')),
      success: function(data) {
        $.jGrowl(I18n.t("global.user.friendship_rejected"));
        return _this.collection.fetch();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  return UsersView;

})();

var NewEventView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

NewEventView = (function() {

  __extends(NewEventView, PageView);

  function NewEventView() {
    NewEventView.__super__.constructor.apply(this, arguments);
  }

  NewEventView.prototype.template = function() {
    return $("#template_new-event-view-page");
  };

  NewEventView.prototype.initialize = function(opts) {
    var _this = this;
    this.save_successful = "events.new.created";
    this.new_event = true;
    opts || (opts = {});
    this.place_id = opts.place_id;
    if (this.place_id) {
      this.place = new Place({
        id: this.place_id
      });
    }
    this.event = new Event;
    this.current_user = AppController.current_user();
    if (this.current_user.get("category") === 0) {
      this.user_sports = this.current_user.sports();
      this.user_sports.fetch({
        success: function() {
          return _this.update_sports();
        }
      });
      this.user_locations = this.current_user.locations();
      this.user_locations.fetch({
        success: function() {
          return _this.update_locations();
        }
      });
    } else {
      this.services = new MyProServices;
      this.services.fetch({
        success: function() {
          _this.user_sports = new MyUserSports;
          _this.services.each(function(service) {
            var k, v, _ref, _results;
            _ref = service.get('sportsMap');
            _results = [];
            for (k in _ref) {
              v = _ref[k];
              _results.push(_this.user_sports.add(new Sport({
                sportName: v,
                sportId: k
              })));
            }
            return _results;
          });
          return _this.update_sports();
        }
      });
      this.pro_locations = new MyProLocations;
      this.pro_locations.fetch({
        success: function() {
          return _this.update_locations();
        }
      });
    }
    this.update_locations();
    this.user_friends = this.current_user.friends();
    this.user_friends.unbind("reset");
    this.user_friends.bind("reset", function() {
      return _this.update_friends();
    });
    this.address_latlng = {};
    this.selected_friends = [];
    this.social_friends = [];
    this.el = this.template().clone().removeClass("hidden").get(0);
    if (this.place) this.lock_address();
    this.events = {
      "keyup #address": "geolocalize_key",
      "click #dx .cerca": "geolocalize",
      "click #navigation .avanti": "next_page",
      "click #navigation .indietro": "previous_page",
      "click #navigation .seleziona-tutti": "select_all",
      "click #search-nearby a": "search_nearby",
      "click #search-friends a": "search_friends",
      "click #search-social a": "search_social",
      "click #search-friend .go": "search",
      "change #sportId": "update_search_results",
      "click #createEvent": "create_event",
      "change #user-locations": "change_map_location",
      "keyup #sportivi-form": "search_key",
      "click input.recall": "recall_last_event"
    };
    this.delegateEvents();
    return this.setup_autocompletes();
  };

  NewEventView.prototype.slug = function() {
    return "tab-new-event";
  };

  NewEventView.prototype.update_sports = function() {
    this.$("#sportId").empty().append("<option value='' selected='selected'></option>");
    this.user_sports.each(function(sport) {
      return this.$("#sportId").append("<option value='" + (sport.get("sportId")) + "'>" + (sport.get("sportName")) + "</option>");
    });
    return this.$("#sportId").css('display', 'inline');
  };

  NewEventView.prototype.update_locations = function() {
    Utils.log("Update locations");
    this.$("#user-locations").empty().append("<option value='' selected='selected'></option>");
    (this.user_locations || this.pro_locations).each(function(location, i) {
      var l;
      l = location.get("location");
      return this.$("#user-locations").append("<option value='" + l.latitude + "|" + l.longitude + "|" + l.address + "'>" + l.address + "</option>");
    });
    return this.$("#user-locations").css('display', 'inline');
  };

  NewEventView.prototype.update_friends = function(opts) {
    var force_distance_from, latlng, _ref;
    var _this = this;
    opts = $.extend({}, opts);
    if (this.user_friends.filters.page === 0) {
      this.$('.indietro').hide();
    } else {
      this.$('.indietro').show();
    }
    if (!this.user_friends.filters.per_page_multiplier) {
      this.user_friends.filters.per_page_multiplier = 1;
    }
    if (this.user_friends.models.length) this.$('.seleziona-tutti').show();
    if ((this.user_friends.filters.per_page * this.user_friends.filters.per_page_multiplier) > this.user_friends.length || !this.user_friends.filters.per_page) {
      this.$('.avanti').hide();
    } else {
      this.$('.avanti').show();
    }
    this.$('#box-risultati').empty();
    force_distance_from = (_ref = opts.force_distance_from) != null ? _ref : false;
    latlng = new google.maps.LatLng(this.latitude() || 45, this.longitude() || 7.5);
    return this.user_friends.each(function(friend) {
      return $("#template_new-event-view-friend").clone().removeClass('hidden').autoRender(friend.data_for_render({
        distance_from: latlng,
        force_distance_from: force_distance_from
      })).click(function() {
        return _this.add_friend(friend);
      }).appendTo(_this.$('#box-risultati'));
    });
  };

  NewEventView.prototype.add_friend = function(friend) {
    var $el, playerId, _ref;
    var _this = this;
    Utils.log("Add friend", friend);
    playerId = (_ref = friend.get("playerId")) != null ? _ref : null;
    if ((playerId != null) && playerId === this.current_user.get("id")) return;
    if (friend.get("player").localUri && this.social_friends.indexOf(friend.get("player").localUri) === -1) {
      this.social_friends.push(friend.get("player").localUri);
      $el = $("#template_new-event-view-selected-friend").clone().removeClass('hidden').autoRender({
        image: "" + (friend.get('player').urlImg) + "=s48-c?imgmax=48&crop=1",
        name: friend.name()
      }).appendTo(this.$('#selected-friends'));
      return $el.click(function() {
        return _this.remove_friend(friend, $el);
      });
    } else if (this.selected_friends.indexOf(friend.get("playerId")) === -1 && !friend.get("player").localUri) {
      this.selected_friends.push(friend.get("playerId"));
      $el = $("#template_new-event-view-selected-friend").clone().removeClass('hidden').autoRender({
        image: "" + (friend.get('player').urlImg) + "=s48-c?imgmax=48&crop=1",
        name: friend.name()
      }).appendTo(this.$('#selected-friends'));
      return $el.click(function() {
        return _this.remove_friend(friend, $el);
      });
    }
  };

  NewEventView.prototype.select_all = function() {
    var _this = this;
    return this.user_friends.each(function(friend) {
      return _this.add_friend(friend);
    });
  };

  NewEventView.prototype.remove_friend = function(friend, el) {
    var idx;
    el.remove();
    if ((idx = this.selected_friends.indexOf(friend.get("playerId"))) !== -1) {
      return this.selected_friends.splice(idx, 1);
    } else if ((idx = this.social_friends.indexOf(friend.get("player").localUri)) !== -1) {
      return this.social_friends.splice(idx, 1);
    }
  };

  NewEventView.prototype.geolocalize_key = function(e) {
    if (e.keyCode === 13) return this.geolocalize();
  };

  NewEventView.prototype.geolocalize = function() {
    var _this = this;
    return Utils.geocode(this.$("#address").val(), function(geoResult) {
      Utils.log(geoResult);
      if (geoResult) {
        _this.address_latlng = geoResult;
        _this.update_search_results();
        _this.map.setCenter(geoResult.latlng);
        _this.marker || (_this.marker = new google.maps.Marker({
          map: _this.map,
          title: 'Posizione',
          position: _this.current_user.latlng()
        }));
        return _this.marker.setPosition(geoResult.latlng);
      } else {
        return $.jGrowl(I18n.t("global.geocode_fail"));
      }
    });
  };

  NewEventView.prototype.change_map_location = function(e) {
    var coords, latlng;
    coords = $(e.target).val().split("|");
    latlng = new google.maps.LatLng(coords[0], coords[1]);
    this.$("#address").val(coords[2]);
    this.address_latlng = {
      latitude: coords[0],
      longitude: coords[1]
    };
    this.update_search_results();
    this.map.setCenter(latlng);
    this.marker || (this.marker = new google.maps.Marker({
      map: this.map,
      title: 'Posizione',
      position: this.current_user.latlng()
    }));
    return this.marker.setPosition(latlng);
  };

  NewEventView.prototype.next_page = function() {
    this.user_friends.next_page();
    this.user_friends.fetch();
    return false;
  };

  NewEventView.prototype.previous_page = function() {
    this.user_friends.previous_page();
    this.user_friends.fetch();
    return false;
  };

  NewEventView.prototype.latitude = function() {
    var _ref;
    return (_ref = this.address_latlng.latitude) != null ? _ref : this.current_user.get("latitude");
  };

  NewEventView.prototype.longitude = function() {
    var _ref;
    return (_ref = this.address_latlng.longitude) != null ? _ref : this.current_user.get("longitude");
  };

  NewEventView.prototype.search_friends = function(e) {
    this.$("#navigation .indietro, #navigation .avanti, #navigation .seleziona-tutti").hide();
    this.$(".friends-filter a").removeClass("w-current");
    $(e.target).addClass("w-current");
    this.user_friends.set_filters({
      is_friend: true,
      page: 0,
      per_page: 18,
      per_page_multiplier: 1
    });
    this.user_friends.fetch();
    return false;
  };

  NewEventView.prototype.search_nearby = function(e) {
    this.$("#navigation .indietro, #navigation .avanti, #navigation .seleziona-tutti").hide();
    this.$(".friends-filter a").removeClass("w-current");
    $(e.target).addClass("w-current");
    this.user_friends.set_filters({
      latitude: this.latitude(),
      longitude: this.longitude(),
      page: 0,
      per_page: 9,
      sport_id: this.$("#sportId").val(),
      per_page_multiplier: 2
    });
    this.user_friends.fetch();
    return false;
  };

  NewEventView.prototype.update_search_results = function() {
    if (this.$("#search-nearby a").is(".w-current")) {
      return this.search_nearby({
        target: this.$("#search-nearby a").get(0)
      });
    } else if (this.$("#search-friends a").is(".w-current")) {
      return this.update_friends();
    } else if (!this.$("#search-social a").is(".w-current")) {
      return this.update_friends({
        force_distance_from: true
      });
    }
  };

  NewEventView.prototype.search_social = function(e) {
    var _this = this;
    this.$("#navigation .indietro, #navigation .avanti").hide();
    this.$(".friends-filter a").removeClass("w-current");
    $(e.target).addClass("w-current");
    this.user_friends.set_filters({
      page: 0,
      per_page: 0
    });
    this.user_friends.models = [];
    show_loading();
    $.getJSON(ApplicationScript.RestUrl('friends.list', this.current_user.get("token")) + "&callback=?", function(data, textStatus, jqXHR) {
      var f, friend, _i, _len, _ref;
      hide_loading();
      _ref = data.friends;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        friend = _ref[_i];
        f = new Friend({
          player: {
            localUri: friend.LocalUri,
            name: friend.DisplayName,
            urlImg: friend.ImageProfile
          }
        });
        _this.user_friends.models.push(f);
      }
      return _this.update_friends();
    });
    return false;
  };

  NewEventView.prototype.search = function() {
    var filters, name;
    name = this.$("#sportivi-form").val();
    if (name !== "") {
      this.$("#navigation .indietro, #navigation .avanti, #navigation .seleziona-tutti").hide();
      this.$(".friends-filter a").removeClass("w-current");
      filters = {
        page: 0,
        per_page: 9
      };
      filters.name = name;
      filters.longitude = this.longitude();
      filters.latitude = this.latitude();
      this.user_friends.set_filters(filters);
      this.user_friends.fetch();
    }
    return false;
  };

  NewEventView.prototype.search_key = function(e) {
    if (e.keyCode === 13) return this.search();
  };

  NewEventView.prototype.setup_autocompletes = function() {
    var _this = this;
    return this.$("#sportivi-form").autocomplete({
      source: function(request, response) {
        var query, requestSplit;
        requestSplit = request.term.split(" ");
        query = 'prefix1=' + requestSplit[0];
        if (requestSplit.length > 1) query += '&prefix2=' + requestSplit[1];
        return $.getJSON('/api/private/autocomplete_player.json?' + query, function(data) {
          var player, players, _i, _len, _ref;
          players = [];
          _ref = data.list;
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            player = _ref[_i];
            players.push({
              label: player.name,
              playerId: player.id,
              location: player.location,
              player: player
            });
          }
          return response(players);
        });
      },
      select: function(event, ui) {
        return _this.selected_user_id = ui.item.id;
      }
    });
  };

  NewEventView.prototype.setup_map = function() {
    var self;
    this.map = new google.maps.Map(this.$("#map").get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    this.marker = new google.maps.Marker({
      map: this.map,
      title: 'Mia posizione',
      position: this.current_user.latlng()
    });
    this.marker.setDraggable(true);
    self = this;
    return google.maps.event.addListener(this.marker, 'dragend', function() {
      var location;
      location = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
      self.address_latlng = {
        latitude: this.getPosition().lat(),
        longitude: this.getPosition().lng()
      };
      self.update_search_results();
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return self.$("#address").val(results[0].formatted_address);
        }
      });
    });
  };

  NewEventView.prototype.render = function() {
    var _this = this;
    if (this.current_user.get("token").match(/^WW/)) {
      this.$("#search-social").hide();
    }
    Utils.log("Render di " + (this.slug()));
    this.setup_map();
    if (this.place) {
      this.place.fetch({
        success: function() {
          var latlng;
          _this.address_latlng = {
            latitude: _this.place.get("location").latitude,
            longitude: _this.place.get("location").longitude
          };
          _this.update_search_results();
          _this.$("#address").val(_this.place.get("location").address);
          latlng = new google.maps.LatLng(_this.place.get("location").latitude, _this.place.get("location").longitude);
          _this.map.setCenter(latlng);
          _this.marker || (_this.marker = new google.maps.Marker({
            map: _this.map,
            title: 'Posizione',
            position: latlng
          }));
          _this.marker.setPosition(latlng);
          return _this.marker.setDraggable(false);
        }
      });
    } else {
      this.update_search_results();
    }
    return this;
  };

  NewEventView.prototype.lock_address = function() {
    $(this.el).find("#address").prop("disabled", "disabled");
    $(this.el).find("#dx .cerca").hide();
    return $(this.el).find("#dx form").hide();
  };

  NewEventView.prototype.create_event = function() {
    var attrs, date, eventType, player_list, players, sn_players;
    var _this = this;
    players = _.map(this.selected_friends, function(id) {
      return {
        playerId: id
      };
    });
    sn_players = _.map(this.social_friends, function(id) {
      return {
        localUri: id
      };
    });
    if (this.new_event) {
      player_list = {
        gamePlayersList: players
      };
    } else {
      player_list = {
        newGamePlayersList: players
      };
    }
    if (this.$("#eventDate").val().length > 0) {
      date = Date.parse(this.$("#eventDate").val());
    }
    if (date != null) {
      date.set_time_from_string(this.$("#eventTimeHours").val() + ":" + this.$("#eventTimeMinutes").val());
    }
    eventType = this.$("#eventType:checked").val();
    if (!(Utils.is_date(date) && (Date.parse(date) > new Date()))) {
      $.jGrowl(I18n.t("global.event.errors.date"));
      return false;
    }
    attrs = {
      sportId: this.$("#sportId").val(),
      date: Utils.date_to_iso8601(date),
      maxPlayersReq: parseInt(this.$("#maxPlayers").val()),
      minPlayersReq: parseInt(this.$("#minPlayers").val()),
      flagPrivate: eventType === "private" ? true : (eventType === "public" ? false : null),
      location: {
        address: this.$("#address").val(),
        longitude: this.address_latlng.longitude,
        latitude: this.address_latlng.latitude
      },
      name: this.$("#eventName").val(),
      description: this.$("#eventDescription").val(),
      message: this.$("#message").val(),
      flagNotificationStatusChange: this.$("#flagNotificationStatusChange").is(":checked"),
      otherUsersLocalUri: sn_players,
      otherFriendsEmails: this.$("#other-emails").val() ? this.$("#other-emails").val().split(/\s*,\s*/) : []
    };
    if (this.place_id != null) attrs.businessId = this.place_id;
    attrs = $.extend(attrs, player_list);
    Utils.log(attrs);
    this.event.save(attrs, {
      success: function() {
        $.jGrowl(I18n.t(_this.save_successful));
        return document.location = "#/my_home/events/" + (_this.event.get("id"));
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
    return false;
  };

  NewEventView.prototype.recall_last_event = function() {
    var _this = this;
    return $.ajax({
      url: "/api/private/findLastCreatedEvent.json",
      success: function(event) {
        return _this.update_event_fields({
          update_players: true,
          event: new Event(event)
        });
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  NewEventView.prototype.update_event_fields = function(opts) {
    var event, players;
    var _this = this;
    opts = _.extend({
      update_players: false,
      event: this.event
    }, opts);
    event = opts.event;
    this.$("#sportId option[value='" + (event.get("sportId")) + "']").attr("selected", "selected");
    this.$("#maxPlayers").val(event.get("maxPlayersReq"));
    this.$("#minPlayers").val(event.get("minPlayersReq"));
    this.$("#eventType[value='" + (event.get("flagPrivate") ? "private" : "public") + "']").attr("checked", "checked");
    if (event.get("flagNotificationStatusChange")) {
      this.$("#flagNotificationStatusChange").attr("checked", "checked");
    }
    this.$("#eventName").val(event.get("name"));
    this.$("#eventDescription").val(event.get("message"));
    if (event.get("date")) {
      this.$("#eventDate").val(Date.parse(event.get("date")).strftime(Utils.date_format_short($.cookie("lang"))));
    }
    if (event.get("date")) {
      this.$("#eventTimeHours").val(Date.parse(event.get("date")).toString("HH"));
    }
    if (event.get("date")) {
      this.$("#eventTimeMinutes").val(Date.parse(event.get("date")).toString("mm"));
    }
    if (event.get("location") != null) {
      this.address_latlng = event.get("location");
      this.$("#address").val(event.get("location").address);
      this.marker || (this.marker = new google.maps.Marker({
        map: this.map,
        title: 'Posizione',
        position: event.latlng()
      }));
      this.marker.setPosition(event.latlng());
      this.map.setCenter(event.latlng());
      this.marker.setDraggable(false);
    }
    if (opts.update_players) {
      players = event.get("gamePlayersList");
      _.each(players, function(player) {
        return _this.add_friend(new Friend(player));
      });
    }
    return this.update_search_results();
  };

  return NewEventView;

})();

var EditEventView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

EditEventView = (function() {

  __extends(EditEventView, NewEventView);

  function EditEventView() {
    EditEventView.__super__.constructor.apply(this, arguments);
  }

  EditEventView.prototype.template = function() {
    return $("#template_edit_event_view-page");
  };

  EditEventView.prototype.initialize = function(options) {
    EditEventView.__super__.initialize.apply(this, arguments);
    this.save_successful = "events.new.modified";
    this.new_event = false;
    this.event_id = options.id;
    return this.event = new Event({
      id: this.event_id
    });
  };

  EditEventView.prototype.slug = function() {
    return "tab-edit-event";
  };

  EditEventView.prototype.render = function() {
    var _this = this;
    EditEventView.__super__.render.apply(this, arguments);
    this.event.fetch({
      success: function() {
        return _this.update_event_fields();
      }
    });
    return this.lock_address();
  };

  EditEventView.prototype.update_event_fields = function(opts) {
    var friend, _i, _len, _ref, _results;
    EditEventView.__super__.update_event_fields.call(this, opts);
    if (true) {
      $('#crea-squadre').show();
      $("#partecipanti .list, #non-partecipanti .list, #attesa .list").empty();
      _ref = this.event.get("gamePlayersList");
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        friend = _ref[_i];
        friend = new Friend(friend);
        if (friend.get("accepted")) {
          _results.push(this.add_accepted_player(friend));
        } else if (friend.get("declined")) {
          _results.push(this.add_declined_player(friend));
        } else if (!friend.get("requestPartecipate")) {
          _results.push(this.add_waiting_player(friend));
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    } else {
      return $('#crea-squadre').hide();
    }
  };

  EditEventView.prototype.add_accepted_player = function(friend) {
    var $el;
    return $el = $("#template-player-accepted").clone().removeAttr("id").removeClass('hidden').autoRender({
      image: "" + (friend.get('player').urlImg) + "=s48-c?imgmax=48&crop=1",
      name: friend.name()
    }).appendTo(this.$('#partecipanti .list'));
  };

  EditEventView.prototype.add_waiting_player = function(friend) {
    var $el;
    var _this = this;
    $el = $("#template-player-waiting").clone().removeAttr("id").removeClass('hidden').autoRender({
      image: "" + (friend.get('player').urlImg) + "=s48-c?imgmax=48&crop=1",
      name: friend.name()
    }).appendTo(this.$('#attesa .list'));
    return $el.find(".mail").click(function() {
      return _this.send_mail(friend);
    });
  };

  EditEventView.prototype.add_declined_player = function(friend) {
    var $el;
    return $el = $("#template-player-declined").clone().removeAttr("id").removeClass('hidden').autoRender({
      image: "" + (friend.get('player').urlImg) + "=s48-c?imgmax=48&crop=1",
      name: friend.name()
    }).appendTo(this.$('#non-partecipanti .list'));
  };

  EditEventView.prototype.send_mail = function(friend) {
    $.ajax({
      url: "/api/private/event_notify_reminder.json",
      data: {
        userId: friend.get("playerId"),
        eventId: this.event.get("id")
      },
      success: function() {
        return $.jGrowl(I18n.t("global.event.messages.reminder_sent"));
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  return EditEventView;

})();

var AbuseView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

AbuseView = (function() {

  __extends(AbuseView, PageView);

  function AbuseView() {
    AbuseView.__super__.constructor.apply(this, arguments);
  }

  AbuseView.prototype.tagName = "div";

  AbuseView.prototype.initialize = function(options) {
    if (options) return this.place_id = options.id;
  };

  AbuseView.prototype.slug = function() {
    return "tab-place-abuse";
  };

  AbuseView.prototype.submit = function() {
    var _this = this;
    $.ajax({
      type: "POST",
      url: "/api/private/report_abuse_business/" + this.place_id,
      data: {
        reason: this.$("textarea").val()
      },
      success: function() {
        $.jGrowl(I18n.t("abuse.success"));
        return document.location = "#/my_home/places/" + _this.place_id;
      }
    });
    return false;
  };

  AbuseView.prototype.render = function() {
    $(this.el).empty().append($("#template_abuse_view-page").clone().removeClass("hidden"));
    return this.delegateEvents({
      "click .button": "submit"
    });
  };

  return AbuseView;

})();

var EventUserView, SportUserView, UserView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SportUserView = (function() {

  __extends(SportUserView, Backbone.View);

  function SportUserView() {
    SportUserView.__super__.constructor.apply(this, arguments);
  }

  SportUserView.prototype.initialize = function(ops) {
    this.sport = ops.sport;
    this.locations = ops.locations;
    this.el = $("#template-profilo-sport-user-show").clone().removeClass("hidden").autoRender(this.data()).removeAttr("id").get(0);
    this.$(".expand").hide();
    return this.delegateEvents({
      "click .dettagli a": "toggle"
    });
  };

  SportUserView.prototype.data = function() {
    var level_2_css;
    level_2_css = {
      0: "debuttante",
      1: "amatore",
      2: "esperto",
      3: "agonista"
    };
    return {
      level: level_2_css[parseInt(this.sport.get("levelId"))],
      level_title: I18n.t("settings.step2.ability" + (this.sport.get("levelId") + 1)),
      name: this.sport.get("sportName"),
      votes: I18n.t("global.place.votes", {
        count: this.sport.get("rating"),
        total: this.sport.get("ratingTotal")
      })
    };
  };

  SportUserView.prototype.toggle = function(e) {
    var $mapContainer, bounds, location, schedules, sport_locations, _fn, _i, _len;
    var _this = this;
    $(e.target).toggleClass("open").toggleClass("closed");
    if (!this.$(".expand").is(":visible")) {
      this.$(".expand").show();
      sport_locations = this.locations.filter(function(location) {
        return _.any(location.get('sportList'), function(el) {
          return el.id === _this.sport.get("sportId");
        });
      });
      $mapContainer = $("<div/>").css({
        height: 300
      }).appendTo(this.$(".expand"));
      this.map = new google.maps.Map($mapContainer.get(0), {
        zoom: 14,
        center: sport_locations[0].latlng(),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      schedules = this.sport.get('listSchedule').length > 0 ? _.map(this.sport.get('listSchedule'), function(schedule) {
        var dayname;
        dayname = I18n.t("global.days.day" + (parseInt(schedule.dayOfWeek)));
        return {
          description: "" + dayname + " " + (Utils.pad_total_time(schedule.startTime)) + " - " + (Utils.pad_total_time(schedule.endTime))
        };
      }) : I18n.t("users.show.anytime");
      bounds = new google.maps.LatLngBounds();
      _fn = function(location) {
        var bubble_content, data, infoWindow, marker;
        data = {
          name: _this.sport.get("sportName"),
          address: location.get("location").address,
          schedules: schedules
        };
        bubble_content = $("#template-profilo-sport-bubble-user-show").clone().removeClass('hidden').autoRender(data);
        marker = location.marker(_this.map);
        infoWindow = new google.maps.InfoWindow({
          content: bubble_content.html()
        });
        google.maps.event.addListener(marker, 'click', function() {
          return infoWindow.open(_this.map, marker);
        });
        return bounds.extend(location.latlng());
      };
      for (_i = 0, _len = sport_locations.length; _i < _len; _i++) {
        location = sport_locations[_i];
        _fn(location);
      }
      if (sport_locations.length > 1) this.map.fitBounds(bounds);
    } else {
      this.$(".expand").hide().empty();
    }
    return false;
  };

  SportUserView.prototype.render = function() {
    var location;
    var _this = this;
    location = this.locations.detect(function(location) {
      return _.any(location.get('sportList'), function(el) {
        return el.id === _this.sport.get("sportId");
      });
    });
    if (!location) this.$(".dettagli").remove();
    return this;
  };

  return SportUserView;

})();

EventUserView = (function() {

  __extends(EventUserView, Backbone.View);

  function EventUserView() {
    EventUserView.__super__.constructor.apply(this, arguments);
  }

  EventUserView.prototype.initialize = function(ops) {
    this.event = ops.event;
    this.user_id = ops.user_id;
    this.from_place = ops.from_place;
    this.el = $("#template-profilo-event-user-show").clone().removeClass("hidden").autoRender(this.event.data_for_render()).removeAttr("id").get(0);
    this.$(".expand").hide();
    return this.delegateEvents({
      "click .dettagli-eventi a": "toggle"
    });
  };

  EventUserView.prototype.toggle = function(e) {
    var $mapContainer, bubble_content;
    $(e.target).toggleClass("open").toggleClass("closed");
    this.$(".expand").toggle();
    if (this.$(".expand").is(":visible")) {
      $mapContainer = $("<div/>").css({
        height: 300
      }).appendTo(this.$(".expand"));
      this.map = new google.maps.Map($mapContainer.get(0), {
        zoom: 14,
        center: this.event.latlng(),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      this.marker = new google.maps.Marker({
        map: this.map,
        title: 'Posizione',
        position: this.event.latlng()
      });
      bubble_content = $("#template_events-view-maps-bubble").clone().removeClass('hidden').autoRender(this.event.data_for_render());
      if (parseInt(this.user_id) !== parseInt(AppController.current_user().get("id"))) {
        $(".private_actions", bubble_content).hide();
        $(".public_view", bubble_content).removeClass('hidden');
      }
      if (this.from_place) $('.public_view', bubble_content).hide();
      this.infoWindow = new google.maps.InfoWindow({
        content: bubble_content.html()
      });
      this.infoWindow.open(this.map, this.marker);
    } else {
      this.$(".expand").empty();
    }
    return false;
  };

  EventUserView.prototype.render = function() {
    if (this.event.my_status() === "owner") {
      $("<a class='modifica-attivo'/>").attr("href", "#/my_home/events/" + (this.event.get("id")) + "/edit").appendTo(this.$(".risposte"));
    } else {
      $("<span class='modifica-disattivato'/>").appendTo(this.$(".risposte"));
    }
    return this;
  };

  return EventUserView;

})();

UserView = (function() {

  __extends(UserView, PageView);

  function UserView() {
    UserView.__super__.constructor.apply(this, arguments);
  }

  UserView.prototype.tagName = "div";

  UserView.prototype.initialize = function(options) {
    var _this = this;
    this.user_id = options.id;
    this.owner = parseInt(this.user_id) === parseInt(AppController.current_user().get("id"));
    this.user = new User({
      id: this.user_id
    });
    this.sports = new UserSports([], {
      user_id: this.user_id
    });
    this.events = new UserEvents([], {
      user_id: this.user_id
    });
    this.messages = new ProfileMessages([], {
      user_id: this.user_id
    });
    this.friends = new Friendships([], {
      user_id: this.user_id
    });
    this.locations = new UserLocations([], {
      user_id: this.user_id
    });
    this.photos = new ProfilePhotos([], {
      user_id: this.user_id
    });
    this.videos = new ProfileVideos([], {
      user_id: this.user_id
    });
    this.fetch_count = 0;
    this.user.fetch({
      success: function() {
        if (!(_this.user.attributes && _this.user.attributes.registrationComplete)) {
          $.jGrowl(I18n.t("global.user.not_existing"));
          document.location = "#/my_home/users";
          return;
        }
        return _this.fetch_count++ && _this.render();
      }
    });
    this.sports.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.events.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.messages.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.friends.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.locations.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.photos.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.videos.fetch({
      success: function() {
        return _this.fetch_count++ && _this.render();
      }
    });
    this.current_user = AppController.current_user();
    return this.delegateEvents({
      "click #send-new-message": "post_message",
      "click .back": "back",
      "click #add-photo-button": "toggle_photo_form",
      "click #add-video-button": "toggle_video_form",
      "click #cancel-photo-button": "toggle_photo_form",
      "click #cancel-video-button": "toggle_video_form",
      "click #save-video": "save_video",
      "click #save-photo": "save_photo"
    });
  };

  UserView.prototype.toggle_video_form = function() {
    this.$("#add-video, #add-video-button}").toggle();
    return false;
  };

  UserView.prototype.toggle_photo_form = function() {
    this.$("#add-photo, #add-photo-button").toggle();
    return false;
  };

  UserView.prototype.save_photo = function() {
    var _this = this;
    if (this.$('input[name="profile_picture"]').val().length > 0) {
      $.ajax({
        url: "/api/private/createUploadProfilePicture",
        dataType: 'text',
        success: function(data) {
          var url;
          url = data.replace(/http:\/\/.*?\//, '/');
          return _this.$('#photo-upload').attr('action', url).ajaxForm({
            iframe: true,
            success: function(data, status, xhr) {
              Utils.log("Inviato con successo!");
              _this.photos.fetch({
                success: function() {
                  return _this.render();
                }
              });
              return _this.toggle_photo_form();
            }
          }).submit();
        },
        error: function() {
          return $.jGrowl(I18n.t("settings.step1.upload_error"));
        }
      });
    }
    return false;
  };

  UserView.prototype.save_video = function() {
    var video;
    var _this = this;
    if (this.$("#video-url").val().trim().length > 0 && this.$("#video-url").val() !== I18n.t('users.show.youtube_url')) {
      video = new ProfileVideo;
      return video.save({
        url: this.$("#video-url").val(),
        type: 0
      }, {
        success: function() {
          _this.videos.fetch({
            success: function() {
              return _this.render();
            }
          });
          return _this.toggle_video_form();
        },
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    }
  };

  UserView.prototype.back = function() {
    return document.location = "#/my_home/users";
  };

  UserView.prototype.slug = function() {
    return "tab-user-show";
  };

  UserView.prototype.data = function() {
    return this.user.data_for_render({
      image_size: 105
    });
  };

  UserView.prototype.render = function() {
    var _this = this;
    if (this.owner) $("#header #menu #myprofile a").addClass("menu-selected");
    if (this.fetch_count >= 8) {
      $(this.el).empty().append($("#template_show_user_view-page").clone().removeClass("hidden").autoRender(this.data()));
      if (this.owner) this.$("#c1 .aggiungi, #c3 .distance, #c3 .luogo").remove();
      this.$("#messaggio").empty();
      this.sports.each(function(sport) {
        var mess_cont, sport_desc, view;
        view = new SportUserView({
          sport: sport,
          locations: _this.locations
        });
        _this.$("#sports-list").append(view.render().el);
        sport_desc = sport.get('levelDescription') && sport.get('levelDescription').length > 0;
        if (sport_desc) {
          mess_cont = _this.$("#messaggio").append($("<div>"));
          return mess_cont.append($("<span/>").addClass("sport").text(sport.get('sportName') + ": ")).append($("<span/>").addClass("sport_desc").text(sport.get('levelDescription')));
        }
      });
      if (this.sports.length === 0) {
        this.$("#sports-list").text(I18n.t("users.show.no_sports"));
      }
      this.events.each(function(event) {
        var view;
        view = new EventUserView({
          event: event,
          user_id: _this.user_id
        });
        return _this.$("#events-list").append(view.render().el);
      });
      if (this.events.length === 0) {
        this.$("#events-list").text(I18n.t("users.show.no_events"));
      }
      this.comments_container = this.$("#commenti");
      this.messages.each(function(message) {
        var view;
        view = new ProfileMessageView({
          message: message,
          owner: _this.owner
        });
        return _this.comments_container.append(view.render().el);
      });
      this.friends = new Friendships(this.friends.filter(function(friend) {
        return friend.get('accepted');
      }), {
        user_id: this.pro_id
      });
      this.friends.each(function(friend) {
        if (friend.get('friend')) {
          return $("<li class='tipsy-n'><a href='" + (friend.detail_path()) + "'><img src='" + (friend.get('friend').urlImg) + "=s50-c?imgmax=50&crop=1'/></a></li>").attr("title", friend.get('friend').name).appendTo(_this.$("#amici ul"));
        }
      });
      if (this.friends.length === 0) {
        this.$("#amici ul").text(I18n.t("users.show.no_friends"));
      }
      if (this.photos.length === 0) {
        this.$("#foto ul").text(I18n.t("users.show.no_photos"));
      }
      this.photos.each(function(image) {
        var $el;
        $el = $("<li><a href='" + (image.get('url')) + "' class='highslide' onclick='return hs.expand(this)'><img src='" + (image.get('url')) + "=s70-c' height='70'/></a></li>").appendTo(_this.$("#foto ul"));
        if (_this.owner) {
          return $("<a href='#' class='delete'></a>").text(I18n.t("users.show.remove")).appendTo($el).click(function() {
            image.destroy({
              success: function() {
                return $el.remove();
              },
              error: function() {
                return $.jGrowl(I18n.t("global.connection_error"));
              }
            });
            return false;
          });
        }
      });
      this.videos.each(function(video) {
        var $el, video_url;
        if (video.get('oembed')) {
          if (video.get('url').match(/youtube/)) {
            video_url = video.get('url').replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/") + "?rel=0&amp;wmode=transparent";
          }
          if (video.get('url').match(/vimeo/)) {
            video_url = video.get('url').replace("http://vimeo.com/", "http://vimeo.com/moogaloop.swf?&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&amp;clip_id=");
          }
          $el = $("<li class='tipsy-n'><a href='" + video_url + "' onclick=\"return hs.htmlExpand(this, {objectType: 'iframe', width: 480, height: 385, 		  allowSizeReduction: false, wrapperClassName: 'draggable-header no-footer', 		  preserveContent: false, objectLoadTime: 'after'})\" class='highslide'><img src='" + (video.thumb_url()) + "' width='93' height='70'/></a></li>").attr("title", video.get('oembed').title).appendTo(_this.$("#video ul"));
          if (_this.owner) {
            return $("<a href='#' class='delete'></a>").text(I18n.t("users.show.remove")).appendTo($el).click(function() {
              video.destroy({
                success: function() {
                  return $el.remove();
                },
                error: function() {
                  return $.jGrowl(I18n.t("global.connection_error"));
                }
              });
              return false;
            });
          }
        } else {
          return _this.videos.length -= 1;
        }
      });
      if (this.videos.length === 0) {
        this.$("#video ul").text(I18n.t("users.show.no_videos"));
      }
      this.$("#video-url").placeholder();
      this.$("#video-url").live('focus blur', function() {
        return $(this).placeholder();
      });
      if (this.owner) return this.$("#add-photo-button, #add-video-button").show();
    }
  };

  UserView.prototype.post_message = function(e) {
    var message;
    var _this = this;
    message = new ProfileMessage;
    Utils.log({
      message: this.$("#new-message").val(),
      playerIdReceiver: this.user_id,
      privateMessage: this.$("#private-message").is(":checked")
    });
    message.save({
      message: this.$("#new-message").val(),
      playerIdReceiver: this.user_id,
      privateMessage: this.$("#private-message").is(":checked")
    }, {
      success: function() {
        var view;
        _this.$("#new-message").val("");
        view = new ProfileMessageView({
          message: message,
          owner: _this.owner
        }).render();
        return _this.comments_container.prepend(view.el);
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
    return false;
  };

  return UserView;

})();

var EventMessageInboxRow, FeedbackEventInboxRow, FeedbackEventPlaceView, FeedbackEventPlayerView, FriendshipRequestInboxRow, InboxRow, InboxView, InviteEventInboxRow, PartecipationRequestEventInboxRow, ProMessageInboxRow, WallMessageInboxRow;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

InboxRow = (function() {

  __extends(InboxRow, Backbone.View);

  function InboxRow() {
    InboxRow.__super__.constructor.apply(this, arguments);
  }

  InboxRow.prototype.initialize = function(opts) {
    this.inbox = opts.inbox;
    return this.row = opts.row;
  };

  InboxRow.prototype.icon = function() {
    return "";
  };

  InboxRow.prototype.image = function() {
    return null;
  };

  InboxRow.prototype.excerpt_template = function() {
    return $("<div/>");
  };

  InboxRow.prototype.excerpt_data = function() {
    return {};
  };

  InboxRow.prototype.has_details = function() {
    return false;
  };

  InboxRow.prototype.details = function() {
    return null;
  };

  InboxRow.prototype.actions = function() {
    return [
      {
        "class": "elimina",
        event: "delete_message",
        tipsy: "Elimina questo messaggio"
      }
    ];
  };

  InboxRow.prototype.delete_message = function() {
    var _this = this;
    Utils.log("delete_message()");
    return this.row.destroy({
      success: function() {
        $(_this.el).remove();
        if (!_this.row.get("read")) return Utils.lower_inbox_counter();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  InboxRow.prototype.refresh_details = function() {
    return this.$(".box-details").empty().hide().append(this.details());
  };

  InboxRow.prototype.render = function() {
    var _this = this;
    this.el = $("#inbox-row-template").clone().removeAttr("id").removeClass("hidden").get(0);
    if (!this.row.get("read")) {
      this.$(".box-message").addClass("box-message-unread");
    }
    this.$(".box-message").click(function() {
      Utils.log("click");
      if (!_this.row.get("read")) {
        _this.row.mark_as_read({
          success: function() {
            _this.row.set({
              'read': true
            });
            Utils.log("read");
            _this.$(".box-message").removeClass("box-message-unread");
            return Utils.lower_inbox_counter();
          },
          error: function() {
            return $.jGrowl(I18n.t("global.connection_error"));
          }
        });
      }
      if (_this.has_details()) return _this.$(".box-details").slideToggle();
    });
    this.$(".row-type-icon").addClass(this.icon());
    if (this.image()) {
      this.$(".foto").empty().append("<img src='" + (this.image()) + "' />");
    }
    this.$(".data").empty().append(Date.parse(this.row.get('date')).strftime(Utils.date_format($.cookie("lang"))));
    this.$(".corpo").empty().append(this.excerpt_template().clone().removeAttr("id").removeClass("hidden").autoRender(this.excerpt_data(), {}));
    if (this.has_details()) {
      this.refresh_details();
    } else {
      this.$(".box-details").remove();
    }
    _.each(this.actions(), function(action) {
      var el;
      el = $("<span><a href='#'/></span>").addClass(action["class"]).addClass("tipsy-gravity-s").attr("tooltip", action.tipsy);
      _this.$(".tools p").append(el);
      return el.click(function() {
        _this[action.event]();
        return false;
      });
    });
    return this;
  };

  return InboxRow;

})();

FriendshipRequestInboxRow = (function() {

  __extends(FriendshipRequestInboxRow, InboxRow);

  function FriendshipRequestInboxRow() {
    FriendshipRequestInboxRow.__super__.constructor.apply(this, arguments);
  }

  FriendshipRequestInboxRow.prototype.actions = function() {
    var actions;
    actions = FriendshipRequestInboxRow.__super__.actions.apply(this, arguments);
    actions.push({
      "class": "no",
      event: "reject_friendship",
      tipsy: "Rifiuta la richiesta di amicizia!"
    });
    actions.push({
      "class": "si",
      event: "accept_friendship",
      tipsy: "Accetta la richiesta di amicizia!"
    });
    return actions;
  };

  FriendshipRequestInboxRow.prototype.accept_friendship = function() {
    var _this = this;
    return $.ajax({
      url: "/api/private/friendship_accept.json?idFriend=" + (this.row.get("detail").id),
      success: function() {
        $.jGrowl(I18n.t("global.user.messages.friendship_accepted"));
        return _this.delete_message();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  FriendshipRequestInboxRow.prototype.reject_friendship = function() {
    var _this = this;
    return $.ajax({
      url: "/api/private/friendship_decline.json?idFriend=" + (this.row.get("detail").id),
      success: function() {
        $.jGrowl(I18n.t("global.user.messages.friendship_declined"));
        return _this.delete_message();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  FriendshipRequestInboxRow.prototype.icon = function() {
    return "invita-sportivo";
  };

  FriendshipRequestInboxRow.prototype.image = function() {
    return "" + (this.row.get("detail").urlImg) + "=s44-c?imgmax=44&crop=1";
  };

  FriendshipRequestInboxRow.prototype.excerpt_template = function() {
    return $("#friendship-request-row-template");
  };

  FriendshipRequestInboxRow.prototype.excerpt_data = function() {
    var user;
    user = new Friend({
      player: this.row.get('detail')
    }).data_for_render();
    return {
      nome: I18n.t("inbox.friendship_request.title", {
        name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
      }),
      reliability: user.reliability
    };
  };

  return FriendshipRequestInboxRow;

})();

WallMessageInboxRow = (function() {

  __extends(WallMessageInboxRow, InboxRow);

  function WallMessageInboxRow() {
    WallMessageInboxRow.__super__.constructor.apply(this, arguments);
  }

  WallMessageInboxRow.prototype.actions = function() {
    var actions;
    actions = WallMessageInboxRow.__super__.actions.apply(this, arguments);
    return actions;
  };

  WallMessageInboxRow.prototype.open = function() {
    return $.jGrowl("Open Message");
  };

  WallMessageInboxRow.prototype.reply = function() {
    return $.jGrowl("Reply Message");
  };

  WallMessageInboxRow.prototype.icon = function() {
    switch (this.row.get("detail").category) {
      case 0:
        return "sportivo";
      case 1:
        return "pro";
      case 2:
        return "pro";
      case 3:
        return "pro";
      case 4:
        return "pro";
      case 5:
        return "pro";
    }
  };

  WallMessageInboxRow.prototype.image = function() {
    return "" + (this.row.get("detail").urlImg) + "=s44-c?imgmax=44&crop=1";
  };

  WallMessageInboxRow.prototype.excerpt_template = function() {
    return $("#wall-message-row-template");
  };

  WallMessageInboxRow.prototype.excerpt_data = function() {
    var user;
    user = new User(this.row.get('detail')).data_for_render();
    return {
      nome: I18n.t("inbox.wall_message.title", {
        name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
      }),
      message: this.row.message().escape()
    };
  };

  WallMessageInboxRow.prototype.has_details = function() {
    return true;
  };

  WallMessageInboxRow.prototype.details_template = function() {
    return $("#reply-to-message-template");
  };

  WallMessageInboxRow.prototype.details = function() {
    var $el, message;
    var _this = this;
    message = this.row.get("playerMessage");
    $el = $("#reply-to-message-template").clone().removeAttr("id").removeClass("hidden").render(message, {
      ".message > .text .author_name": function(a) {
        var user;
        if ((a.context != null) && (a.context.playerSender != null)) {
          user = new User(a.context.playerSender).data_for_render();
          return I18n.t("inbox.wall_message.title", {
            name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
          });
        } else {
          return "";
        }
      },
      ".message > .text .date": function(a) {
        return Date.parse(a.context.date).strftime(Utils.date_format($.cookie("lang")));
      },
      ".message > .picture img@src": function(a) {
        if ((a.context != null) && (a.context.playerSender != null)) {
          return a.context.playerSender.urlImg + "=s38-c?imgmax=38&crop=1";
        } else {
          return "";
        }
      },
      ".message > .text .message_content": function(a) {
        return "" + (a.context.message.escape());
      },
      ".submessage": {
        'submessage <- playerSubMessageList': {
          '.picture img@src': function(a) {
            if (a.item.playerSender != null) {
              return a.item.playerSender.urlImg + "=s38-c?imgmax=38&crop=1";
            } else {
              return "";
            }
          },
          '.text .message_content': function(a) {
            return "" + (a.item.message.escape());
          },
          '.text .date': function(a) {
            return Date.parse(a.item.date).strftime(Utils.date_format($.cookie("lang")));
          },
          ".text .author_name": function(a) {
            var user;
            if (a.item.playerSender != null) {
              user = user = new User(a.item.playerSender).data_for_render();
              return I18n.t("inbox.wall_message.title", {
                name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
              });
            } else {
              return "";
            }
          }
        }
      }
    });
    $el.find("#send-reply").click(function() {
      message = new ProfileMessage({
        reply_to: _this.row.get("playerMessage").id
      });
      message.save({
        message: $el.find("textarea").val()
      }, {
        success: function() {
          $el.find("textarea").val("");
          if (_this.row.get("playerMessage").playerSubMessageList == null) {
            _this.row.get("playerMessage").playerSubMessageList = [];
          }
          _this.row.get("playerMessage").playerSubMessageList.push(message.attributes);
          return _this.$(".box-details").empty().append(_this.details());
        },
        error: function(model, errors) {
          return $.jGrowl(errors);
        }
      });
      return false;
    });
    return $el;
  };

  return WallMessageInboxRow;

})();

EventMessageInboxRow = (function() {

  __extends(EventMessageInboxRow, WallMessageInboxRow);

  function EventMessageInboxRow() {
    EventMessageInboxRow.__super__.constructor.apply(this, arguments);
  }

  EventMessageInboxRow.prototype.icon = function() {
    return "evento";
  };

  EventMessageInboxRow.prototype.image = function() {
    try {
      return this.row.get('detail').urlImg + "=s44-c?imgmax=44&crop=1";
    } catch (e) {
      return "";
    }
  };

  EventMessageInboxRow.prototype.excerpt_template = function() {
    return $("#wall-message-row-template");
  };

  EventMessageInboxRow.prototype.excerpt_data = function() {
    var event, user;
    try {
      user = new User(this.row.get('detail')).data_for_render();
      event = new Event(this.row.get('event')).data_for_render();
      return {
        nome: I18n.t("inbox.event_message.title", {
          event: "<a href='" + event.details_path + "'>" + (event.name.escape()) + "</a>",
          name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
        }),
        message: this.row.message().escape()
      };
    } catch (e) {
      return {
        nome: "...",
        message: "..."
      };
    }
  };

  EventMessageInboxRow.prototype.has_details = function() {
    return this.row.has_long_message();
  };

  EventMessageInboxRow.prototype.details = function() {
    var $el;
    $el = $("#event-message-details-template").clone().removeAttr("id").removeClass("hidden").autoRender({
      message: this.row.long_message()
    });
    return $el;
  };

  return EventMessageInboxRow;

})();

InviteEventInboxRow = (function() {

  __extends(InviteEventInboxRow, InboxRow);

  function InviteEventInboxRow() {
    InviteEventInboxRow.__super__.constructor.apply(this, arguments);
  }

  InviteEventInboxRow.prototype.icon = function() {
    return "invito-evento";
  };

  InviteEventInboxRow.prototype.image = function() {
    return this.row.get('detail').urlImg + "=s44-c?imgmax=44&crop=1";
  };

  InviteEventInboxRow.prototype.actions = function() {
    var actions;
    actions = InviteEventInboxRow.__super__.actions.apply(this, arguments);
    actions.push({
      "class": "no",
      event: "decline_invite",
      tipsy: "Declina l'invito!"
    });
    actions.push({
      "class": "si",
      event: "accept_invite",
      tipsy: "Accetta l'invito!"
    });
    return actions;
  };

  InviteEventInboxRow.prototype.accept_invite = function() {
    var event;
    var _this = this;
    event = new Event({
      id: this.row.get('eventId')
    });
    return event.perform_action({
      action: "accept",
      success: function() {
        $.jGrowl(I18n.t("inbox.invite_event.accepted"));
        return _this.delete_message();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  InviteEventInboxRow.prototype.decline_invite = function() {
    var event;
    var _this = this;
    event = new Event({
      id: this.row.get('eventId')
    });
    return event.perform_action({
      action: "decline",
      success: function() {
        $.jGrowl(I18n.t("inbox.invite_event.declined"));
        return _this.delete_message();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  InviteEventInboxRow.prototype.excerpt_template = function() {
    return $("#wall-message-row-template");
  };

  InviteEventInboxRow.prototype.excerpt_data = function() {
    var event, user;
    if (this.row.get('event')) {
      user = new User(this.row.get('event').organizerDetail).data_for_render();
      event = new Event(this.row.get('event')).data_for_render();
      return {
        nome: I18n.t("inbox.invite_event.title", {
          event: "<a href='" + event.details_path + "'>" + (event.name.escape()) + "</a>",
          name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
        }),
        message: event.message.escape()
      };
    }
  };

  InviteEventInboxRow.prototype.has_details = function() {
    var event;
    if (this.row.get('event')) {
      event = new Event(this.row.get('event')).data_for_render();
      return event.has_long_message;
    }
  };

  InviteEventInboxRow.prototype.details = function() {
    var $el, event;
    if (this.row.get('event')) {
      event = new Event(this.row.get('event')).data_for_render();
      $el = $("#event-message-details-template").clone().removeAttr("id").removeClass("hidden").autoRender({
        message: event.long_message
      });
    }
    return $el;
  };

  return InviteEventInboxRow;

})();

PartecipationRequestEventInboxRow = (function() {

  __extends(PartecipationRequestEventInboxRow, InboxRow);

  function PartecipationRequestEventInboxRow() {
    PartecipationRequestEventInboxRow.__super__.constructor.apply(this, arguments);
  }

  PartecipationRequestEventInboxRow.prototype.icon = function() {
    return "invito-evento";
  };

  PartecipationRequestEventInboxRow.prototype.image = function() {
    return this.row.get('detail').urlImg + "=s44-c?imgmax=44&crop=1";
  };

  PartecipationRequestEventInboxRow.prototype.actions = function() {
    var actions;
    actions = [];
    actions.push({
      "class": "no",
      event: "decline_request",
      tipsy: "Rifiuta la richiesta di partecipazione!"
    });
    actions.push({
      "class": "si",
      event: "accept_request",
      tipsy: "Accetta la richiesta di partecipazione!"
    });
    return actions;
  };

  PartecipationRequestEventInboxRow.prototype.accept_request = function() {
    var _this = this;
    return $.ajax({
      url: "/api/private/event_accept.json?eventId=" + (this.row.get('eventId')) + "&playerId=" + (this.row.get('detail').id),
      success: function() {
        $.jGrowl(I18n.t("inbox.request_partecipation_event.accepted"));
        return _this.delete_message();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  PartecipationRequestEventInboxRow.prototype.decline_request = function() {
    var _this = this;
    return $.ajax({
      url: "/api/private/event_decline.json?eventId=" + (this.row.get('eventId')) + "&playerId=" + (this.row.get('detail').id),
      success: function() {
        $.jGrowl(I18n.t("inbox.request_partecipation_event.declined"));
        return _this.delete_message();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  PartecipationRequestEventInboxRow.prototype.excerpt_template = function() {
    return $("#wall-message-row-template");
  };

  PartecipationRequestEventInboxRow.prototype.excerpt_data = function() {
    var event, user;
    user = new User(this.row.get('detail')).data_for_render();
    event = new Event(this.row.get('event')).data_for_render();
    return {
      nome: I18n.t("inbox.request_partecipation_event.title", {
        event: "<a href='" + event.details_path + "'>" + (event.name.escape()) + "</a>",
        name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
      }),
      message: event.message.escape()
    };
  };

  PartecipationRequestEventInboxRow.prototype.has_details = function() {
    var event;
    if (this.row.get('event')) {
      event = new Event(this.row.get('event')).data_for_render();
      return event.has_long_message;
    }
  };

  PartecipationRequestEventInboxRow.prototype.details = function() {
    var $el, event;
    if (this.row.get('event')) {
      event = new Event(this.row.get('event')).data_for_render();
      $el = $("#event-message-details-template").clone().removeAttr("id").removeClass("hidden").autoRender({
        message: event.long_message
      });
    }
    return $el;
  };

  return PartecipationRequestEventInboxRow;

})();

FeedbackEventInboxRow = (function() {

  __extends(FeedbackEventInboxRow, InboxRow);

  function FeedbackEventInboxRow() {
    FeedbackEventInboxRow.__super__.constructor.apply(this, arguments);
  }

  FeedbackEventInboxRow.prototype.icon = function() {
    return "feedback";
  };

  FeedbackEventInboxRow.prototype.image = function() {
    try {
      return this.row.get('event').organizerDetail.urlImg + "=s44-c?imgmax=44&crop=1";
    } catch (e) {
      return "";
    }
  };

  FeedbackEventInboxRow.prototype.excerpt_template = function() {
    return $("#wall-message-row-template");
  };

  FeedbackEventInboxRow.prototype.excerpt_data = function() {
    var event;
    event = new Event(this.row.get('event')).data_for_render();
    return {
      nome: I18n.t("inbox.event_feedback.title", {
        event: "<a href='" + event.details_path + "'>" + (event.name.escape()) + "</a>"
      }),
      message: I18n.t("inbox.event_feedback.message")
    };
  };

  FeedbackEventInboxRow.prototype.has_details = function() {
    return true;
  };

  FeedbackEventInboxRow.prototype.details = function() {
    var $container, view;
    var _this = this;
    $container = $("<div/>").addClass("clearfix");
    /*
        $.ajax
          type: "get"
          url: "/api/private/feedback_event/"+@row.get('event').id+".json"
          success: =>
            alert "test"
    */
    this.player_views = [];
    _.each(this.row.get('event').gamePlayersList, function(player) {
      var view;
      player = new Friend(player);
      if (!(player.get("playerId") === AppController.current_user().id || !player.get("accepted"))) {
        view = new FeedbackEventPlayerView({
          player: player,
          event: _this.row.get('event'),
          rating: 4
        });
        _this.player_views.push(view);
        return $container.append(view.render().el);
      }
    });
    if (this.row.get('event').businessId) {
      view = new FeedbackEventPlaceView({
        event: this.row.get('event'),
        rating: 4
      });
      this.structure_view = view;
      $container.append(view.render().el);
    }
    $container.append($("#feedback-event-vote-template").clone().removeAttr("id").removeClass("hidden"));
    $container.find("#feedback-vote").click(function() {
      return _this.give_feedback();
    });
    return $container;
  };

  FeedbackEventInboxRow.prototype.give_feedback = function() {
    var business_id, event_id, feedback, feedback_event, request_queue, struttura_feedback, _ref;
    var _this = this;
    request_queue = [];
    feedback = [];
    feedback_event = [];
    event_id = null;
    _.each(this.player_views, function(view) {
      var cleverness_feedback, player, reliability_feedback, _ref, _ref2;
      reliability_feedback = (_ref = view.reliability_feedback) != null ? _ref : 0;
      cleverness_feedback = (_ref2 = view.cleverness_feedback) != null ? _ref2 : 0;
      player = view.player;
      if (reliability_feedback) {
        Utils.log("give_feedback() : " + "player = " + player.get("playerId") + " reliability_feedback = " + reliability_feedback);
        feedback.push({
          playerIdTo: player.get("playerId"),
          rating: reliability_feedback
        });
      }
      if (cleverness_feedback) {
        Utils.log("give_feedback() : " + "player = " + player.get("playerId") + " event_id = " + event_id + " cleverness_feedback = " + cleverness_feedback);
        event_id = view.event_id;
        return feedback_event.push({
          playerIdTo: player.get("playerId"),
          rating: cleverness_feedback
        });
      }
    });
    if (this.row.get('event').businessId) {
      struttura_feedback = (_ref = this.structure_view.struttura_feedback) != null ? _ref : 0;
      business_id = this.row.get('event').businessId;
      if (struttura_feedback) {
        Utils.log("give_feedback() : " + "business_id = " + business_id + " struttura_feedback = " + struttura_feedback);
        feedback.push({
          playerIdTo: business_id,
          rating: struttura_feedback
        });
      }
    }
    if (feedback.length) {
      request_queue.push($.ajax({
        type: "post",
        url: "/api/private/feedback_list",
        contentType: 'application/json',
        data: JSON.stringify({
          feedbacks: feedback
        })
      }));
    }
    if (feedback_event.length) {
      request_queue.push($.ajax({
        type: "post",
        url: "/api/private/feedback_event_list?eventId=" + event_id,
        contentType: 'application/json',
        data: JSON.stringify({
          feedbackEvents: feedback_event
        })
      }));
    }
    return $.when.apply(this, request_queue).then(function() {
      _this.delete_message();
      return Utils.log("give_feedback() : SUCCESS, deleting inbox message.");
    }, function() {
      Utils.log("give_feedback() : ERROR, triggering error message.");
      return $.jGrowl(I18n.t("global.connection_error"));
    });
  };

  return FeedbackEventInboxRow;

})();

FeedbackEventPlayerView = (function() {

  __extends(FeedbackEventPlayerView, Backbone.View);

  function FeedbackEventPlayerView() {
    FeedbackEventPlayerView.__super__.constructor.apply(this, arguments);
  }

  FeedbackEventPlayerView.prototype.initialize = function(opts) {
    this.player = opts.player;
    this.event_id = opts.event.id;
    this.rating = opts.rating;
    this.el = $("#feedback-event-player-template").clone().removeAttr("id").removeClass("hidden").autoRender(this.player.data_for_render()).get(0);
    return this.delegateEvents({
      "mouseover .reliability-stars span": "hover_stars",
      "mouseover .cleverness-stars span": "hover_stars",
      "mouseleave .cleverness-stars span": "mouse_out_cleverness",
      "mouseleave .reliability-stars span": "mouse_out_reliability",
      "click .cleverness-stars span": "give_cleverness_feedback",
      "click .reliability-stars span": "give_reliability_feedback"
    });
  };

  FeedbackEventPlayerView.prototype.render = function() {
    if (!this.player.get('imageTeam')) this.$('.squadre').hide();
    return this;
  };

  FeedbackEventPlayerView.prototype.hover_stars = function(e) {
    $(e.currentTarget).parents(".stars").eq(0).find("span").removeClass("selected");
    return $(e.currentTarget).prevAll().add(e.currentTarget).addClass("selected");
  };

  FeedbackEventPlayerView.prototype.mouse_out_cleverness = function(e) {
    var $el;
    this.$(".cleverness-stars span").removeClass("selected");
    $el = this.$(".cleverness-stars span:nth(" + (this.cleverness_feedback - 1) + ")");
    return $el.prevAll().add($el[0]).addClass("selected");
  };

  FeedbackEventPlayerView.prototype.mouse_out_reliability = function(e) {
    var $el;
    this.$(".reliability-stars span").removeClass("selected");
    $el = this.$(".reliability-stars span:nth(" + (this.reliability_feedback - 1) + ")");
    return $el.prevAll().add($el[0]).addClass("selected");
  };

  FeedbackEventPlayerView.prototype.give_cleverness_feedback = function(e) {
    return this.cleverness_feedback = $(e.currentTarget).prevAll().length + 1;
  };

  FeedbackEventPlayerView.prototype.give_reliability_feedback = function(e) {
    return this.reliability_feedback = $(e.currentTarget).prevAll().length + 1;
  };

  return FeedbackEventPlayerView;

})();

FeedbackEventPlaceView = (function() {

  __extends(FeedbackEventPlaceView, Backbone.View);

  function FeedbackEventPlaceView() {
    FeedbackEventPlaceView.__super__.constructor.apply(this, arguments);
  }

  FeedbackEventPlaceView.prototype.initialize = function(opts) {
    this.event_id = opts.event.id;
    this.business_id = opts.event.businessId;
    this.el = $("#feedback-event-place-template").clone().removeAttr("id").removeClass("hidden").autoRender().get(0);
    this.place = new Place(opts.event.businessDetail);
    this.rating = opts.rating;
    return this.delegateEvents({
      "mouseover .struttura-stars span": "hover_stars",
      "mouseleave .struttura-stars span": "mouse_out_struttura",
      "click .struttura-stars span": "give_struttura_feedback"
    });
  };

  FeedbackEventPlaceView.prototype.render = function() {
    if (this.business_id) {
      this.$('.struttura .name').text(this.place.get('businessName'));
    }
    return this;
  };

  FeedbackEventPlaceView.prototype.hover_stars = function(e) {
    $(e.currentTarget).parents(".stars").eq(0).find("span").removeClass("selected");
    return $(e.currentTarget).prevAll().add(e.currentTarget).addClass("selected");
  };

  FeedbackEventPlaceView.prototype.mouse_out_struttura = function(e) {
    var $el;
    this.$(".struttura-stars span").removeClass("selected");
    $el = this.$(".struttura-stars span:nth(" + (this.struttura_feedback - 1) + ")");
    return $el.prevAll().add($el[0]).addClass("selected");
  };

  FeedbackEventPlaceView.prototype.give_struttura_feedback = function(e) {
    return this.struttura_feedback = $(e.currentTarget).prevAll().length + 1;
  };

  return FeedbackEventPlaceView;

})();

ProMessageInboxRow = (function() {

  __extends(ProMessageInboxRow, InboxRow);

  function ProMessageInboxRow() {
    ProMessageInboxRow.__super__.constructor.apply(this, arguments);
  }

  ProMessageInboxRow.prototype.actions = function() {
    var actions;
    actions = ProMessageInboxRow.__super__.actions.apply(this, arguments);
    actions.push({
      "class": "blocca",
      event: "block_pro",
      tipsy: "Blocca i messaggi di questo PRO!"
    });
    return actions;
  };

  ProMessageInboxRow.prototype.block_pro = function() {
    var _this = this;
    return $.ajax({
      type: "post",
      url: "/api/private/block_user/" + (this.row.get("detail").id) + ".json",
      data: {
        userId: this.row.get("detail").id
      },
      success: function() {
        $.jGrowl(I18n.t("inbox.new_pro_message.block_pro"));
        return _this.delete_message();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  ProMessageInboxRow.prototype.open = function() {
    return $.jGrowl("Open Message");
  };

  ProMessageInboxRow.prototype.reply = function() {
    return $.jGrowl("Reply Message");
  };

  ProMessageInboxRow.prototype.icon = function() {
    return "pro";
  };

  ProMessageInboxRow.prototype.image = function() {
    return "" + (this.row.get("detail").urlImg) + "=s44-c?imgmax=44&crop=1";
  };

  ProMessageInboxRow.prototype.excerpt_template = function() {
    return $("#wall-message-row-template");
  };

  ProMessageInboxRow.prototype.excerpt_data = function() {
    var user;
    user = new User(this.row.get('detail')).data_for_render();
    return {
      nome: I18n.t("inbox.wall_message.title", {
        name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
      }),
      message: this.row.message().escape()
    };
  };

  ProMessageInboxRow.prototype.has_details = function() {
    return true;
  };

  ProMessageInboxRow.prototype.details_template = function() {
    return $("#reply-to-message-template");
  };

  ProMessageInboxRow.prototype.details = function() {
    var $el, proMessage;
    var _this = this;
    proMessage = {
      message: this.row.get("message").value,
      playerSender: this.row.get("detail")
    };
    $el = $("#reply-to-message-pro-template").clone().removeAttr("id").removeClass("hidden").render(proMessage, {
      ".message > .text .author_name": function(a) {
        var user;
        if ((a.context != null) && (a.context.playerSender != null)) {
          user = new User(a.context.playerSender).data_for_render();
          return I18n.t("inbox.wall_message.title", {
            name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
          });
        } else {
          return "";
        }
      },
      ".message > .picture img@src": function(a) {
        if ((a.context != null) && (a.context.playerSender != null)) {
          return a.context.playerSender.urlImg + "=s32-c?imgmax=32&crop=1";
        } else {
          return "";
        }
      },
      ".message > .text .message_content": function(a) {
        return "" + (a.context.message.escape());
      },
      ".submessage": {
        'submessage <- playerSubMessageList': {
          '.picture img@src': function(a) {
            if (a.item.playerSender != null) {
              return a.item.playerSender.urlImg + "=s32-c?imgmax=32&crop=1";
            } else {
              return "";
            }
          },
          '.text .message_content': function(a) {
            return "" + (a.item.message.escape());
          },
          ".text .author_name": function(a) {
            var user;
            if (a.item.playerSender != null) {
              user = user = new User(a.item.playerSender).data_for_render();
              return I18n.t("inbox.wall_message.title", {
                name: "<a href='" + user.details_path + "'>" + (user.name.escape()) + "</a>"
              });
            } else {
              return "";
            }
          }
        }
      }
    });
    return $el;
  };

  return ProMessageInboxRow;

})();

InboxView = (function() {

  __extends(InboxView, PageView);

  function InboxView() {
    this.render = __bind(this.render, this);
    this.add_row = __bind(this.add_row, this);
    this.remove_row = __bind(this.remove_row, this);
    InboxView.__super__.constructor.apply(this, arguments);
  }

  InboxView.prototype.tagName = "div";

  InboxView.prototype.slug = function() {
    return "inbox-view";
  };

  InboxView.prototype.initialize = function() {
    var _this = this;
    $(this.el).empty().append($("#template_inbox_view-page").clone().removeClass("hidden").removeAttr("id"));
    if (AppController.current_user().get("category") === 0) {
      this.$("#pro").remove();
    }
    $("#inbox").click(function() {
      if (AppController.current_user().logged_in()) Utils.refresh_inbox_counter();
      return _this.inbox.reload();
    });
    this.delegateEvents({
      "click #load-more": "load_more"
    });
    this.inbox = new Inbox();
    this.inbox.bind('add', this.add_row);
    this.inbox.bind('remove', this.remove_row);
    return this.inbox.bind('reset', this.render);
  };

  InboxView.prototype.remove_row = function() {
    if (this.inbox.length === 0) {
      return this.$("#footer").html("<p style='padding-top: 10px'>" + (I18n.t('inbox.no_message')) + "</p>");
    }
  };

  InboxView.prototype.add_row = function(row) {
    var RowViewClass, row_view_classes, view;
    row_view_classes = {
      0: FriendshipRequestInboxRow,
      1: WallMessageInboxRow,
      2: EventMessageInboxRow,
      4: InviteEventInboxRow,
      5: FeedbackEventInboxRow,
      6: PartecipationRequestEventInboxRow,
      7: ProMessageInboxRow
    };
    RowViewClass = row_view_classes[row.get("type")];
    view = new RowViewClass({
      row: row,
      inbox: this
    });
    this.$("#messages").append(view.render().el);
    if (this.inbox.more_messages()) {
      return this.$("#load-more").show();
    } else {
      return this.$("#load-more").hide();
    }
  };

  InboxView.prototype.render = function() {
    var _this = this;
    this.$("#content").empty();
    this.$("#content").append('<div id="messages"></div>');
    this.$("#content").append('<div id="footer"></div>');
    if (this.inbox.length === 0 && !this.inbox.more_messages()) {
      this.$("#footer").html("<p style='padding-top: 10px'>" + (I18n.t('inbox.no_message')) + "</p>");
    } else {
      this.$("#footer").append($("#navigation-more").clone().removeClass('hidden'));
      this.$("#load-more").hide();
    }
    return this.inbox.each(function(row) {
      return _this.add_row(row);
    });
  };

  InboxView.prototype.load_more = function() {
    Utils.log("InboxView.load_more()");
    return this.inbox.load_more();
  };

  return InboxView;

})();

var EventMessageView, EventPlayerView, EventView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

EventMessageView = (function() {

  __extends(EventMessageView, Backbone.View);

  function EventMessageView() {
    EventMessageView.__super__.constructor.apply(this, arguments);
  }

  EventMessageView.prototype.tagName = "div";

  EventMessageView.prototype.events = {
    "click .reply": "toggle_reply_box",
    "click .delete": "delete_comment",
    "submit #post-comment": "post_comment"
  };

  EventMessageView.prototype.initialize = function(opts) {
    return this.message = opts.message;
  };

  EventMessageView.prototype.render = function() {
    var $inner, message, view, _i, _len, _ref;
    $inner = $("#template_show_event_view-message-page").clone().removeAttr("id").removeClass("hidden").autoRender({
      message: this.message.get("message"),
      date: Date.parse(this.message.get("date")).strftime(Utils.date_format($.cookie("lang"))),
      name: this.message.get("player").name,
      image: this.message.get("player").urlImg + "=s48-c?imgmax=48&crop=1",
      id: this.message.get("id"),
      user_details_path: "#/my_home/users/" + (this.message.get("player").id),
      'private': this.message.get("privateMessage") ? " (" + (I18n.t("messages.private")) + ")" : "",
      privateClass: this.message.get("privateMessage") ? "message-private" : ""
    });
    this.comments_container = $("#commenti", $inner);
    $(this.el).empty().append($inner);
    if (this.message.get("reply_to") != null) {
      this.$(".reply, .reply-box").remove();
    }
    if (this.message.get("player").id !== AppController.current_user().get("id")) {
      this.$(".delete").remove();
    }
    if (this.message.get("playerSubMessageList") != null) {
      _ref = this.message.get("playerSubMessageList");
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        message = _ref[_i];
        message = new EventMessage(_.extend(EventMessage.prototype.parse(message), {
          reply_to: this.message.get("id")
        }));
        view = new EventMessageView({
          message: message
        }).render();
        Utils.log(message, this.comments_container.length, view.el);
        this.comments_container.append(view.el);
        $(".sottocommenti", view.el).hide();
      }
    }
    return this;
  };

  EventMessageView.prototype.toggle_reply_box = function() {
    this.$(".reply-box").toggle();
    return false;
  };

  EventMessageView.prototype.post_comment = function() {
    var message;
    var _this = this;
    message = new EventMessage({
      reply_to: this.message.get("id")
    });
    message.save({
      message: this.$(".comment").val()
    }, {
      success: function() {
        var view;
        _this.$(".comment").val("");
        view = new EventMessageView({
          message: message
        }).render();
        return _this.comments_container.append(view.el);
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
    return false;
  };

  EventMessageView.prototype.delete_comment = function() {
    var _this = this;
    this.message.destroy({
      success: function() {
        return $(_this.el).remove();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  return EventMessageView;

})();

EventPlayerView = (function() {

  __extends(EventPlayerView, Backbone.View);

  function EventPlayerView() {
    EventPlayerView.__super__.constructor.apply(this, arguments);
  }

  EventPlayerView.prototype.tagName = "div";

  EventPlayerView.prototype.initialize = function(opts) {
    return this.player = opts.player;
  };

  EventPlayerView.prototype.render = function() {
    var $inner, f;
    f = new Friend(this.player);
    Utils.log(f.data_for_render());
    $inner = $("#template_show_event_view-player-page").clone().removeAttr("id").removeClass("hidden").autoRender(f.data_for_render());
    $(this.el).empty().append($inner);
    return this;
  };

  return EventPlayerView;

})();

EventView = (function() {

  __extends(EventView, PageView);

  function EventView() {
    EventView.__super__.constructor.apply(this, arguments);
  }

  EventView.prototype.tagName = "div";

  EventView.prototype.events = {
    "click #accepted-players": "filter_accepted",
    "click #unconfirmed-players": "filter_unconfirmed",
    "click #declined-players": "filter_declined",
    "click #waiting-for-acceptation-players": "filter_waiting_for_acceptation",
    "submit #post-comment": "post_message"
  };

  EventView.prototype.initialize = function(options) {
    var _this = this;
    this.event_id = options.id;
    this.event = new Event({
      id: this.event_id
    });
    this.event.fetch({
      success: function() {
        if (!_this.event.attributes.sportId) {
          $.jGrowl(I18n.t("global.event.not_existing"));
          document.location = "#/my_home/events";
          return;
        }
        _this.messages = _this.event.messages();
        return _this.messages.fetch({
          success: function() {
            _this.fetched = true;
            return _this.render();
          },
          error: function() {
            return $.jGrowl(I18n.t("global.connection_error"));
          }
        });
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    this.current_user = AppController.current_user();
    return this.delegateEvents();
  };

  EventView.prototype.slug = function() {
    return "tab-show-event";
  };

  EventView.prototype.data = function(opts) {
    return this.event.data_for_render(opts);
  };

  EventView.prototype.render = function() {
    var _this = this;
    if (this.fetched) {
      $(this.el).empty().append($("#template_show_event_view-page").clone().removeClass("hidden").autoRender(this.data({
        image_size: 115
      })));
      this.comments_container = this.$("#commenti");
      this.init_map();
      this.map.setCenter(this.event.latlng());
      this.marker = new google.maps.Marker({
        map: this.map,
        title: 'Posizione',
        position: this.event.latlng()
      });
      this.$("#box-risultato").empty();
      this.filter_accepted();
      this.messages.each(function(message) {
        var view;
        view = new EventMessageView({
          message: message
        }).render();
        return _this.comments_container.append(view.el);
      });
      return $(this.el).find("a.destroy_path").click(this.confirm_delete);
    }
  };

  EventView.prototype.filterPlayers = function(filters) {
    var player, players, _i, _len, _results;
    var _this = this;
    players = _.filter(this.event.get("gamePlayersList"), function(player) {
      var filter, value;
      for (filter in filters) {
        value = filters[filter];
        if (player[filter] !== value) return false;
      }
      return true;
    });
    this.$("#box-risultati").empty();
    _results = [];
    for (_i = 0, _len = players.length; _i < _len; _i++) {
      player = players[_i];
      _results.push((function(player) {
        var view;
        view = new EventPlayerView({
          player: player
        });
        return _this.$("#box-risultati").append(view.render().el);
      })(player));
    }
    return _results;
  };

  EventView.prototype.init_map = function() {
    return this.map = new google.maps.Map(this.$("#map-ev").css({
      height: 346
    }).get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  };

  EventView.prototype.filter_accepted = function(e) {
    if (e != null) {
      this.$("ul#filters li a").removeClass("w-current");
      $(e.target).addClass("w-current");
    }
    this.filterPlayers({
      accepted: true
    });
    return false;
  };

  EventView.prototype.filter_unconfirmed = function(e) {
    this.$("ul#filters li a").removeClass("w-current");
    $(e.target).addClass("w-current");
    this.filterPlayers({
      accepted: false,
      declined: false,
      requestPartecipate: null
    });
    return false;
  };

  EventView.prototype.filter_waiting_for_acceptation = function(e) {
    this.$("ul#filters li a").removeClass("w-current");
    $(e.target).addClass("w-current");
    this.filterPlayers({
      accepted: false,
      requestPartecipate: true
    });
    return false;
  };

  EventView.prototype.filter_declined = function(e) {
    this.$("ul#filters li a").removeClass("w-current");
    $(e.target).addClass("w-current");
    this.filterPlayers({
      declined: true
    });
    return false;
  };

  EventView.prototype.accept = function(e) {
    var _this = this;
    $.ajax({
      url: this.data().si_url,
      success: function(data) {
        if (data.requestParticipateEvent) {
          return _this.event.fetch({
            success: function() {
              return _this.render();
            }
          });
        } else {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  EventView.prototype.decline = function(e) {
    var _this = this;
    $.ajax({
      url: this.data().no_url,
      success: function() {
        return _this.event.fetch({
          success: function() {
            return _this.render();
          }
        });
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  EventView.prototype.post_message = function(e) {
    var message;
    var _this = this;
    message = new EventMessage;
    message.save({
      message: this.$("#message").val(),
      gameId: this.event.get("id")
    }, {
      success: function() {
        var view;
        _this.$("#message").val("");
        view = new EventMessageView({
          message: message
        }).render();
        return _this.comments_container.append(view.el);
      },
      error: function(model, errors) {
        return $.jGrowl(errors);
      }
    });
    return false;
  };

  EventView.prototype.confirm_delete = function() {
    return confirm(I18n.t("global.event.confirm_delete"));
  };

  return EventView;

})();

var NewProMessageView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

NewProMessageView = (function() {

  __extends(NewProMessageView, PageView);

  function NewProMessageView() {
    NewProMessageView.__super__.constructor.apply(this, arguments);
  }

  NewProMessageView.prototype.initialize = function(opts) {
    var _this = this;
    this.el = $("#template_new_message_pro_view-page").clone().removeClass("hidden").get(0);
    this.delegateEvents({
      "change #luoghi": "filter",
      "change #sport": "filter",
      "click #users": "filter_users",
      "click #pros": "filter_sports",
      "click #navigation .avanti": "next_page",
      "click #navigation .indietro": "previous_page",
      "click #invia": "send"
    });
    this.services = new MyProServices;
    this.services.fetch({
      success: function() {
        _this.user_sports = new MyUserSports;
        _this.services.each(function(service) {
          var is_new, k, s, sport, v, _i, _len, _ref, _ref2, _results;
          _ref = service.get('sportsMap');
          _results = [];
          for (k in _ref) {
            v = _ref[k];
            sport = new Sport({
              sportName: v,
              sportId: k
            });
            is_new = true;
            _ref2 = _this.user_sports.models;
            for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
              s = _ref2[_i];
              if (s.get("sportId") === sport.get("sportId")) is_new = false;
            }
            if (is_new) {
              _results.push(_this.user_sports.add(sport));
            } else {
              _results.push(void 0);
            }
          }
          return _results;
        });
        return _this.update_sports();
      }
    });
    this.pro_locations = new MyProLocations;
    this.pro_locations.fetch({
      success: function() {
        return _this.update_locations();
      }
    });
    return this.filter();
  };

  NewProMessageView.prototype.slug = function() {
    return "new-message-pro";
  };

  NewProMessageView.prototype.update_sports = function() {
    this.$("#sport").empty().append("<option value='' selected='selected'></option>");
    this.user_sports.each(function(sport) {
      return this.$("#sport").append("<option value='" + (sport.get("sportId")) + "'>" + (sport.get("sportName")) + "</option>");
    });
    return this.$("#sport").css('display', 'inline');
  };

  NewProMessageView.prototype.update_locations = function() {
    this.$("#luoghi").empty().append("<option value='' selected='selected'></option>");
    this.pro_locations.each(function(location, i) {
      var l;
      l = location.get("location");
      return this.$("#luoghi").append("<option value='" + l.latitude + "|" + l.longitude + "|" + l.address + "'>" + l.address + "</option>");
    });
    return this.$("#luoghi").css('display', 'inline');
  };

  NewProMessageView.prototype.filter = function() {
    var filter, luogo, sport;
    var _this = this;
    filter = {
      page: 0,
      per_page: 9
    };
    if (this.$("#users").is(".w-current")) {
      this.collection = AppController.current_user().friends();
      filter.per_page = 9;
      filter.per_page_multiplier = 2;
    } else {
      this.collection = new Pros();
      filter.per_page = 8;
      filter.per_page_multiplier = 1;
    }
    luogo = this.$("#luoghi option:selected", this).val();
    sport = this.$("#sport option:selected", this).val();
    if (luogo) {
      filter.latitude = luogo.split("|")[0];
      filter.longitude = luogo.split("|")[1];
    } else {
      filter.latitude = AppController.current_user().get("latitude");
      filter.longitude = AppController.current_user().get("longitude");
    }
    if (sport) filter.sport_id = sport;
    this.collection.set_filters(filter);
    this.collection.unbind("reset");
    this.collection.bind("reset", function() {
      return _this.render();
    });
    return this.collection.fetch();
  };

  NewProMessageView.prototype.filter_users = function(e) {
    $("#widget ul li a").removeClass("w-current");
    $(e.currentTarget).addClass("w-current");
    this.filter();
    return false;
  };

  NewProMessageView.prototype.filter_sports = function(e) {
    $("#widget ul li a").removeClass("w-current");
    $(e.currentTarget).addClass("w-current");
    this.filter();
    return false;
  };

  NewProMessageView.prototype.next_page = function() {
    this.collection.next_page();
    return this.collection.fetch();
  };

  NewProMessageView.prototype.previous_page = function() {
    this.collection.previous_page();
    return this.collection.fetch();
  };

  NewProMessageView.prototype.render = function() {
    var _this = this;
    Utils.log(this.collection);
    this.$('#box-risultati').empty();
    if (this.collection.filters.page === 0) {
      this.$('.indietro').hide();
    } else {
      this.$('.indietro').show();
    }
    if ((this.collection.filters.per_page * this.collection.filters.per_page_multiplier) > this.collection.length) {
      this.$('.avanti').hide();
    } else {
      this.$('.avanti').show();
    }
    this.collection.each(function(object) {
      var data, distance, template;
      if (_this.$("#users").is(".w-current")) {
        template = $("#template_users-view-results");
        data = object.data_for_render();
      } else {
        distance = object.get('distance');
        object = new Pro(object.get('pro'));
        object.set({
          distance: distance
        });
        data = object.data_for_render();
        template = $("#template_pros-view-results");
      }
      return template.clone().removeClass('hidden').removeAttr('id').autoRender(data).click(function() {
        return _this.add_user(object);
      }).appendTo(_this.$('#box-risultati'));
    });
    return this;
  };

  NewProMessageView.prototype.add_user = function(user) {
    var $el;
    var _this = this;
    this.selected_users || (this.selected_users = []);
    if (this.selected_users.indexOf(user.get("playerId")) !== -1) return;
    this.selected_users.push(user.get("playerId"));
    $el = $("#template_new-event-view-selected-friend").clone().removeClass('hidden').removeAttr('id').autoRender(user.data_for_render()).appendTo(this.$("#selected-users"));
    return $el.click(function() {
      return _this.remove_user(user, $el);
    });
  };

  NewProMessageView.prototype.remove_user = function(user, el) {
    var idx;
    if ((idx = this.selected_users.indexOf(user.get("playerId"))) !== -1) {
      this.selected_users.splice(idx, 1);
    }
    return el.remove();
  };

  NewProMessageView.prototype.send = function() {
    var message;
    var _this = this;
    message = new InboxMessage();
    message.save({
      message: this.$("textarea").val(),
      userIdsList: this.selected_users
    }, {
      success: function() {
        $.jGrowl("Messaggio inviato con successo");
        _this.selected_users = [];
        _this.$("#selected-users").empty();
        return _this.$("textarea").val("");
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  return NewProMessageView;

})();

var SignupStep0View;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SignupStep0View = (function() {

  __extends(SignupStep0View, PageView);

  function SignupStep0View() {
    SignupStep0View.__super__.constructor.apply(this, arguments);
  }

  SignupStep0View.prototype.initialize = function() {
    this.current_user = AppController.current_user();
    this.el = $("#template_signup_step0_view-page").clone().removeClass("hidden").get(0);
    return this.delegateEvents({
      "click .puls-sportivo": "select_sportivo",
      "click .puls-pro": "select_pro",
      "click .privacy-checkbox": "show_buttons"
    });
  };

  SignupStep0View.prototype.slug = function() {
    return "signup";
  };

  SignupStep0View.prototype.render = function() {
    $("#container").addClass("container0");
    return Utils.log("Render di Step 0");
  };

  SignupStep0View.prototype.select_sportivo = function() {
    return this.submit(0);
  };

  SignupStep0View.prototype.select_pro = function() {
    return this.submit(2);
  };

  SignupStep0View.prototype.show_buttons = function() {
    if (this.$(".privacy-checkbox:checked").length) {
      return this.$("#pulsanti").show();
    } else {
      return this.$("#pulsanti").hide();
    }
  };

  SignupStep0View.prototype.submit = function(category) {
    var _this = this;
    return this.current_user.save({
      "category": category
    }, {
      success: function(model, response) {
        $("#container").removeClass("container0");
        Utils.log("Successo, category = " + (_this.current_user.get("category")));
        if (_this.current_user.get("registration_complete")) {
          return document.location = "#/";
        } else {
          return _this.current_user.infer_attributes(function() {
            return document.location = "#/settings/1";
          });
        }
      },
      error: function(model, response) {
        $("#container").removeClass("container0");
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  return SignupStep0View;

})();

var SignupStep1View;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SignupStep1View = (function() {

  __extends(SignupStep1View, PageView);

  function SignupStep1View() {
    SignupStep1View.__super__.constructor.apply(this, arguments);
  }

  SignupStep1View.prototype.initialize = function() {
    SignupStep1View.__super__.initialize.apply(this, arguments);
    document.title = "We-Sport.com";
    this.current_user = AppController.current_user();
    this.el = $("#template_signup_step1_view-page").clone().removeClass("hidden").get(0);
    $(this.el).find("#tab a.modify-account").removeClass("hidden");
    $(this.el).find("#tab a.step1-back").hide();
    this.$('#upload-button').hide();
    this.events = {
      "click #step1-go": "step2",
      "click #step1-menu": "step1",
      "click #step2-menu": "step2",
      "click #step3-menu": "step3",
      "click #cerca-indirizzo": "geolocate_me",
      "click #geolocalizzami": "geolocate_html5",
      "click #reset-pass": "reset_password",
      "keyup #address": "geolocate_key",
      "click #upload-button": "upload_photo",
      "change #category": "change_form",
      "click #fileToUpload": "show_upload_button",
      "click .delete-account": "delete_account"
    };
    return this.delegateEvents();
  };

  SignupStep1View.prototype.slug = function() {
    return "signup";
  };

  SignupStep1View.prototype.show_upload_button = function() {
    return this.$('#upload-button').show();
  };

  SignupStep1View.prototype.render = function() {
    var attr, formRender, self, _i, _j, _len, _len2, _ref, _ref2;
    if (parseInt(this.current_user.get('category')) === 2) {
      this.current_form = this.$('#dati-pro').show();
      this.$('#dati-associazione, #dati').hide();
    } else if (parseInt(this.current_user.get('category')) === 1 || parseInt(this.current_user.get('category')) === 3 || parseInt(this.current_user.get('category')) === 4 || parseInt(this.current_user.get('category')) === 5) {
      this.current_form = this.$('#dati-associazione').show();
      this.$('#dati-associazione').val(this.current_user.get('category'));
      this.$('#dati-pro, #dati').hide();
    } else {
      this.current_form = this.$('#dati').show();
      this.$('#dati-pro, #dati-associazione').hide();
      this.$('.address-hint').text(I18n.t("settings.step1.address_hint"));
    }
    this.infer_attributes;
    this.$('#step1-menu').css('opacity', '1');
    this.$('#step2-menu').css('opacity', '0.5');
    this.$('#step3-menu').css('opacity', '0.5');
    if (!this.current_user.get("registration_complete")) {
      this.$('#step2-menu a').hide();
      this.$('#step3-menu a').hide();
    }
    this.$("#address").val(this.current_user.get("address"));
    Utils.log("Render di Step 1");
    _ref = ["#dati-pro", "#dati-associazione", "#dati"];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      formRender = _ref[_i];
      _ref2 = ["email", "first_name", "last_name", "age", "gender", "address", "website", "phone", "contact_name", "business_name", "category"];
      for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
        attr = _ref2[_j];
        Utils.log(attr, this.current_user.get(attr));
        $(formRender).find("#" + attr).val(this.current_user.get(attr));
      }
    }
    if (this.current_user.get("img")) {
      this.$("#foto img").attr("src", this.current_user.get("img") + "=s105-c?imgmax=105&crop=1");
    }
    this.map = new google.maps.Map(this.$("#map-step1").get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    this.marker = new google.maps.Marker({
      map: this.map,
      title: 'Mia posizione',
      position: this.current_user.latlng()
    });
    this.marker.setDraggable(true);
    self = this;
    google.maps.event.addListener(this.marker, 'dragend', function() {
      var location;
      location = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
      self.user_location = {
        latitude: this.getPosition().lat(),
        longitude: this.getPosition().lng()
      };
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return self.$("#address").val(results[0].formatted_address);
        }
      });
    });
    this.user_location = {
      latitude: this.current_user.get("latitude"),
      longitude: this.current_user.get("longitude")
    };
    if (navigator.geolocation == null) return this.$('#geolocalizzami').hide();
  };

  SignupStep1View.prototype.geolocate_key = function(e) {
    if (e.keyCode === 13) return this.geolocate_me();
  };

  SignupStep1View.prototype.geolocate_me = function() {
    var _this = this;
    return Utils.geocode(this.$("#address").val(), function(location) {
      _this.user_location = location;
      _this.map.setCenter(location.latlng);
      return _this.marker.setPosition(location.latlng);
    });
  };

  SignupStep1View.prototype.geolocate_html5 = function() {
    var _this = this;
    if (navigator.geolocation == null) return;
    return navigator.geolocation.getCurrentPosition(function(position) {
      var location;
      location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      _this.map.setCenter(location);
      _this.marker.setPosition(location);
      _this.user_location = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude
      };
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return this.$("#address").val(results[0].formatted_address);
        }
      });
    }, function(error) {
      return $.jGrowl(error);
    });
  };

  SignupStep1View.prototype.reset_password = function() {
    return $.ajax({
      url: ApplicationScript.RestUrl("user.change.password", SessionKey),
      type: "get",
      dataType: "jsonp",
      data: {
        OldPassword: this("#old-password").val(),
        NewPassword: this("#new-password").val()
      },
      success: function(data) {
        if (data._responseStatus === "") {
          return $.jGrowl("Success!");
        } else {
          return $.jGrowl("Fail: " + data._responseStatus);
        }
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  SignupStep1View.prototype.formId = function() {
    return ["dati", "dati-associazione", "dati-pro"];
  };

  SignupStep1View.prototype.category = function() {
    return parseInt(this.current_user.get('category'));
  };

  SignupStep1View.prototype.save_user = function(success) {
    var attr, attrs, errors, _i, _len, _ref;
    var _this = this;
    attrs = {};
    _ref = ["email", "first_name", "last_name", "age", "gender", "website", "phone", "contact_name", "business_name"];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      attr = _ref[_i];
      attrs[attr] = this.current_form.find("#" + attr).val();
    }
    attrs["address"] = this.$("#address").val();
    if (this.current_user.get("category") !== 0) {
      if (this.category() === 2) {
        attrs["category"] = this.$("#" + (this.formId()[this.category()]) + " #category").val();
      } else {
        attrs["category"] = this.$("#" + (this.formId()[1]) + " #category").val();
      }
    }
    if (this.user_location != null) {
      attrs.latitude = this.user_location.latitude;
      attrs.longitude = this.user_location.longitude;
    } else {
      this.user_location = {};
    }
    errors = [];
    if (!Utils.is_nonempty_string(attrs.address)) {
      errors.push(I18n.t("global.user.errors.address"));
    }
    if (!(Utils.is_number(this.user_location.longitude) && Utils.is_number(this.user_location.latitude))) {
      errors.push(I18n.t("global.user.errors.marker"));
    }
    if (this.current_user.get("category") === 0) {
      if (!Utils.is_email(attrs.email)) {
        errors.push(I18n.t("global.user.errors.email"));
      }
      if (!Utils.is_name(attrs.first_name)) {
        errors.push(I18n.t("global.user.errors.first_name"));
      }
      if (!Utils.is_name(attrs.last_name)) {
        errors.push(I18n.t("global.user.errors.last_name"));
      }
      if (!Utils.is_unsigned_int(attrs.age)) {
        errors.push(I18n.t("global.user.errors.age"));
      }
    } else if (attrs["category"] === "2") {
      if (!Utils.is_name(attrs.business_name)) {
        errors.push(I18n.t("global.user.errors.business_name"));
      }
      if (!Utils.is_unsigned_int(attrs.age)) {
        errors.push(I18n.t("global.user.errors.age"));
      }
      if (!Utils.is_nonempty_string(attrs.contact_name)) {
        errors.push(I18n.t("global.user.errors.contact"));
      }
      if (!Utils.is_numeric(attrs.phone)) {
        errors.push(I18n.t("global.user.errors.phone"));
      }
    } else if (attrs["category"] === "1") {
      if (!Utils.is_name(attrs.business_name)) {
        errors.push(I18n.t("global.user.errors.business_name"));
      }
      if (!Utils.is_nonempty_string(attrs.contact_name)) {
        errors.push(I18n.t("global.user.errors.contact"));
      }
      if (!Utils.is_numeric(attrs.phone)) {
        errors.push(I18n.t("global.user.errors.phone"));
      }
    }
    if (errors.length > 0) {
      $.jGrowl(errors[0]);
      return false;
    }
    Utils.log("Invio dei seguenti parametri:", attrs);
    return this.current_user.save(attrs, {
      success: function(model, response) {
        Utils.log("Inviato con successo!");
        if ($.isFunction(success)) return success();
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  SignupStep1View.prototype.upload_photo = function(success) {
    var _this = this;
    if (this.$('input[name="datafile"]').val().length > 0) {
      return $.ajax({
        url: "/api/private/createUploadProfilePicture",
        dataType: 'text',
        success: function(data) {
          var url;
          url = data.replace(/http:\/\/.*?\//, '/');
          return _this.$('#img-form').attr('action', url).ajaxForm({
            dataType: 'text',
            data: {
              defaultImg: true
            },
            iframe: true,
            success: function(data, status, xhr) {
              var oldUrl;
              Utils.log("Inviato con successo!");
              oldUrl = _this.current_user.get("img");
              return AppController.current_user().fetch({
                success: function(result) {
                  _this.$('input[name="datafile"]').val("");
                  _this.$('input[name="datafile"]').attr("value", "");
                  _this.$('#upload-button').hide();
                  if (oldUrl === _this.current_user.get("img")) {
                    return $.jGrowl(I18n.t("settings.step1.upload_error"));
                  } else {
                    _this.$("#foto img").attr("src", _this.current_user.get("img") + "=s105-c?imgmax=105&crop=1");
                    if ($.isFunction(success)) return success();
                  }
                }
              });
            },
            error: function(data, status, xhr) {
              Utils.log("Inviato con errore!");
              _this.$('input[name="datafile"]').val("");
              _this.$('#upload-button').hide();
              return $.jGrowl(I18n.t("settings.step1.upload_error"));
            }
          }).submit();
        },
        error: function() {
          return $.jGrowl(I18n.t("settings.step1.upload_error"));
        }
      });
    } else {
      if ($.isFunction(success)) return success();
    }
  };

  SignupStep1View.prototype.change_form = function(event) {
    var $el;
    $el = $(event.target);
    if ($el.val() === "2") {
      this.current_form = this.$('#dati-pro').show();
      this.$('#dati-associazione').hide();
      this.$('#dati-pro #category').val('2');
    }
    if ($el.val() === "1" || $el.val() === "3" || $el.val() === "4" || $el.val() === "5") {
      this.$('#dati-pro').hide();
      this.current_form = this.$('#dati-associazione').show();
      return this.$('#dati-associazione #category').val($el.val());
    }
  };

  SignupStep1View.prototype.delete_account = function() {
    AppController.current_user().delete_account();
    return false;
  };

  SignupStep1View.prototype.step1 = function() {
    return false;
  };

  SignupStep1View.prototype.step3 = function() {
    if (this.current_user.get('registration_complete')) {
      this.save_user(function() {
        return document.location = "#/settings/3";
      });
    }
    return false;
  };

  SignupStep1View.prototype.step2 = function() {
    this.save_user(function() {
      return document.location = "#/settings/2";
    });
    return false;
  };

  return SignupStep1View;

})();

var SignupSportView, SignupStep2View;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SignupSportView = (function() {

  __extends(SignupSportView, Backbone.View);

  function SignupSportView() {
    SignupSportView.__super__.constructor.apply(this, arguments);
  }

  SignupSportView.prototype.initialize = function(options) {
    var _this = this;
    this.schedule = options.schedule || new Schedule({
      sportId: options.sport.id,
      sportName: options.sport.name
    });
    this.schedules = options.schedules.models;
    this.schedules.push(this.schedule);
    Utils.log("Schedule finale", this.schedule);
    this.el = $("#box-mio-sport").clone().autoRender(this.schedule.toJSON()).removeAttr("id").removeClass("hidden").get(0);
    this.times_template = this.$("#template_schedule-times").clone().removeClass("hidden");
    this.sport_ability = 2;
    if (this.schedule.get("levelId")) {
      this.change_ability({
        target: this.$(".abilita span[data-value='" + (this.schedule.get("levelId")) + "']").get(0)
      });
    }
    if (this.schedule.get("listSchedule") instanceof Array) {
      if (this.schedule.get("listSchedule").length === 0) {
        this.$("#all-days").attr("checked", "checked");
        this.toggle_time_slots();
      } else {
        _.each(this.schedule.get("listSchedule"), function(timeslot) {
          return _this.add_time_slot(timeslot);
        });
      }
      this.minimize();
    } else {
      this.$("#all-days").attr("checked", "checked");
      this.toggle_time_slots();
    }
    return this.delegateEvents({
      "click .salva": "save",
      "click .box-sport": "toggle_visibility",
      "click .open": "toggle_visibility",
      "click .delete-sport": "delete",
      "click .abilita span": "change_ability",
      "click #add-time": "add_time_slot",
      "click #del-time": "del_time_slot",
      "change #all-days": "toggle_time_slots"
    });
  };

  SignupSportView.prototype["delete"] = function() {
    var i, s, _i, _len, _ref, _results;
    if (!this.schedule.isNew()) this.schedule.destroy(this.schedule.get("id"));
    $(this.el).remove();
    i = 0;
    _ref = this.schedules;
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      s = _ref[_i];
      if (s && (s.get("sportId") === this.schedule.get("sportId"))) {
        this.schedules.splice(i, 1);
      }
      _results.push(i++);
    }
    return _results;
  };

  SignupSportView.prototype.toggle_time_slots = function() {
    if (this.$("#all-days").is(":checked")) {
      return this.$("#times").hide();
    } else {
      this.$("#times").show();
      if (this.$(".schedules").children().length < 1) return this.add_time_slot();
    }
  };

  SignupSportView.prototype.add_time_slot = function(timeslot) {
    var $slot;
    $slot = this.times_template.clone();
    if (timeslot && (timeslot.startTime != null)) {
      $slot.find(".day").val(timeslot.dayOfWeek);
      $slot.find(".startTimeH").val(timeslot.startTime.split(":")[0]);
      $slot.find(".startTimeM").val(timeslot.startTime.split(":")[1]);
      $slot.find(".endTimeH").val(timeslot.endTime.split(":")[0]);
      $slot.find(".endTimeM").val(timeslot.endTime.split(":")[1]);
    }
    return this.$(".schedules").append($slot);
  };

  SignupSportView.prototype.del_time_slot = function(event) {
    var el;
    el = $(event.target);
    return $(el).parent().remove();
  };

  SignupSportView.prototype.save = function() {
    var data, errors, time_slots;
    var _this = this;
    time_slots = [];
    errors = [];
    if (!this.$("#all-days").is(":checked")) {
      this.$(".schedules > *").each(function() {
        var eh, em, et, sh, sm, st;
        sh = $(".startTimeH option:selected", this).val();
        sm = $(".startTimeM option:selected", this).val();
        eh = $(".endTimeH option:selected", this).val();
        em = $(".endTimeM option:selected", this).val();
        st = parseInt(sh * 60 + sm);
        et = parseInt(eh * 60 + em);
        if (st > et) {
          return errors.push(I18n.t("global.signup.errors.invalid_time_range", {
            start: "" + sh + ":" + sm,
            end: "" + eh + ":" + em
          }));
        } else {
          return time_slots.push({
            dayOfWeek: $(".day option:selected", this).val(),
            startTime: "" + sh + ":" + sm,
            endTime: "" + eh + ":" + em
          });
        }
      });
    }
    if (errors.length > 0) {
      $.jGrowl(errors[0]);
      return;
    }
    data = {
      levelId: this.sport_ability,
      listSchedule: time_slots,
      levelDescription: this.$("textarea").val()
    };
    Utils.log(data);
    return this.schedule.save(data, {
      success: function() {
        return _this.toggle_visibility();
      },
      error: function(model, error) {
        return $.jGrowl(error);
      }
    });
  };

  SignupSportView.prototype.toggle_visibility = function() {
    return this.$(".expand").toggle();
  };

  SignupSportView.prototype.minimize = function() {
    return this.$(".expand").hide();
  };

  SignupSportView.prototype.change_ability = function(event) {
    var $el;
    $el = $(event.target);
    this.sport_ability = parseInt($el.attr("data-value"));
    this.$(".livello span").attr("class", $el.attr("class"));
    return this.$(".livello span").attr("tooltip", $el.attr("tooltip"));
  };

  SignupSportView.prototype.render = function() {
    return this;
  };

  return SignupSportView;

})();

SignupStep2View = (function() {

  __extends(SignupStep2View, PageView);

  function SignupStep2View() {
    SignupStep2View.__super__.constructor.apply(this, arguments);
  }

  SignupStep2View.prototype.initialize = function() {
    var _this = this;
    this.current_user = AppController.current_user();
    this.schedules = new Schedules;
    this.el = $("#template_signup_step2_view-page").clone().removeClass("hidden").get(0);
    this.delegateEvents({
      "click #step1-menu": "step1",
      "click #step2-menu": "step2",
      "click #step3-menu": "step3",
      "click .forward": "step3",
      "click .back": "step1",
      "click #add-other": "add_other_sport",
      "click #add-special": "add_special_sport",
      "click .delete-account": "delete_account"
    });
    this.schedules.bind("change", function() {
      return _this.show_sport_warning();
    });
    return SignupStep2View.__super__.initialize.apply(this, arguments);
  };

  SignupStep2View.prototype.slug = function() {
    return "signup";
  };

  SignupStep2View.prototype.show_sport_warning = function() {
    if (this.schedules.length > 0) {
      return this.$('#re-dx .sport-warning').hide();
    } else {
      return this.$('#re-dx .sport-warning').show();
    }
  };

  SignupStep2View.prototype.render = function() {
    var _this = this;
    this.$('#step1-menu').css('opacity', '0.5');
    this.$('#step2-menu').css('opacity', '1');
    this.$('#step3-menu').css('opacity', '0.5');
    if (!this.current_user.get("registration_complete")) {
      this.$('#step3-menu a').hide();
    }
    this.render_sports();
    if (this.schedules.length === 0) {
      this.schedules.userId = this.current_user.get("id");
      return this.schedules.fetch({
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        },
        success: function() {
          _this.schedules.each(function(s) {
            return _this.add_sport(s);
          });
          _this.fetched_schedules = true;
          return _this.show_sport_warning();
        }
      });
    } else {
      return this.show_sport_warning();
    }
  };

  SignupStep2View.prototype.add_dropbox_sport = function(dropbox) {
    var selected;
    if (!this.fetched_schedules) return;
    selected = $(dropbox).find("option:selected");
    return this.add_sport({
      name: selected.text(),
      id: selected.val()
    });
  };

  SignupStep2View.prototype.add_special_sport = function() {
    return this.add_dropbox_sport("#special-sports");
  };

  SignupStep2View.prototype.add_other_sport = function() {
    return this.add_dropbox_sport("#other-sports");
  };

  SignupStep2View.prototype.add_sport = function(sport) {
    var schedule, sport_view, _i, _len, _ref;
    var _this = this;
    this.sport_boxes || (this.sport_boxes = []);
    _.each(this.sport_boxes, function(sport_view) {
      return sport_view.minimize();
    });
    _ref = this.schedules.models;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      schedule = _ref[_i];
      if (parseInt(schedule.get("sportId")) === parseInt(sport.id || sport.get("sportId"))) {
        return;
      }
    }
    if (sport instanceof Schedule) {
      Utils.log("Schedule:", sport);
      sport_view = new SignupSportView({
        schedules: this.schedules,
        schedule: sport
      });
    } else {
      Utils.log("Sport:", sport);
      sport_view = new SignupSportView({
        schedules: this.schedules,
        sport: sport
      });
    }
    return this.$("#profili-sport").prepend(sport_view.render().el);
  };

  SignupStep2View.prototype.save = function(success) {
    var _this = this;
    return this.schedules.fetch({
      success: function() {
        if (_this.schedules.length > 0) {
          return success();
        } else {
          return $.jGrowl(I18n.t("global.signup.messages.min_one_sport"));
        }
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  SignupStep2View.prototype.delete_account = function() {
    AppController.current_user().delete_account();
    return false;
  };

  SignupStep2View.prototype.step1 = function() {
    this.save(function() {
      return document.location = "#/settings/1";
    });
    return false;
  };

  SignupStep2View.prototype.step3 = function() {
    this.save(function() {
      return document.location = "#/settings/3";
    });
    return false;
  };

  SignupStep2View.prototype.step2 = function() {
    return false;
  };

  SignupStep2View.prototype.render_sports = function(type, location, model) {
    var sports;
    var _this = this;
    sports = new Sports();
    return sports.fetch({
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      },
      success: function(collection, response) {
        var map, sport, sports1, sports23, _fn, _fn2, _i, _j, _k, _len, _len2, _len3, _ref;
        _this.$("#n-user .sports, #other-sports, #special-sports").empty();
        map = {
          1: {
            template: '#profilo-sport',
            appendTo: '#n-user .sports'
          },
          2: {
            template: false,
            appendTo: "#other-sports"
          },
          3: {
            template: false,
            appendTo: "#special-sports"
          }
        };
        sports1 = [];
        sports23 = [];
        _ref = response.allsports;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          sport = _ref[_i];
          if (sport.flagImportance === 1) {
            sports1.push(sport);
          } else {
            sports23.push(sport);
          }
        }
        sports1.sort(function(a, b) {
          return b.counter - a.counter;
        });
        _fn = function(sport) {
          return $("<option value='" + sport.id + "'>" + sport.name + "</option>").appendTo(map[sport.flagImportance].appendTo);
        };
        for (_j = 0, _len2 = sports23.length; _j < _len2; _j++) {
          sport = sports23[_j];
          _fn(sport);
        }
        _fn2 = function(sport) {
          sport.counter = "(" + sport.counter + ")";
          return $('#profilo-sport').clone().removeClass('hidden').autoRender(sport).removeAttr('id').click(function() {
            return _this.add_sport(sport);
          }).appendTo('#n-user .sports');
        };
        for (_k = 0, _len3 = sports1.length; _k < _len3; _k++) {
          sport = sports1[_k];
          _fn2(sport);
        }
        return _this.$(".aggiungi").css("display", "inline");
      }
    });
  };

  return SignupStep2View;

})();

var SignupStep2ProServiceView, SignupStep2ProView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SignupStep2ProServiceView = (function() {

  __extends(SignupStep2ProServiceView, Backbone.View);

  function SignupStep2ProServiceView() {
    SignupStep2ProServiceView.__super__.constructor.apply(this, arguments);
  }

  SignupStep2ProServiceView.prototype.tagName = "div";

  SignupStep2ProServiceView.prototype.events = {
    "click #add-other": "add_other_sport",
    "click #add-special": "add_special_sport",
    "click #save": "save",
    "click #delete": "destroy",
    "click .open": "toggle_expand"
  };

  SignupStep2ProServiceView.prototype.initialize = function(opts) {
    var _this = this;
    this.master = opts.master;
    this.undestroyable = opts.undestroyable;
    if ((opts != null) && (opts.service != null)) {
      this.service = opts.service;
    } else {
      this.service = new Service;
    }
    if (this.undestroyable) {
      this.service.set({
        'principal': true
      }, {
        silent: true
      });
    } else {
      this.service.set({
        'principal': false
      }, {
        silent: true
      });
    }
    this.service.set({
      sportIdsList: _.uniq(this.service.get('sportIdsList')) || []
    }, {
      silent: true
    });
    this.master.sports.unbind("reset");
    return this.master.sports.bind("reset", function() {
      return _this.render_sports();
    });
  };

  SignupStep2ProServiceView.prototype.render = function() {
    var _this = this;
    $(this.el).empty().append($("#template-signup2-pro-service").clone().removeClass("hidden").removeAttr("id").get(0));
    this.render_sports();
    this.hide();
    if (this.undestroyable) this.$("#delete").remove();
    this.$("#service-name").val((this.service.get("serviceName") || "").capitalize()).autocomplete({
      source: function(request, response) {
        return $.getJSON('/api/autocomplete_service.json?prefix=' + request.term, function(data) {
          var events, result, _i, _len, _ref;
          events = [];
          Utils.log(data);
          _ref = data.result;
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            result = _ref[_i];
            events.push({
              label: result.description.capitalize(),
              serviceId: result.id
            });
          }
          return response(events);
        });
      },
      select: function(event, ui) {
        _this.service.set({
          serviceName: ui.item.label,
          serviceId: ui.item.serviceId
        }, {
          silent: true
        });
        return Utils.log({
          serviceName: ui.item.label,
          serviceId: ui.item.serviceId
        });
      }
    }).keyup(function(e) {
      var serviceName;
      serviceName = $(e.target).val();
      if (_this.service.get("serviceName") !== serviceName) {
        _this.service.set({
          serviceName: serviceName,
          serviceId: null
        }, {
          silent: true
        });
        return Utils.log({
          serviceName: serviceName,
          serviceId: null
        });
      }
    });
    this.$("#service-name").placeholder();
    this.$("#service-name").live('focus blur', function() {
      return $(this).placeholder();
    });
    return this;
  };

  SignupStep2ProServiceView.prototype.add_dropbox_sport = function(dropbox) {
    var selected;
    selected = this.$(dropbox).find("option:selected");
    return this.add_sport({
      name: selected.text(),
      id: selected.val()
    });
  };

  SignupStep2ProServiceView.prototype.add_special_sport = function() {
    return this.add_dropbox_sport("#special-sports");
  };

  SignupStep2ProServiceView.prototype.add_other_sport = function() {
    return this.add_dropbox_sport("#other-sports");
  };

  SignupStep2ProServiceView.prototype.render_sports = function() {
    var map, sport, sportObj, sports1, sports23, _fn, _fn2, _i, _j, _k, _len, _len2, _len3, _ref;
    var _this = this;
    this.$("#sport-principali-col .sports, #other-sports, #special-sports").empty();
    map = {
      1: {
        template: '#template-profilo-sport',
        appendTo: '#sport-principali-col .sports'
      },
      2: {
        template: "option",
        appendTo: '#other-sports'
      },
      3: {
        template: "option",
        appendTo: '#special-sports'
      }
    };
    sports1 = [];
    sports23 = [];
    _ref = this.master.sports.models;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      sport = _ref[_i];
      sportObj = {
        id: sport.get('id'),
        name: sport.get('name'),
        counter: sport.get('counter'),
        flagImportance: sport.get('flagImportance')
      };
      sport = sportObj;
      if (sport.flagImportance === 1) {
        sports1.push(sportObj);
      } else {
        sports23.push(sportObj);
      }
    }
    sports1.sort(function(a, b) {
      return b.counter - a.counter;
    });
    _fn = function(sport) {
      $("<option value='" + sport.id + "'>" + sport.name + "</option>").appendTo(_this.$(map[sport.flagImportance].appendTo));
      if (_this.service.get('sportIdsList') && ((_this.service.get('sportIdsList')).indexOf(sport.id) >= 0)) {
        return _this.add_sport(sport, true);
      }
    };
    for (_j = 0, _len2 = sports23.length; _j < _len2; _j++) {
      sport = sports23[_j];
      _fn(sport);
    }
    _fn2 = function(sport) {
      sport.counter = "(" + sport.counter + ")";
      $('#profilo-sport').clone().removeClass('hidden').autoRender(sport).click(function() {
        return _this.add_sport(sport);
      }).appendTo(_this.$('#sport-principali-col .sports'));
      if (_this.service.get('sportIdsList') && ((_this.service.get('sportIdsList')).indexOf(sport.id) >= 0)) {
        return _this.add_sport(sport, true);
      }
    };
    for (_k = 0, _len3 = sports1.length; _k < _len3; _k++) {
      sport = sports1[_k];
      _fn2(sport);
    }
    return this.$(".aggiungi").css("display", "inline");
  };

  SignupStep2ProServiceView.prototype.remove_sport = function($sport, sport) {
    var idx;
    if (this.service.get('sportIdsList') && ((idx = (this.service.get('sportIdsList')).indexOf(sport.id)) !== -1)) {
      this.service.get('sportIdsList').splice(idx, 1);
    }
    if (this.service.get('sportIdsList') && this.service.get('sportIdsList').length === 0) {
      this.$(".livello span").attr("class", "icona-servizi-d");
    }
    return $sport.remove();
  };

  SignupStep2ProServiceView.prototype.add_sport = function(sport, firstime) {
    var $sport, idx, sportIdsArr;
    var _this = this;
    if (this.service.get('sportIdsList') && ((idx = (this.service.get('sportIdsList')).indexOf(sport.id)) !== -1) && !firstime) {
      return;
    }
    if (this.service.get('sportIdsList')) {
      this.service.get('sportIdsList').push(sport.id);
    } else {
      sportIdsArr = [];
      sportIdsArr.push(sport.id);
      this.service.set({
        sportIdsList: sportIdsArr
      }, {
        silent: true
      });
    }
    $sport = $("#template-associated-sport").clone().removeClass("hidden").removeAttr("id").autoRender(sport);
    $sport.click(function() {
      return _this.remove_sport($sport, sport);
    });
    this.$("#associated-sports").prepend($sport);
    this.service.set({
      sportIdsList: _.uniq(this.service.get('sportIdsList'))
    }, {
      silent: true
    });
    return this.$(".livello span").attr("class", "icona-servizi");
  };

  SignupStep2ProServiceView.prototype.save = function() {
    if (this.service.save(this.service.attributes, {
      error: function(model, response) {
        if (response && response.responseText) {
          return $.jGrowl(response.responseText);
        } else {
          return $.jGrowl(response);
        }
      }
    })) {
      this.$(".expand").hide();
    }
    return false;
  };

  SignupStep2ProServiceView.prototype.destroy = function() {
    var _this = this;
    if (this.service.isNew()) {
      $(this.el).remove();
      return this.master.remove_service(this);
    } else {
      this.service.is_destroying = true;
      return this.service.destroy({
        success: function() {
          $(_this.el).remove();
          return _this.master.remove_service(_this);
        },
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    }
  };

  SignupStep2ProServiceView.prototype.toggle_expand = function() {
    this.$(".expand").toggle();
    return false;
  };

  SignupStep2ProServiceView.prototype.hide = function() {
    this.$(".expand").hide();
    return false;
  };

  SignupStep2ProServiceView.prototype.show = function() {
    this.$(".expand").show();
    return false;
  };

  return SignupStep2ProServiceView;

})();

SignupStep2ProView = (function() {

  __extends(SignupStep2ProView, PageView);

  function SignupStep2ProView() {
    SignupStep2ProView.__super__.constructor.apply(this, arguments);
  }

  SignupStep2ProView.prototype.initialize = function() {
    var _this = this;
    SignupStep2ProView.__super__.initialize.apply(this, arguments);
    this.current_user = AppController.current_user();
    this.el = $("#template_signup_step2_pro_view-page").clone().removeClass("hidden").get(0);
    this.delegateEvents({
      "click #add-service": "add_service",
      "click #step1-menu": "step1",
      "click #step2-menu": "step2",
      "click #step3-menu": "step3",
      "click .forward": "step3",
      "click .back": "step1",
      "click .delete-account": "delete_account"
    });
    this.service_views = [];
    this.services = this.current_user.services();
    this.sports = new Sports();
    return this.sports.fetch({
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      },
      success: function() {
        return _this.services.fetch({
          success: function() {
            return _this.render();
          }
        });
      }
    });
  };

  SignupStep2ProView.prototype.slug = function() {
    return "registrazione-pro";
  };

  SignupStep2ProView.prototype.render = function() {
    var service;
    var _this = this;
    this.$('#step1-menu').css('opacity', '0.5');
    this.$('#step2-menu').css('opacity', '1');
    this.$('#step3-menu').css('opacity', '0.5');
    if (!this.current_user.get("registration_complete")) {
      this.$('#step3-menu a').hide();
    }
    this.$("#description").val(this.current_user.get("description"));
    if (this.services.length === 0) {
      $("#main-service").empty();
      service = new SignupStep2ProServiceView({
        master: this,
        undestroyable: true
      });
      this.service_views.push(service);
      $("#main-service").append(service.render().el);
      return service.show();
    } else {
      $("#main-service, #other-services").empty();
      return this.services.each(function(service) {
        if (service.get('principal')) {
          service = new SignupStep2ProServiceView({
            master: _this,
            service: service,
            undestroyable: true
          });
          _this.service_views.push(service);
          return $("#main-service").append(service.render().el);
        } else {
          service = new SignupStep2ProServiceView({
            master: _this,
            service: service
          });
          _this.service_views.push(service);
          return $("#other-services").append(service.render().el);
        }
      });
    }
  };

  SignupStep2ProView.prototype.add_service = function() {
    var service;
    service = new SignupStep2ProServiceView({
      master: this
    });
    this.service_views.push(service);
    $("#other-services").append(service.render().el);
    return service.show();
  };

  SignupStep2ProView.prototype.remove_service = function(service) {
    return this.service_views = _.reject(this.service_views, function(el) {
      return el === service;
    });
  };

  SignupStep2ProView.prototype.save = function(success) {
    var _this = this;
    return $.ajax({
      url: "/api/private/pro_description",
      type: "POST",
      data: {
        description: this.$("#description").val()
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      },
      success: function(data) {
        AppController.current_user().set({
          description: _this.$("#description").val()
        });
        return _this.services.fetch({
          success: function() {
            if (_this.services.length > 0) {
              return success();
            } else {
              return $.jGrowl(I18n.t("global.signup.messages.min_one_service"));
            }
          }
        });
      }
    });
  };

  SignupStep2ProView.prototype.delete_account = function() {
    AppController.current_user().delete_account();
    return false;
  };

  SignupStep2ProView.prototype.step3 = function() {
    this.save(function() {
      return document.location = "#/settings/3";
    });
    return false;
  };

  SignupStep2ProView.prototype.step2 = function() {
    return false;
  };

  SignupStep2ProView.prototype.step1 = function() {
    this.save(function() {
      return document.location = "#/settings/1";
    });
    return false;
  };

  return SignupStep2ProView;

})();

var SignupPlaceView, SignupStep3View;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SignupPlaceView = (function() {

  __extends(SignupPlaceView, Backbone.View);

  function SignupPlaceView() {
    SignupPlaceView.__super__.constructor.apply(this, arguments);
  }

  SignupPlaceView.prototype.initialize = function(options) {
    var sportId, _i, _len, _ref;
    var _this = this;
    this.location = options.location;
    this.undestroyable = options.undestroyable;
    this.el = $("#template_signup-place-view").clone().removeAttr('id').autoRender(this.location.get("location")).removeClass("hidden").get(0);
    this.user_sports = options.user_sports;
    if (this.undestroyable) this.$(".delete-location").remove();
    this.delegateEvents({
      "click .salva": "save",
      "click .profilo-sport .ps-open": "toggle_visibility",
      "click .delete-location": "delete",
      "click .sport-praticati .ps-closed": "add_sport",
      "click .sport-associati .ps-closed": "remove_sport",
      "click .check": "select_all_sports"
    });
    Utils.log(this.location);
    this.$(".livello span").attr("class", "icona-luogo-d");
    this.user_sports.each(function(sport) {
      var $sport_el;
      $sport_el = $("#template_signup-place-sport-view").clone().removeAttr('id').removeClass("hidden").autoRender(sport.attributes);
      _this.$("#sport-list").append($sport_el);
      Utils.log("lista sport location", _this.location.sport_ids());
      Utils.log("sport id", sport.get("sportId"));
      if ((_this.location.sport_ids()).indexOf(sport.get("sportId")) >= 0) {
        return $sport_el.find(".ps-closed").click();
      }
    });
    if (this.location.get("sportIdsList") && this.location.get("sportIdsList").length > 0) {
      _ref = this.location.get("sportIdsList");
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        sportId = _ref[_i];
        this.$("#sport-list").children().each(function() {
          if (parseInt($('.sportId', this).attr('sportid')) === parseInt(sportId)) {
            return $(this).click();
          }
        });
      }
    }
    return this.toggle_visibility();
  };

  SignupPlaceView.prototype["delete"] = function() {
    if (!(this.location.isNew() || (this.location.get("geoHash") === AppController.current_user().get("geo_hash")))) {
      this.location.destroy(this.location.get("id"));
      $(this.el).remove();
    }
    if (this.location.isNew() && !((this.location.get("location").geoHash || this.location.get("geoHash")) === AppController.current_user().get("geo_hash"))) {
      return $(this.el).remove();
    }
  };

  SignupPlaceView.prototype.save = function() {
    this.location.set({
      sportIdsList: this.location.sport_ids()
    });
    this.location.set({
      sportIds: []
    });
    this.location.save();
    this.toggle_visibility();
    return false;
  };

  SignupPlaceView.prototype.toggle_visibility = function() {
    return this.$('.expand').toggleClass('hidden');
  };

  SignupPlaceView.prototype.select_all_sports = function(event) {
    var _this = this;
    return this.$("#sport-list").children().each(function() {
      return _this.$('#sport-list .ps-closed').click();
    });
  };

  SignupPlaceView.prototype.add_sport = function(event) {
    var $el;
    $el = $(event.currentTarget);
    this.$("#selected-sport-list").append($el);
    this.location.add_sport_id($el.attr('sportId'));
    return this.$(".livello span").attr("class", "icona-luogo");
  };

  SignupPlaceView.prototype.remove_sport = function(event) {
    var $el;
    $el = $(event.currentTarget);
    this.$("#sport-list").append($el);
    this.location.remove_sport_id(parseInt($el.attr("sportId")));
    if (this.location.sport_ids().length === 0) {
      return this.$(".livello span").attr("class", "icona-luogo-d");
    }
  };

  SignupPlaceView.prototype.render = function() {
    return this;
  };

  return SignupPlaceView;

})();

SignupStep3View = (function() {

  __extends(SignupStep3View, PageView);

  function SignupStep3View() {
    SignupStep3View.__super__.constructor.apply(this, arguments);
  }

  SignupStep3View.prototype.initialize = function() {
    var _this = this;
    SignupStep3View.__super__.initialize.apply(this, arguments);
    this.current_user = AppController.current_user();
    this.locations = new Locations();
    this.locations.fetch({
      success: function() {
        _this.user_sports = new Schedules();
        return _this.user_sports.fetch({
          success: function() {
            return _this.add_places();
          },
          error: function() {
            return $.jGrowl(I18n.t("global.connection_error"));
          }
        });
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    this.el = $("#template_signup_step3_view-page").clone().removeClass("hidden").get(0);
    return this.delegateEvents({
      "click #add-place": "add_place",
      "click .cerca": "search_place",
      "click #step1-menu": "step1",
      "click #step2-menu": "step2",
      "click #step3-menu": "step3",
      "click #save-step3": "finish_wizard",
      "click .back": "step2",
      "keyup #place-address": "add_place_key",
      "click #geolocalizzami": "geolocate_html5",
      "click .delete-account": "delete_account"
    });
  };

  SignupStep3View.prototype.slug = function() {
    return "signup";
  };

  SignupStep3View.prototype.geolocate_html5 = function() {
    var _this = this;
    if (navigator.geolocation == null) return;
    return navigator.geolocation.getCurrentPosition(function(position) {
      var location;
      location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      _this.map.setCenter(location);
      _this.marker.setPosition(location);
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return this.$("#place-address").val(results[0].formatted_address);
        }
      });
    }, function(error) {
      return $.jGrowl(error);
    });
  };

  SignupStep3View.prototype.add_place_key = function(e) {
    if (e.keyCode === 13) return this.search_place();
  };

  SignupStep3View.prototype.add_places = function() {
    var main_location_found, myLocation, userLocation;
    var _this = this;
    Utils.log(this.locations);
    main_location_found = false;
    this.locations.each(function(location) {
      var userLocation;
      Utils.log(location.get("geoHash"), " --> ", AppController.current_user().get("geo_hash"));
      if (location.get("geoHash") === AppController.current_user().get("geo_hash")) {
        userLocation = new SignupPlaceView({
          location: location,
          user_sports: _this.user_sports,
          undestroyable: true
        });
        main_location_found = true;
        _this.main_location = location.get("location");
        return _this.$("#luogo-principale").append(userLocation.render().el);
      } else {
        userLocation = new SignupPlaceView({
          location: location,
          user_sports: _this.user_sports
        });
        _this.$('.altri-luoghi').show();
        return _this.$("#lista-luoghi").append(userLocation.render().el);
      }
    });
    if (!main_location_found) {
      myLocation = new Location({
        location: {
          address: this.current_user.get("address"),
          longitude: this.current_user.get("longitude"),
          latitude: this.current_user.get("latitude"),
          geoHash: this.current_user.get("geo_hash")
        }
      });
      userLocation = new SignupPlaceView({
        location: myLocation,
        user_sports: this.user_sports,
        undestroyable: true
      });
      userLocation.select_all_sports();
      userLocation.toggle_visibility();
      return this.$("#luogo-principale").append(userLocation.render().el);
    }
  };

  SignupStep3View.prototype.search_place = function() {
    var _this = this;
    return Utils.geocode(this.$("#place-address").val(), function(geoResult) {
      if (geoResult) {
        _this.map.setCenter(geoResult.latlng);
        return _this.marker.setPosition(geoResult.latlng);
      } else {
        return $.jGrowl(I18n.t("global.geocode_fail"));
      }
    });
  };

  SignupStep3View.prototype.add_place = function() {
    var location, userLocation;
    if (!(Math.round(this.marker.position.lat() * 10000) === Math.round(this.main_location.latitude * 10000) && Math.round(this.marker.position.lng() * 10000) === Math.round(this.main_location.longitude * 10000))) {
      location = new Location({
        "location": {
          address: this.$("#place-address").val(),
          latitude: this.marker.position.lat(),
          longitude: this.marker.position.lng()
        }
      });
      userLocation = new SignupPlaceView({
        "location": location,
        user_sports: this.user_sports
      });
      userLocation.toggle_visibility();
      this.$('.altri-luoghi').show();
      this.$("#lista-luoghi").prepend(userLocation.render().el);
    }
    return end;
  };

  SignupStep3View.prototype.save_step = function(success) {
    var _this = this;
    this.locations.fetch({
      success: function() {
        if (_this.locations.length > 0) {
          return success();
        } else {
          return $.jGrowl("Prima di proseguire è necessario specificare almeno un luogo nel quale pratichi sport!");
        }
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  SignupStep3View.prototype.delete_account = function() {
    AppController.current_user().delete_account();
    return false;
  };

  SignupStep3View.prototype.step1 = function() {
    this.save_step(function() {
      return document.location = "#/settings/1";
    });
    return false;
  };

  SignupStep3View.prototype.step2 = function() {
    this.save_step(function() {
      return document.location = "#/settings/2";
    });
    return false;
  };

  SignupStep3View.prototype.step3 = function() {
    return false;
  };

  SignupStep3View.prototype.finish_wizard = function() {
    var _this = this;
    return this.save_step(function() {
      if (_this.current_user.get("registration_complete")) {
        return document.location = "#/my_home/users";
      } else {
        return $.get('/api/private/user_registration_complete', function(data) {
          _this.current_user.set({
            registration_complete: true
          });
          return document.location = "#/my_home/users";
        });
      }
    });
  };

  SignupStep3View.prototype.render = function() {
    this.$('#step1-menu').css('opacity', '0.5');
    this.$('#step2-menu').css('opacity', '0.5');
    this.$('#step3-menu').css('opacity', '1');
    this.$('.altri-luoghi').hide();
    this.map = new google.maps.Map(this.$("#map-step3").get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    this.marker = new google.maps.Marker({
      map: this.map,
      title: 'Mia posizione',
      position: this.current_user.latlng()
    });
    this.marker.setDraggable(true);
    return google.maps.event.addListener(this.marker, 'dragend', function() {
      var location;
      location = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return this.$("#place-address").val(results[0].formatted_address);
        }
      });
    });
  };

  return SignupStep3View;

})();

var SignupPlaceProView, SignupStep3ProView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SignupPlaceProView = (function() {

  __extends(SignupPlaceProView, Backbone.View);

  function SignupPlaceProView() {
    SignupPlaceProView.__super__.constructor.apply(this, arguments);
  }

  SignupPlaceProView.prototype.initialize = function(options) {
    var _this = this;
    this.location = options.location;
    this.undestroyable = options.undestroyable;
    this.el = $("#template_signup-place-pro-view").clone().removeAttr('id').autoRender(this.location.get("location")).removeClass("hidden").get(0);
    this.pro_services = options.pro_services;
    if (this.undestroyable) this.$(".delete-location").remove();
    this.delegateEvents({
      "click .salva": "save",
      "click .profilo-service .address": "toggle_visibility",
      "click .profilo-service .icona-luogopro": "toggle_visibility",
      "click .profilo-service .modifica": "toggle_visibility",
      "click .delete-location": "delete",
      "click .service-praticati .serviceName": "add_service",
      "click .service-associati .serviceName": "remove_service",
      "click #allServices": "select_all_services"
    });
    Utils.log(this.location);
    this.pro_services.each(function(service) {
      var $service_el;
      $service_el = $("#template_signup-place-service-view").clone().removeAttr('id').removeClass("hidden").autoRender(service.attributes);
      _this.$("#service-list").append($service_el);
      Utils.log("lista service location", _this.location.service_ids());
      Utils.log("service id", service.get("serviceId"));
      if ((_this.location.service_ids()).indexOf(service.get("serviceId")) >= 0) {
        return $service_el.find(".ps-closed.serviceName").click();
      }
    });
    this.$(".livello span").attr("class", this.location.service_ids().length > 0 ? "icona-luogopro" : "icona-luogopro-d");
    return this.toggle_visibility();
  };

  SignupPlaceProView.prototype["delete"] = function() {
    if (!this.location.isNew()) this.location.destroy(this.location.get("id"));
    return $(this.el).remove();
  };

  SignupPlaceProView.prototype.save = function() {
    this.location.set({
      serviceIdsList: this.location.service_ids()
    });
    this.location.save({
      error: function(model, response) {
        return $.jGrowl(response);
      }
    });
    this.toggle_visibility();
    return false;
  };

  SignupPlaceProView.prototype.toggle_visibility = function() {
    return this.$('.expand').toggleClass('hidden');
  };

  SignupPlaceProView.prototype.select_all_services = function(event) {
    var _this = this;
    return this.$("#service-list").children().each(function() {
      return _this.$('.service-praticati .serviceName').click();
    });
  };

  SignupPlaceProView.prototype.add_service = function(event) {
    var $el;
    $el = $(event.currentTarget);
    this.$("#selected-service-list").append($el);
    this.location.add_service_id($el.attr('serviceid'));
    return this.$(".livello span").attr("class", "icona-luogopro");
  };

  SignupPlaceProView.prototype.remove_service = function(event) {
    var $el;
    $el = $(event.currentTarget);
    this.$("#service-list").append($el);
    this.location.remove_service_id(parseInt($el.attr("serviceid")));
    if (this.location.service_ids().length === 0) {
      return this.$(".livello span").attr("class", "icona-luogopro-d");
    }
  };

  SignupPlaceProView.prototype.render = function() {
    return this;
  };

  return SignupPlaceProView;

})();

SignupStep3ProView = (function() {

  __extends(SignupStep3ProView, PageView);

  function SignupStep3ProView() {
    SignupStep3ProView.__super__.constructor.apply(this, arguments);
  }

  SignupStep3ProView.prototype.initialize = function() {
    var _this = this;
    SignupStep3ProView.__super__.initialize.apply(this, arguments);
    this.current_user = AppController.current_user();
    this.locations = new MyProLocations();
    this.pro_services = new MyProServices();
    this.locations.fetch({
      success: function() {
        return _this.pro_services.fetch({
          success: function() {
            return _this.add_places();
          },
          error: function() {
            return $.jGrowl(I18n.t("global.connection_error"));
          }
        });
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    this.el = $("#template_signup_step3_pro_view-page").clone().removeClass("hidden").get(0);
    return this.delegateEvents({
      "click #add-location-pro": "add_place",
      "click .cerca": "search_place",
      "click #step1-menu": "step1",
      "click #step2-menu": "step2",
      "click .back": "step2",
      "click #step3-menu": "step3",
      "click #save-step3": "finish_wizard",
      "keyup #service-address": "add_place_key",
      "click #geolocalizzami": "geolocate_html5",
      "click .delete-account": "delete_account"
    });
  };

  SignupStep3ProView.prototype.slug = function() {
    return "signup";
  };

  SignupStep3ProView.prototype.geolocate_html5 = function() {
    var _this = this;
    if (navigator.geolocation == null) return;
    return navigator.geolocation.getCurrentPosition(function(position) {
      var location;
      location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      _this.map.setCenter(location);
      _this.marker.setPosition(location);
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return this.$("#service-address").val(results[0].formatted_address);
        }
      });
    }, function(error) {
      return $.jGrowl(error);
    });
  };

  SignupStep3ProView.prototype.search_place = function() {
    var _this = this;
    return Utils.geocode(this.$("#service-address").val(), function(geoResult) {
      if (geoResult) {
        _this.map.setCenter(geoResult.latlng);
        return _this.marker.setPosition(geoResult.latlng);
      } else {
        return $.jGrowl(I18n.t("global.geocode_fail"));
      }
    });
  };

  SignupStep3ProView.prototype.add_place_key = function(e) {
    if (e.keyCode === 13) return this.search_place();
  };

  SignupStep3ProView.prototype.add_places = function() {
    var main_location_found, myLocation, userLocation;
    var _this = this;
    Utils.log(this.locations);
    main_location_found = false;
    this.locations.each(function(location) {
      var userLocation;
      if (location.get("geoHash") === AppController.current_user().get("geo_hash")) {
        main_location_found = true;
        userLocation = new SignupPlaceProView({
          location: location,
          pro_services: _this.pro_services,
          undestroyable: true
        });
        return _this.$("#luogo-principale").append(userLocation.render().el);
      } else {
        userLocation = new SignupPlaceProView({
          location: location,
          pro_services: _this.pro_services
        });
        _this.$('.altri-luoghi').show();
        return _this.$("#lista-luoghi").append(userLocation.render().el);
      }
    });
    if (!main_location_found) {
      myLocation = new LocationPro({
        location: {
          address: this.current_user.get("address"),
          longitude: this.current_user.get("longitude"),
          latitude: this.current_user.get("latitude")
        }
      });
      userLocation = new SignupPlaceProView({
        location: myLocation,
        pro_services: this.pro_services,
        undestroyable: true
      });
      userLocation.select_all_services();
      userLocation.toggle_visibility();
      return this.$("#luogo-principale").append(userLocation.render().el);
    }
  };

  SignupStep3ProView.prototype.search_place = function() {
    var _this = this;
    return Utils.geocode(this.$("#service-address").val(), function(geoResult) {
      if (geoResult) {
        _this.map.setCenter(geoResult.latlng);
        return _this.marker.setPosition(geoResult.latlng);
      } else {
        return $.jGrowl(I18n.t("global.geocode_fail"));
      }
    });
  };

  SignupStep3ProView.prototype.add_place = function() {
    var location, userLocation;
    location = new LocationPro({
      location: {
        address: this.$("#service-address").val(),
        longitude: this.marker.position.lng(),
        latitude: this.marker.position.lat()
      }
    });
    userLocation = new SignupPlaceProView({
      "location": location,
      user_sports: this.user_sports,
      pro_services: this.pro_services
    });
    userLocation.toggle_visibility();
    this.$('.altri-luoghi').show();
    return this.$("#lista-luoghi").prepend(userLocation.render().el);
  };

  SignupStep3ProView.prototype.save = function(success) {
    var _this = this;
    this.locations.fetch({
      success: function() {
        if (_this.locations.length > 0) {
          return success();
        } else {
          return $.jGrowl(I18n.t("global.signup.messages.min_one_association_between_places_and_services"));
        }
      }
    });
    return false;
  };

  SignupStep3ProView.prototype.finish_wizard = function() {
    var _this = this;
    return this.save(function() {
      if (_this.current_user.get("registration_complete")) {
        return document.location = "#/my_home/users";
      } else {
        return $.get('/api/private/user_registration_complete', function(data) {
          _this.current_user.set({
            registration_complete: true
          });
          return document.location = "#/my_home/users";
        });
      }
    });
  };

  SignupStep3ProView.prototype.delete_account = function() {
    AppController.current_user().delete_account();
    return false;
  };

  SignupStep3ProView.prototype.step3 = function() {
    return false;
  };

  SignupStep3ProView.prototype.step2 = function() {
    this.save(function() {
      return document.location = "#/settings/2";
    });
    return false;
  };

  SignupStep3ProView.prototype.step1 = function() {
    this.save(function() {
      return document.location = "#/settings/1";
    });
    return false;
  };

  SignupStep3ProView.prototype.render = function() {
    this.$('#step1-menu').css('opacity', '0.5');
    this.$('#step2-menu').css('opacity', '0.5');
    this.$('#step3-menu').css('opacity', '1');
    this.$('.altri-luoghi').hide();
    this.map = new google.maps.Map(this.$("#map-step3").get(0), {
      zoom: 14,
      center: this.current_user.latlng(),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    this.marker = new google.maps.Marker({
      map: this.map,
      title: 'Mia posizione',
      position: this.current_user.latlng()
    });
    this.marker.setDraggable(true);
    return google.maps.event.addListener(this.marker, 'dragend', function() {
      var location;
      location = new google.maps.LatLng(this.getPosition().lat(), this.getPosition().lng());
      return new google.maps.Geocoder().geocode({
        'latLng': location
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK && (results[0] != null)) {
          return this.$("#service-address").val(results[0].formatted_address);
        }
      });
    });
  };

  return SignupStep3ProView;

})();

var ChangePassView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

ChangePassView = (function() {

  __extends(ChangePassView, PageView);

  function ChangePassView() {
    ChangePassView.__super__.constructor.apply(this, arguments);
  }

  ChangePassView.prototype.initialize = function() {
    ChangePassView.__super__.initialize.apply(this, arguments);
    this.current_user = AppController.current_user();
    this.el = $("#template_change_pass_view-page").clone().removeClass("hidden").get(0);
    $(this.el).find("#tab a.step1-back").removeClass("hidden");
    this.events = {
      "click .submit_change": "submit_change",
      "click #step1-menu": "step1"
    };
    return this.delegateEvents();
  };

  ChangePassView.prototype.slug = function() {
    return "signup";
  };

  ChangePassView.prototype.submit_change = function() {
    if ((this.$("input[name=new-password]").val().length > 0) && (this.$("input[name=new-password]").val() === this.$("input[name=repeat-password]").val())) {
      return $.ajax({
        url: ApplicationScript.RestUrl("user.change.password", AppController.current_user().get('token')),
        type: "get",
        dataType: "jsonp",
        data: {
          OldPassword: this.$("input[name=old-password]").val(),
          NewPassword: this.$("input[name=new-password]").val()
        },
        success: function(data) {
          Utils.log(data);
          if (data._responseStatus === "") {
            $.jGrowl(I18n.t("global.signup.messages.changed_password"));
            $("input[name=email]").val("");
          } else {
            $.jGrowl("fail");
          }
          $("input[name=old-password]").val("");
          $("input[name=new-password]").val("");
          return $("input[name=repeat-password]").val("");
        },
        error: function() {
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    } else {
      $.jGrowl("Inserire correttamente la nuova password");
      $("input[name=new-password]").val("");
      return $("input[name=repeat-password]").val("");
    }
  };

  ChangePassView.prototype.step1 = function() {
    return document.location = "#/settings/1";
  };

  ChangePassView.prototype.render = function() {
    this.$('#step1-menu').css('opacity', '0.5');
    this.$('#step2-menu').css('opacity', '0');
    return this.$('#step3-menu').css('opacity', '0');
  };

  return ChangePassView;

})();

var NotificationsView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

NotificationsView = (function() {

  __extends(NotificationsView, PageView);

  function NotificationsView() {
    NotificationsView.__super__.constructor.apply(this, arguments);
  }

  NotificationsView.prototype.initialize = function() {
    var attr, html, val, _i, _len, _ref;
    NotificationsView.__super__.initialize.apply(this, arguments);
    this.current_user = AppController.current_user();
    this.el = $("#template_notifications_view-page").clone().removeClass("hidden").autoRender({
      'mail-address': " " + (this.current_user.get('email'))
    }).get(0);
    $(this.el).find("#tab a.step1-back").removeClass("hidden");
    _ref = ["flag_email_confirm_friendship_request", "flag_email_friendship_request", "flag_email_event", "flag_email_message_event", "flag_email_message_profile", "flag_email_newsletter"];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      attr = _ref[_i];
      html = $(this.el).find("#" + attr);
      val = this.current_user.get("" + attr);
      $(this.el).find("#" + attr).prop('checked', this.current_user.get("" + attr));
    }
    this.events = {
      "click .submit_change": "submit_change",
      "click #step1-menu": "step1"
    };
    return this.delegateEvents();
  };

  NotificationsView.prototype.slug = function() {
    return "signup";
  };

  NotificationsView.prototype.submit_change = function() {
    var attr, attrs, _i, _len, _ref;
    var _this = this;
    attrs = {};
    _ref = ["flag_email_confirm_friendship_request", "flag_email_friendship_request", "flag_email_event", "flag_email_message_event", "flag_email_message_profile", "flag_email_newsletter"];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      attr = _ref[_i];
      attrs[attr] = $(this.el).find("#" + attr).prop('checked');
    }
    Utils.log("Invio (NON E' VERO, SET, INVIO di toJSON) dei seguenti parametri:", attrs);
    return this.current_user.save(attrs, {
      success: function(model, response) {
        Utils.log("Inviato con successo!");
        return $.jGrowl(I18n.t("global.signup.messages.changed_notifications"));
      },
      error: function() {
        $.jGrowl(I18n.t("global.connection_error"));
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
  };

  NotificationsView.prototype.step1 = function() {
    return document.location = "#/settings/1";
  };

  NotificationsView.prototype.render = function() {
    this.$('#step1-menu').css('opacity', '0.5');
    this.$('#step2-menu').css('opacity', '0');
    return this.$('#step3-menu').css('opacity', '0');
  };

  return NotificationsView;

})();

var AboutView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

AboutView = (function() {

  __extends(AboutView, PageView);

  function AboutView() {
    AboutView.__super__.constructor.apply(this, arguments);
  }

  AboutView.prototype.initialize = function() {
    this.el = $("#template_static_pages-about-us").clone().removeClass("hidden");
    return this.$("#about_" + I18n.currentLocale()).removeClass("hidden");
  };

  AboutView.prototype.slug = function() {
    return "static-page";
  };

  return AboutView;

})();

var TosView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

TosView = (function() {

  __extends(TosView, PageView);

  function TosView() {
    TosView.__super__.constructor.apply(this, arguments);
  }

  TosView.prototype.initialize = function(lang) {
    this.el = $("#template_static_pages-tos").clone().removeClass("hidden");
    if (lang === "it") {
      return this.$(".it").removeClass("hidden");
    } else {
      return this.$("." + I18n.currentLocale()).removeClass("hidden");
    }
  };

  TosView.prototype.slug = function() {
    return "static-page";
  };

  return TosView;

})();

var PrivacyView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

PrivacyView = (function() {

  __extends(PrivacyView, PageView);

  function PrivacyView() {
    PrivacyView.__super__.constructor.apply(this, arguments);
  }

  PrivacyView.prototype.initialize = function() {
    this.el = $("#template_static_pages-privacy").clone().removeClass("hidden");
    return this.$("." + I18n.currentLocale()).removeClass("hidden");
  };

  PrivacyView.prototype.slug = function() {
    return "static-page";
  };

  return PrivacyView;

})();

var SponsorsView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

SponsorsView = (function() {

  __extends(SponsorsView, PageView);

  function SponsorsView() {
    SponsorsView.__super__.constructor.apply(this, arguments);
  }

  SponsorsView.prototype.initialize = function(opts) {
    this.page = opts.page;
    this.id = opts.news_id;
    this.el = $('#template_static_pages-sponsors').clone().removeClass('hidden');
    this.events = {
      "click .button.news": "to_news",
      "click .button.project": "to_project",
      "click .button.press-room": "to_press",
      "click .sidebar li": "change_news",
      "click .press-room-content h2": "change_comunicato"
    };
    return this.delegateEvents();
  };

  SponsorsView.prototype.slug = function() {
    return "static-page";
  };

  SponsorsView.prototype.change_news = function(e) {
    var $el;
    $el = $(e.currentTarget);
    return document.location = "#/sponsor/news/" + $el.attr('news');
  };

  SponsorsView.prototype.to_news = function() {
    return document.location = "#/sponsor/news";
  };

  SponsorsView.prototype.to_project = function() {
    return document.location = "#/sponsor/project";
  };

  SponsorsView.prototype.to_press = function() {
    return document.location = "#/sponsor/press";
  };

  SponsorsView.prototype.render = function() {
    if (this.page === "news") {
      return this.show_news(this.id);
    } else if (this.page === "press") {
      return this.show_press();
    } else {
      return this.show_project();
    }
  };

  SponsorsView.prototype.show_news = function(id) {
    var news_id;
    this.$('.contenuto .news').removeClass("hidden");
    this.$('.contenuto .progetto').addClass('hidden');
    this.$('.contenuto .press-room-content').addClass('hidden');
    this.$('.button.news').addClass('selected');
    this.$('.button.project').removeClass('selected');
    this.$('.button.press-room').removeClass('selected');
    news_id = id;
    if (!news_id) news_id = "1";
    this.$('.sidebar li').each(function() {
      if ($(this).attr('news') === news_id) {
        return $(this).addClass('selected');
      } else {
        return $(this).removeClass('selected');
      }
    });
    this.$('.news-container').empty();
    return this.$('.news-store .news' + news_id).clone().appendTo('.news-container');
  };

  SponsorsView.prototype.show_project = function() {
    this.$('.contenuto .news').addClass("hidden");
    this.$('.contenuto .press-room-content').addClass("hidden");
    this.$('.contenuto .progetto').removeClass('hidden');
    this.$('.button.news').removeClass('selected');
    this.$('.button.project').addClass('selected');
    return this.$('.button.press-room').removeClass('selected');
  };

  SponsorsView.prototype.show_press = function() {
    this.$('.contenuto .news').addClass("hidden");
    this.$('.contenuto .progetto').addClass('hidden');
    this.$('.contenuto .press-room-content').removeClass("hidden");
    this.$('.button.news').removeClass('selected');
    this.$('.button.project').removeClass('selected');
    return this.$('.button.press-room').addClass('selected');
  };

  SponsorsView.prototype.change_comunicato = function(e) {
    var $next;
    $next = $(e.currentTarget).next();
    if ($next.hasClass('hidden')) {
      $('.press-room-content .comunicato').addClass('hidden');
      return $next.removeClass('hidden');
    } else {
      return $next.addClass('hidden');
    }
  };

  return SponsorsView;

})();

var PartnerView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

PartnerView = (function() {

  __extends(PartnerView, PageView);

  function PartnerView() {
    PartnerView.__super__.constructor.apply(this, arguments);
  }

  PartnerView.prototype.initialize = function() {
    return this.el = $("#template_static_pages-partners").clone().removeClass("hidden");
  };

  PartnerView.prototype.slug = function() {
    return "static-page";
  };

  return PartnerView;

})();

var NewsView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

NewsView = (function() {

  __extends(NewsView, PageView);

  function NewsView() {
    NewsView.__super__.constructor.apply(this, arguments);
  }

  NewsView.prototype.initialize = function() {
    return this.el = $("#template_static_pages-news").clone().removeClass("hidden");
  };

  NewsView.prototype.slug = function() {
    return "static-page";
  };

  return NewsView;

})();

var PressView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

PressView = (function() {

  __extends(PressView, PageView);

  function PressView() {
    PressView.__super__.constructor.apply(this, arguments);
  }

  PressView.prototype.initialize = function() {
    return this.el = $("#template_static_pages-press").clone().removeClass("hidden");
  };

  PressView.prototype.slug = function() {
    return "static-page";
  };

  return PressView;

})();

var Contact_UsView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Contact_UsView = (function() {

  __extends(Contact_UsView, PageView);

  function Contact_UsView() {
    Contact_UsView.__super__.constructor.apply(this, arguments);
  }

  Contact_UsView.prototype.initialize = function() {
    this.el = $("#template_static_pages-contact-us").clone().removeClass("hidden");
    return this.$("." + I18n.currentLocale()).removeClass("hidden");
  };

  Contact_UsView.prototype.slug = function() {
    return "static-page";
  };

  return Contact_UsView;

})();

var HomepageView;
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

HomepageView = (function() {

  __extends(HomepageView, PageView);

  function HomepageView() {
    HomepageView.__super__.constructor.apply(this, arguments);
  }

  HomepageView.prototype.initialize = function() {
    document.title = "We-Sport.com";
    this.el = $("#template_home_view-page").clone().removeClass("hidden");
    this.events = {
      "click #login_form .go": "signup",
      "click .change-pass-box .button": "change_password"
    };
    return this.delegateEvents();
  };

  HomepageView.prototype.slug = function() {
    return "homepage";
  };

  HomepageView.prototype.render = function() {
    HomepageView.__super__.render.apply(this, arguments);
    this.$('.area-person').tipsy({
      gravity: 's',
      title: 'tooltip'
    });
    this.$('#sponsorVideo, #sponsorVideo2').css('visibility', 'visible');
    if (!$.cookie("lang")) $.cookie("lang", "it");
    this.$('#banner').css('background', 'url(../../img/istituzionali/hp_' + $.cookie("lang") + '.jpg) no-repeat');
    if ($.cookie("lang") === "it") {
      $('#player').attr('href', 'http://flashondemand.top-ix.org/we-sport/we-sport_it.flv');
    } else {
      $('#player').attr('href', 'http://flashondemand.top-ix.org/we-sport/we-sport_en.flv');
    }
    return flowplayer("player", "./flowplayer-3.2.7.swf");
  };

  HomepageView.prototype.signup = function() {
    if (!Utils.is_email($("input[name=email]").val())) {
      $.jGrowl(I18n.t("homepage.signup.valid_email"));
    } else if (!$(".check input[type='checkbox']").is(":checked")) {
      $.jGrowl(I18n.t("homepage.signup.accept_tos_error"));
    } else if ($("input[name=password]").val().length === 0) {
      $.jGrowl(I18n.t("homepage.signup.insert_password"));
    } else if ($("input[name=password]").val() !== $("input[name=password1]").val()) {
      $.jGrowl(I18n.t("homepage.signup.equal_passwords"));
      $("input[name=password]").val("");
      $("input[name=password1]").val("");
    } else {
      window.show_loading();
      $.ajax({
        url: ApplicationScript.RestUrl("user.add.mini", ""),
        type: "get",
        dataType: "jsonp",
        data: {
          OptIn: true,
          Email: $("input[name=email]").val(),
          Password: $("input[name=password]").val()
        },
        success: function(data) {
          window.hide_loading();
          Utils.log(data);
          if (data._responseStatus === "") {
            $.jGrowl(I18n.t("global.signup.messages.success"));
            $("input[name=email]").val("");
          } else {
            if ((data._responseStatus.match(/CurrentUser\.Email\.Exist/)) || (data._responseStatus.match(/User\.Email\.Exist/))) {
              $.jGrowl(I18n.t("homepage.signup.existing_email"));
            } else if (data._responseStatus.match(/CurrentUser\.Bad\.Email/)) {
              $.jGrowl(I18n.t("homepage.signup.invalid_email"));
            } else if ((data._responseStatus.match(/CurrentUser\.Bad\.Password/)) || (data._responseStatus.match(/User\.Bad\.Password/))) {
              $.jGrowl(I18n.t("homepage.signup.bad_password"));
            } else {
              $.jGrowl(I18n.t("homepage.signup.general_error", {
                status_detail: data._responseStatus
              }));
            }
          }
          $("input[name=password]").val("");
          return $("input[name=password1]").val("");
        },
        error: function() {
          window.hide_loading();
          return $.jGrowl(I18n.t("global.connection_error"));
        }
      });
    }
    return false;
  };

  HomepageView.prototype.change_password = function() {
    $.ajax({
      url: ApplicationScript.RestUrl("user.change.password", this.current_user.get('token')),
      type: "get",
      dataType: "jsonp",
      data: {
        OldPassword: $("input[name=password]").val(),
        NewPassword: $("input[name=password]").val()
      },
      success: function(data) {
        Utils.log(data);
        if (data._responseStatus === "") {
          $.jGrowl(I18n.t("homepage.signup.change_password"));
        }
        $("input[name=password]").val("");
        return $("input[name=password1]").val("");
      },
      error: function() {
        return $.jGrowl(I18n.t("global.connection_error"));
      }
    });
    return false;
  };

  return HomepageView;

})();

