/* encoding: UTF-8

Dirty Hack for dvdrtree.com modified Redsilver3 Theme
Modding by Gerry - http://www.gerry.it/serve/mail/
*/

// funzioni di appoggio
// controlla se una stringa ha un certo prefisso 
String.prototype.dt_startsWith = function(s) { 
	return (this.indexOf(s)==0); 
};
// controlla se una stringa ha un certo prefisso (case insensitive)
String.prototype.dt_startsWithI = function(s) { 
	return (this.toLowerCase().indexOf(s.toLowerCase())==0); 
};

// controlla se un url fa parte dei domini esclusi
String.prototype.dt_chkExcluded = function() {
	// ciclo l'array
	var i = 0;
	for (i = 0; i < dthacks.url.excludedUrls.length; i++) {
		if( this.dt_startsWithI( dthacks.url.excludedUrls[i] ) )
			return(true);
	}
	
	// non inizia per un escluso
	return(false);
};


/* OGGETTO dthacks, contiene tutto il codice necessario alla gestione degli hacks */
var dthacks = {

	// costanti per le chiamate ajax
	ajax : {
		ajaxServiceDir : null
	},

	// funzione di inizializzazione
	init : function( templatePath ) {	
	
		// init delle variabili	
		dthacks.ajax.ajaxServiceDir = templatePath + '/hacks/ajax/';	
	
		// popolo gli url esclusi con dei dati di default
		if( document.location.hostname != '' ){
			// varianti dell'hostname
			dthacks.url.excludedUrls.push('http://' + document.location.hostname ); //http
			dthacks.url.excludedUrls.push('https://' + document.location.hostname ); //https
			if( ! document.location.hostname.dt_startsWithI('www') ){
				// versioni con www
				dthacks.url.excludedUrls.push('http://www.' + document.location.hostname ); //http
				dthacks.url.excludedUrls.push('https://www.' + document.location.hostname ); //https	
			}
		}
		
		
		// toggle custom searches
		$('#dt_customSearches_toggle').click(function(e){
			e.preventDefault();
			// nascondo il toggler
			$('#dt_customSearches_toggle').hide();
			// mostro glia ltri comendi
			$('#dt_customSearches').show();	
			}
		);

		// riscrive gli url
		dthacks.url.urlRewrite();

		// controllo se siamo in una pagina con l'editor
		if( dthacks.bbcode.customBBcode === true ){
			// gestione del bbcode custom
			dthacks.bbcode.handleCustomBBcode();
			
			// se ci sono i bbcode, ci sarà anche la textarea
			// installo l'auto -resizer		
			// settaggi
			$('textarea[name="message"]').supertextarea({
				// maximum height
				maxh : 500,
				tabr : {use: false},
				maxl : 0
			});
			
			
			// installo il quote²
			dthacks.bbcode.quoteCleaner.installCleaner();
			
			
			// definisco le mappature per le hotkeys
			// accesskey => hotkey corrispondente
			dthacks.bbcode.hotKeysMappings['b'] = 'ctrl+b';
			dthacks.bbcode.hotKeysMappings['i'] = 'ctrl+i';
			dthacks.bbcode.hotKeysMappings['u'] = 'ctrl+u';
			dthacks.bbcode.hotKeysMappings['q'] = 'ctrl+q';
			dthacks.bbcode.hotKeysMappings['l'] = 'ctrl+l';
			dthacks.bbcode.hotKeysMappings['t'] = 'ctrl+*';
			dthacks.bbcode.hotKeysMappings['p'] = 'ctrl+p';
			dthacks.bbcode.hotKeysMappings['2'] = 'ctrl+2';
			
			
			// installo i bind per le hotkeys bbcode			
			var buttons = $('INPUT[accesskey]').get();
			for( var i = 0; i < buttons.length; i++ ){
				// tengo solo i bottoni che hanno come classe btnbbcode 				
				if( ! $(buttons[i]).hasClass('btnbbcode') ){
					// skippo
					continue;
				}
				
				// accesskey la copio localmente
				var accessKey = $(buttons[i]).attr('accesskey');
				
				// controllo se esiste il mapping altrimenti salto 
				if( typeof(dthacks.bbcode.hotKeysMappings[accessKey]) != 'string' ){
					// non esiste, salto
					continue;
				}
				
				// recupero il bottone e faccio un bell'oggettino
				var hotKeyData = {
					"accessKey" : accessKey,
					"hotKey" : dthacks.bbcode.hotKeysMappings[accessKey],
					"button" : buttons[i]
				};
				
				// siccome non so usare bene le closures
				// metto un oggetto coi dettagli della chiamata nella textbox
				// in modo da poterlo recuperare al fire dell'evento
				$('textarea[name="message"]').data(hotKeyData.hotKey, hotKeyData);
				
				// bindo l'evento
				$('textarea[name="message"]').bind('keydown', hotKeyData.hotKey, function(e){ 
					// recupero l'oggetto con i dati dell'hotkey
					var hotKeyDataRetrieved = $('textarea[name="message"]').data( e.data );
					
					// se non esiste l'accesskey, ritorno
					if( typeof(hotKeyDataRetrieved) != 'object' ){
						return(true);
					}
					
					// fire dell'evento-bottone associato
					$(hotKeyDataRetrieved.button).click();
					
					// ritorno false per stoppare l'evento di default
					return (false);
				} );
				
				// workaround rozzo per evitare i default: bindo keyup e keypress ritornando false
				// così non scatena gli evento di default
				$('textarea[name="message"]').bind('keyup', hotKeyData.hotKey, function(e){ return(false); } );
				$('textarea[name="message"]').bind('keypress', hotKeyData.hotKey, function(e){ return(false); } );

			}			
			
		}
		
		// se voglio istallare l'hi-lighter
		if( dthacks.hilight.chkHilight ){
		
			var chkToHack = $('input[name="marked_msg_id[]"],input[name="topic_id_list[]"],input[name="post_id_list[]"]').get();
			
			// $(chkToHack).css('background-color','red');
			
			$(chkToHack).bind('click change dblclick', function(e){
				// seleziono il tr parent più vicino
				var nearestTr = $(this).closest('tr');
				
				if( nearestTr.length != 1 ){
					// qualcosa non torna, return
					return;
				}
				
				// cambio la classe della tr a seconda dello stato della 
				// chackbox
				if( this.checked ){
					$(nearestTr[0]).addClass('dt_rowHilight');
				}
				else{
					$(nearestTr[0]).removeClass('dt_rowHilight');
				}
				
			});
		
		}
		
		// smiles personalizzati
		dthacks.smiles.prev(-1);
	
		
	}, // fine init

	// parte url rewriting (video in generale)
	url : {
		// url esclusi dalla gestione
		excludedUrls : new Array(),
		
		// converte un anchor youtube
		youtubeConvert : function(anchor){
			// ottengo l'id del video
			var code = dthacks.url.youTube_extract_id( anchor.href );
			
			// se l'id è vuoto, ritorno false
			if( code == '' ) {
				return(false);
			}
			
			
			// creo il codice
			var newCode = 
				'<div class="msgBodyYoutubeAuto">' +
				'<span>Lo sai che puoi <a href="http://www.dvdrtree.com/board/viewtopic.php?p=226682&f=1#p226682" class="dvdt_youtube_bbcode" target="_blank">usare il tag YT</a>?</span><br/>' +
				'<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/' + code + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + code + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>' +
				'<br/><a href="http://www.youtube.com/watch/v=' + code + '" class="dvdt_youtube_bbcode" target="_blank" title="Guarda il video originale su youtube">Guarda il video originale su youtube</a>' +
				'</div>';		
				
			// rimpiazzo il codice	
			$(anchor).replaceWith(newCode);
			
			// true -> non fa aprire il link in un'altra finestra
			return(true);
		},
		
		// controlla se un id è un id valido youtube
		youTube_checkid : function(id){
			return( id.match(/^[A-Za-z_0-9-]+$/) );
		},
		
		// estrae l'id da un url youtube
		youTube_extract_id : function(url){

			
			// controllo che l'url sia coerente
			if( ! (
				url.dt_startsWithI('http://www.youtube.com') ||
				url.dt_startsWithI('http://youtube.com') 
				)
			){ return(''); } // se non è coerente, ritorno un vuoto
				
			// estrae l'id
			var youtube_id = url.replace(/^[^v]+v.([A-Za-z_0-9-]+).*/,"$1");
			// '/^[^v]+v.(.{11}).*/'
			
			// controllo che sia un id valido, altrimenti lo casso
			if( dthacks.url.youTube_checkid( youtube_id ) ){
				return( youtube_id );	
			}
			else{	
				return('');	
			}	
			
		},
		
		// riscrive gli url
		urlRewrite : function(){

			// ottengo tutti i link
			var linkPagina = document.getElementsByTagName("a");
			var anchor; // appoggio per il tag a
			var href; // appoggio per l'href corrente
			var i=0; // iteratore
			
			for (i = 0; i < linkPagina.length; i++) {
			
				// assegno ad href l'i-esimo link
				anchor = linkPagina[i];
				href = anchor.href;        
				
				var a = 0;
			
				// link che devono essere lasciati come sono
				if(
					href == '' || // no link
					href.dt_startsWithI('mailto:') || // indirizzi mail
					href.dt_chkExcluded() || // url esclusi
					anchor.className.toLowerCase().indexOf('dvdt_youtube_bbcode') > -1 // sono stati messi con il tag youtube		
				) { continue; }
				
				
				// link youtube che non sono stati messi col tag
				if( dthacks.url.youTube_extract_id(href) != ''  ){
					
					// provo a riscriverlo, se riesco skippo
					// altrimenti verrà mandato in finestra nuova
					if( dthacks.url.youtubeConvert( anchor ) )
						continue;
				
				}		
				
				// debug 
				// anchor.innerHTML += ' <span style="text-decoration: blink;">◄◄◄◄</span> ';
				// gli altri si possono accomodare fuori
				anchor.target="_blank";
			
			}
			
		}
		
	
	}, // fin parte url rewriter
	
	// helper per il bbcode	
	bbcode : {
		// per default, non ci sono i comandi 
		customBBcode : false,
		
		handleCustomBBcode_clickYT : function(event){
	
			// ottengo la selezione 
			var selection = $("textarea[name='message']").getSelection();
			
			// se la selezione è vuotma, mi limito a mettere i tag in posizione
			if( selection.start == selection.end ){
				// chiedo il link
				var userLink = prompt('Inserisci il link al video youtube');		
				
				// controllo se è un link valido
				if( dthacks.url.youTube_checkid(userLink) ){
					// lo inserisco 'as is'
					$("textarea[name='message']").insertAtCaretPos( '[YT]' + userLink + '[/YT]' );
				}
				else if( dthacks.url.youTube_extract_id(userLink) != '' ) { // provo ad estrarlo, in caso sia un link
					// se si può estrarre, lo estraggo
					$("textarea[name='message']").insertAtCaretPos( '[YT]' + dthacks.url.youTube_extract_id(userLink) + '[/YT]' );
				}
				else{
					// errore
					alert('L\'indirizzo ' + userLink + ' non sembra essere un indirizzo youtube valido.');
				}
				
				
				// inserisco i tag alla selezione
				// $("textarea[name='message']").insertAtCaretPos('[YT][/YT]')
			}
			// qualcosa è selezionato
			else{
				// controllo se è già un id valido
				if( dthacks.url.youTube_checkid(selection.text) ){
				
					// pare essere un id valido, wrappo nei tag
					$("textarea[name='message']").replaceSelection( '[YT]' + selection.text + '[/YT]' );
					// alert( selection.text );		
				
				}
				
				// controllo almeno inizi con 
				else if( dthacks.url.youTube_extract_id(selection.text) != '' ){
					// è valido, lo inserisco
					$("textarea[name='message']").replaceSelection( '[YT]' + dthacks.url.youTube_extract_id(selection.text) + '[/YT]' );	
					
				}
				else{
					// errore
					alert('L\'indirizzo ' + selection.text + ' non sembra essere un indirizzo youtube valido.');			
				}		
			}

		},
		
		// attaca gli eventi ai tag BBCode custom
		handleCustomBBcode : function (){

			// aggiungo gli eventi via jquery
			
			// youtube	
			// unbind rozzo dell'attributo
			$("input[value='YT']").removeAttr("onclick");
			// bind della nuova funzione	
			$("input[value='YT']").click(dthacks.bbcode.handleCustomBBcode_clickYT);
		},

		// array per mappare le hotkeys
		hotKeysMappings : Array(),
		
		// sezione per la pulitura dei quote doppi
		quoteCleaner : {
		
			// pulisce un testo 
			cleanNestedText : function(originalText){
				
				// REGEXP: trova tutti i tags
				var regFindTags = new RegExp("\\[.*?quote.*?\\]","gi");
							
				// una working copy 
				var wCopy = originalText;
				// copia output
				var oCopy = "";
				
				// tutti i tags
				var matches = wCopy.match(regFindTags);
				
				// se non ci sono matches, ritrono il testo com'è
				if(matches==null){
					return( originalText );
				}
				
				// livello di quote
				var level = 0;	
				// variabile appoggio
				var i = 0;		
				// tag che sto considerando
				var tagText = "";
				// teso prima
				var textBefore = "";
				// posizione del tag
				var tagPos = 0;
					
				for (i = 0; i < matches.length; i++)
				{
					tagText = matches[i];
					// trovo dovè l'elemento
					tagPos = wCopy.indexOf(tagText);
					// prima
					textBefore = wCopy.substr(0, tagPos);
					
					// aggiungo o non aggiungo?
					// se il livello è meno di due aggiungo
					if ( level < 2 ){ oCopy += textBefore; }
					
					// devo capire di che tipo è l'elemento
					if ( tagText.search("\\[\\w*?\\/quote\\w*?\\]") != -1 )
					{
						// tag di chiususra
						// abbasso il livello 
						level--;
						// se sono a 0, allora era l'ultimo tag e lo aggiungo
						if ( level == 0 ) { oCopy += tagText; }
					}
					else
					{
						// tag di apertura
						// alzo il livello 
						level++;
						// se sono a 1, allora era il primo tag e va accodato
						if ( level == 1 ) { oCopy += tagText; }
					}
					
					// avendo trattato il testo prima e il tag, li posso eliminare
					wCopy = wCopy.substr( textBefore.length + tagText.length );
					
					// se in qualsiasi momento sono a livello 
					// sottozero, allora ritorno vuoto
					if ( level < 0 ){ return(""); }
					
				}
				
				// se non sono tornato a livello 0
				// allora ritorno vuoto
				if ( level > 0 ){ return(""); }
				
				// altrimenti ritorno l'outtext
				return ( oCopy );
				
			},

			// installa il quote cleaner
			installCleaner : function(){
			
				// prima controlla che ci sia l'oggetto regExp, se non c'è non isntalla
				if( ! window.RegExp ) { 
					return; 
				}
				
				// installa il bottone cleaner
				var btnCleaner = $('<input type="button" value="No quote²" name="addbbcodeq2" class="btnbbcode" accesskey="2">').appendTo('#dt_customButtons');
				
				// installo l'event handler
				$(btnCleaner).click(function(e){					
					// provo a pulire il testo
					var cleanedText = dthacks.bbcode.quoteCleaner.cleanNestedText( $("textarea[name='message']").val() );
					
					// se è vuoto, ho sbagliato, qualcosa
					if ( cleanedText == ""){
						// disabilito il bottone in modo che non venga + chiamato
						$( btnCleaner ).attr('disabled', 'disabled');
					}
					else{
						// ok, posso sostituire il testo
						$("textarea[name='message']").val( cleanedText );
					}
				});			
			}		
		}	
	
	}, // fine parte bbcode
	
	hilight : {
		// per default non c'è il codice per evidenziale le righe
		chkHilight : false	
	},
	
	// smiles ajax
	smiles : {
		
		// oggetto standard ajax
		ajaxObj  : function(){
			var ajaxDef = {
				cache : false,
				url : dthacks.ajax.ajaxServiceDir + '/posting_smilies_gallery.php',
				beforeSend : function(request){ // prima di inviare, metto il loading				
					
					// controllo se esiste il target, se non esiste fermo tutto
					if( $('#dtAjaxSmiles').length != 1 ){
						return(false);
					}
					
					// se non ho salvato l'originale, lo faccio (solo la prima volta)
					if( dthacks.smiles.original == '' ){
						dthacks.smiles.original = $('#dtAjaxSmiles').html();
					}
					
					// metto il loading			
					$('#dtAjaxSmiles').html('<img src="' + dthacks.ajax.ajaxServiceDir + '/loading.gif" alt="Loading smiles" />');
					return(request);				
					
				},
				
				error : function(XMLHttpRequest, textStatus, errorThrown){
					// errore ajax ripristino l'originale
					$('#dtAjaxSmiles').html( dthacks.smiles.original );
				
				},
				
				success : function(data, textStatus, XMLHttpRequest){
					// carico i dati nella tabella
					$('#dtAjaxSmiles').html(data);
				}
				
			};
			
			return(ajaxDef);
		},
		
	
		// carica il pacco precedente
		prev :  function(first){
			// ottengo l'oggetto ajax
			var ajaxDef = dthacks.smiles.ajaxObj();
			
			// aggiungo il parametro
			ajaxDef.url += ( '?f=' + first );
			
			// mando 
			$.ajax(ajaxDef);
		
		},
		
		// carica il pacco successivo
		next : function(last){
			// ottengo l'oggetto ajax
			var ajaxDef = dthacks.smiles.ajaxObj();
			
			// aggiungo il parametro
			ajaxDef.url += ( '?l=' + last );
			
			// mando 
			$.ajax(ajaxDef);
		
		},
		
		// salva il frammento html originale
		original : ''
		
	}
	
};
