
// variabili globali
var smiliestrans = null;

// variabili per le funzioni dell'archivio
var archivio_anno_corrente = 0;
var object_type_selected = null;
var anno_object_selected = null;
var mese_object_selected = null;

/**************************************************************************
 * Funzioni per l'archivio												  *
 **************************************************************************/
function loadDefaultsArchivio(){
	
	var archivioAnni = document.getElementById("archivio-anni"); 
	archivioAnni.style.background = "url(/images/indicator.gif) no-repeat center center";
	
	var myEffect = new fx.Opacity(archivioAnni.getElementsByTagName("ul")[0] , {duration: 500} );
	myEffect.hide();

	var myAjax = new Ajax.Request("/blog/archivio-ajax.php?tipo=anni",{
		method: 'get',
		onFailure: function(request){
			archivioAnni.style.background = "none";
		},
		onSuccess: function(t){
			var data = t.responseXML;
			var content = "";
			var anni = data.getElementsByTagName("anno");
			for (var i=0; i<anni.length; i++) {
				node 		= anni.item(i);
				anno 		= node.childNodes.item(0).data;
				totElementi = node.getAttribute("tot");
				content += "<li onmouseover=\"this.className = 'selected'\" onmouseout=\"removeSelected(this)\" onclick=\"cambiaAnno(this, "+ anno +")\"><strong>"+ anno +"</strong>  ("+ totElementi +")</li>";
			}
			
			archivioAnni.childNodes[0].innerHTML = content;
			archivioAnni.style.background = "none";
			
			object_type_selected = "anni";
			content = null;
			
			myEffect.toggle();
		}
	});
}

function removeSelected(obj){
	for (var i=0; i<obj.parentNode.childNodes.length; i++) {
		node = obj.parentNode.childNodes[i];
		node.className = "";
		if( node == anno_object_selected || node == mese_object_selected ) {
			node.className = "selected";		
		}
	}
}

function cambiaAnno(obj, anno){
	
	object_type_selected = "anni";
	anno_object_selected = obj;
	archivio_anno_corrente = anno;

	removeSelected(obj);
	obj.className = "selected";
	
	var archivioMesi = document.getElementById("archivio-mesi");
	
	archivioMesi.innerHTML = "<ul><li></li></ul>";
	archivioMesi.style.background = "url(/images/indicator.gif) no-repeat center center";
	document.getElementById("archivio-posts").innerHTML = "";
			
	var myEffect = new fx.Opacity(archivioMesi.getElementsByTagName("ul")[0] , {duration: 500} );
	myEffect.hide();
	
	var myAjax = new Ajax.Request("/blog/archivio-ajax.php?tipo=mesi&anno="+ anno,{
		method: 'get',
		onFailure: function(request){
			archivioMesi.style.background = "none";
		},
		onSuccess: function(t){
			var data = t.responseXML;
			var content = "";
			var mesi = data.getElementsByTagName("mese");
			for (var i=0; i<mesi.length; i++) {
				node 		= mesi.item(i);
				mese 		= node.childNodes.item(0).data;
				numeroMese  = node.getAttribute("n");
				totElementi = node.getAttribute("tot");
				content += "<li onmouseover=\"this.className = 'selected'\" onmouseout=\"removeSelected(this)\" onclick=\"cambiaMese(this, "+ numeroMese +")\"><strong>"+ mese +"</strong>  ("+ totElementi +")</li>";
			}
			archivioMesi.childNodes[0].innerHTML = content;
			archivioMesi.style.background = "none";
			content = null;
			
			myEffect.toggle();
		}
	});
}

function cambiaMese(obj, mese){

	object_type_selected = "mesi";
	mese_object_selected = obj;
	
	removeSelected(obj);
	obj.className = "selected";
	
	var archivioPosts = document.getElementById("archivio-posts"); 
	archivioPosts.innerHTML = "<ul><li><em></em></li></ul>";
	archivioPosts.style.background = "url(/images/indicator.gif) no-repeat center center";
	
	var myEffect = new fx.Opacity(archivioPosts.getElementsByTagName("ul")[0] , {duration: 1000} );
	myEffect.hide();
	
	var myAjax = new Ajax.Request("/blog/archivio-ajax.php?tipo=posts&anno="+ archivio_anno_corrente +"&mese="+ mese,{
		method: 'get',
		onFailure: function(request){
			archivioPosts.style.background = "none";
		},
		onSuccess: function(t){
			var data = t.responseXML;
			var content = "";
			var posts = data.getElementsByTagName("post");
			for (var i=0; i<posts.length; i++) {
				node 	= posts.item(i);
				title 	= node.childNodes.item(0).data;
				path  	= node.getAttribute("path");
				content += "<li onmouseover=\"this.className = 'selected'\" onmouseout=\"removeSelected(this)\" onclick=\"location.href = '"+ path +"'\"><strong>"+ title +"</strong></li>";
			}
			archivioPosts.childNodes[0].innerHTML = content;
			archivioPosts.style.background = "none";
			content = null;
			
			myEffect.toggle();
		}
	});
}

/**************************************************************************
 * associa a tutte le ancore l'attributo target="_blank"				  *
 **************************************************************************/
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if ( anchor.getAttribute("href") &&	anchor.getAttribute("rel") == "external" ){
			anchor.target = "_blank";
		}
	}
}

/**************************************************************************
 * funzioni per la parte di amministrazione								  *
 **************************************************************************/
function admin_cancella(id, ritorno){
	if( confirm("Vuoi eliminare questo elemento?") ){
		location.href = "../actions.php?action=progetti.can&return="+ ritorno +"&id="+ id;
	}
}

function admin_reset(){
	if( confirm("Vuoi eliminare quello che hai scritto ??") ){
		return true;
	}
	return false;
}

function admin_anteprima(){
	var anteprimaObj = document.getElementById("anteprima");
	var descrizioneObj = document.getElementById("descrizione");
	anteprimaObj.innerHTML = descrizioneObj.value;
}


/**************************************************************************
 * Funzione che permette l'istallazione automatica						  * 
 * delle estensioni per Mozilla Firefox								      *
 **************************************************************************/	
function installMozillaFirefox(aEvent, extName) {   

	var params = new Array();
	params[extName] = {
		URL: aEvent.target.href,
		IconURL: "https://addons.update.mozilla.org/images/default.png",
		toString: function () { return this.URL; }
	};
	
	InstallTrigger.install(params);
	return false;
}

/**************************************************************************
 * Funzione che permette l'istallazione automatica						  * 
 * dei motori di ricerca perosnlizzati per Mozilla Firefox				  *
 **************************************************************************/	
function addMozillaFirefoxEngine(name, title, cat){
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
		window.sidebar.addSearchEngine(
			"http://www.blackbirdblog.it/download/firefox-search/"+ name +".src",
			"http://www.blackbirdblog.it/download/firefox-search/"+ name +".gif", title, cat);
	} else {
		alert("Questo plug-in \xe8 disponibile solamente per Mozilla Firefox!");
	}
	return false;
}

/**************************************************************************
 * Funzione che crea l'anteprima del commento mentre lo si scrive.		  * 
 **************************************************************************/
function initCommentPreview(){
	
	// smilies
	smiliestrans = new Array();
	smiliestrans[" :\\)"] 			= 	"icon_smile.gif";
	smiliestrans[" :D"]        		=	"icon_biggrin.gif";
	smiliestrans[" :-D"]       		=	"icon_biggrin.gif";
	smiliestrans[":grin:"]    		=	"icon_biggrin.gif";
	smiliestrans[" :\\)"]       	=	"icon_smile.gif";
	smiliestrans[" :-\\)"]      	=	"icon_smile.gif";
	smiliestrans[":smile:"]   		=	"icon_smile.gif";
	smiliestrans[" :\\("]       	=	"icon_sad.gif";
	smiliestrans[" :-\\("]      	=	"icon_sad.gif";
	smiliestrans[":sad:"]     		=	"icon_sad.gif";
	smiliestrans[" :o"]        		=	"icon_surprised.gif";
	smiliestrans[" :-o"]       		=	"icon_surprised.gif";
	smiliestrans[":eek:"]     		=	"icon_surprised.gif";
	smiliestrans[" 8O"]        		=	"icon_eek.gif";
	smiliestrans[" 8-O"]       		=	"icon_eek.gif";
	smiliestrans[":shock:"]   		=	"icon_eek.gif";
	smiliestrans[" :\\?"]       	=	"icon_confused.gif";
	smiliestrans[" :-\\?"]      	=	"icon_confused.gif";
	smiliestrans[" :\\?\\?\\?:"]	=	"icon_confused.gif";
	smiliestrans[" 8\\)"]       	=	"icon_cool.gif";
	smiliestrans[" 8-\\)"]      	=	"icon_cool.gif";
	smiliestrans[":cool:"]    		=	"icon_cool.gif";
	smiliestrans[":lol:"]     		=	"icon_lol.gif";
	smiliestrans[" :x"]        		=	"icon_mad.gif";
	smiliestrans[" :-x"]       		=	"icon_mad.gif";
	smiliestrans[":mad:"]     		=	"icon_mad.gif";
	smiliestrans[" :P"]        		=	"icon_razz.gif";
	smiliestrans[" :-P"]       		=	"icon_razz.gif";
	smiliestrans[":razz:"]    		=	"icon_razz.gif";
	smiliestrans[":oops:"]    		=	"icon_redface.gif";
	smiliestrans[":cry:"]     		=	"icon_cry.gif";
	smiliestrans[":evil:"]    		=	"icon_evil.gif";
	smiliestrans[":twisted:"] 		=	"icon_twisted.gif";
	smiliestrans[":roll:"]    		=	"icon_rolleyes.gif";
	smiliestrans[":wink:"]    		=	"icon_wink.gif";
	smiliestrans[" ;\\)"]       	=	"icon_wink.gif";
	smiliestrans[" ;-\\)"]      	=	"icon_wink.gif";
	smiliestrans[":\\!:"]       	=	"icon_exclaim.gif";
	smiliestrans[":\\?:"]       	=	"icon_question.gif";
	smiliestrans[":idea:"]    		=	"icon_idea.gif";
	smiliestrans[":arrow:"]   		=	"icon_arrow.gif";
	smiliestrans[" :\\|"]       	=	"icon_neutral.gif";
	smiliestrans[" :-\\|"]      	=	"icon_neutral.gif";
	smiliestrans[":neutral:"] 		=	"icon_neutral.gif";
	smiliestrans[":mrgreen:"] 		=	"icon_mrgreen.gif";
}

/*******************************************************************************
 * This is the update function from Jeff Minard - http://www.creatimation.net/ * 
 *******************************************************************************/
function superTextile(s) {
    var r = s;
    // quick tags first
    qtags = [['\\*', 'strong'],
             ['\\?\\?', 'cite'],
             ['\\+', 'ins'],  //fixed
             ['~', 'sub'],   
             ['\\^', 'sup'], // me
             ['@', 'code']];
    for (var i=0;i<qtags.length;i++) {
        ttag = qtags[i][0]; htag = qtags[i][1];
        re = new RegExp(ttag+'\\b(.+?)\\b'+ttag,'g');
        r = r.replace(re,'<'+htag+'>'+'$1'+'</'+htag+'>');
    }
    // underscores count as part of a word, so do them separately
    re = new RegExp('\\b_(.+?)_\\b','g');
    r = r.replace(re,'<em>$1</em>');
	
	//jeff: so do dashes
    re = new RegExp('[\s\n]-(.+?)-[\s\n]','g');
    r = r.replace(re,'<del>$1</del>');

    // links
    re = new RegExp('"\\b(.+?)\\(\\b(.+?)\\b\\)":([^\\s]+)','g');
    r = r.replace(re,'<a href="$3" title="$2">$1</a>');
    re = new RegExp('"\\b(.+?)\\b":([^\\s]+)','g');
    r = r.replace(re,'<a href="$2">$1</a>');

    // images
    re = new RegExp('!\\b(.+?)\\(\\b(.+?)\\b\\)!','g');
    r = r.replace(re,'<img src="$1" alt="$2">');
    re = new RegExp('!\\b(.+?)\\b!','g');
    r = r.replace(re,'<img src="$1">');
    
    // block level formatting
	
		// Jeff's hack to show single line breaks as they should.
		// insert breaks - but you get some....stupid ones
	    re = new RegExp('(.*)\n([^#\*\n].*)','g');
	    r = r.replace(re,'$1<br />$2');
		// remove the stupid breaks.
	    re = new RegExp('\n<br />','g');
	    r = r.replace(re,'\n');
	
    lines = r.split('\n');
    nr = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i].replace(/\s*$/,'');
        changed = 0;
        if (line.search(/^\s*bq\.\s+/) != -1) { line = line.replace(/^\s*bq\.\s+/,'\t<blockquote>')+'</blockquote>'; changed = 1; }
		
		// jeff adds h#.
        if (line.search(/^\s*h[1-6]\.\s+/) != -1) { 
	    	re = new RegExp('h([1-6])\.(.+)','g');
	    	line = line.replace(re,'<h$1>$2</h$1>');
			changed = 1; 
		}
		
		if (line.search(/^\s*\*\s+/) != -1) { line = line.replace(/^\s*\*\s+/,'\t<liu>') + '</liu>'; changed = 1; } // * for bullet list; make up an liu tag to be fixed later
        if (line.search(/^\s*#\s+/) != -1) { line = line.replace(/^\s*#\s+/,'\t<lio>') + '</lio>'; changed = 1; } // # for numeric list; make up an lio tag to be fixed later
        if (!changed && (line.replace(/\s/g,'').length > 0)) line = '<p>'+line+'</p>';
        lines[i] = line + '\n';
    }
	
    // Second pass to do lists
    inlist = 0; 
	listtype = '';
    for (var i=0;i<lines.length;i++) {
        line = lines[i];
        if (inlist && listtype == 'ul' && !line.match(/^\t<liu/)) { line = '</ul>\n' + line; inlist = 0; }
        if (inlist && listtype == 'ol' && !line.match(/^\t<lio/)) { line = '</ol>\n' + line; inlist = 0; }
        if (!inlist && line.match(/^\t<liu/)) { line = '<ul>' + line; inlist = 1; listtype = 'ul'; }
        if (!inlist && line.match(/^\t<lio/)) { line = '<ol>' + line; inlist = 1; listtype = 'ol'; }
        lines[i] = line;
    }

    r = lines.join('\n');
	// jeff added : will correctly replace <li(o|u)> AND </li(o|u)>
    r = r.replace(/li[o|u]>/g,'li>');

    return r;
}

/*******************************************************************************
 * Funzione per l'anteprima in tempo reale del commento 					   * 
 *******************************************************************************/
 
function findSmilie(item){
	var image = "none";
	if( smiliestrans[item] != null && typeof String ){
		image = smiliestrans[item];
	}
	return image;
}
	
function commentPreview(){
	var commentPreview 		= document.getElementById("comment-preview");
	
	var commentPreviewBody 	= document.getElementById("comment-preview-body");
	var commentPreviewName 	= document.getElementById("comment-preview-name");
	
	var commentHTML = document.getElementById("comment").value;
	var re = null;
	
	// processo il commento con Textile
	commentHTML = superTextile(commentHTML);
	
	// sostituisco i caratteri smile on l'immagine dello smile
	for (var item in smiliestrans) {
		re = new RegExp(item, "g");
		commentHTML = commentHTML.replace(re, " <img src=\"/images/smilies/"+ findSmilie(item) +"\" title=\""+ item.replace("\\","") +"\" />");
	}
	
	if( document.getElementById("comment").value != "" ){
		commentPreviewBody.innerHTML = commentHTML;
		if( document.getElementById("url").value != "" ){
			commentPreviewName.innerHTML = "<a href=\""+ document.getElementById("url").value +"\">"+ document.getElementById("author").value +"</a>";
		}else{
			commentPreviewName.innerHTML = document.getElementById("author").value;
		}
		commentPreview.style.display = "block";
	}else{
		commentPreviewBody.innerHTML = "<p>&nbsp;</p>";
		commentPreview.style.display = "none";
	}
}

/*******************************************************************************
 * apre il pop-up dell'help per Textile 					  				   * 
 *******************************************************************************/
function textileHelp(aObj){
	var w = window.open(aObj.href, "textilehelp", "width=400,height=400,scrollbars=yes,resizable=no");
	w.focus();
	return false;
}


/*******************************************************************************
 * Funzioni per il resize tracker dei commenti					  				   	 	   * 
 *******************************************************************************/
var resizeTracker 	= null;
var commento		= null;
var lastClientY     = 0;
var maxHeight		= 300;
var minHeight		= 100;

function resizeTracker_mouseDown(e){
	e = resizeTracker_fixE(e);
	lastClientY = e.clientY;
	document.onmousemove	= resizeTracker_startDrag;
	document.onmouseup		= resizeTracker_endDrag;
	return false;
}

function resizeTracker_startDrag(e){
	e = resizeTracker_fixE(e);
	heightShift = Math.abs(e.clientY - lastClientY);
	if( e.clientY > lastClientY ){
		newHeight =	(parseInt(commento.style.height)+heightShift);
		if( newHeight < maxHeight ){
			resizeTracker.style.top = (parseInt(resizeTracker.style.top)+heightShift) +"px";
			commento.style.height = newHeight +"px";
		}
	}else{
		newHeight =	(parseInt(commento.style.height)-heightShift);
		if( newHeight > minHeight ){
			resizeTracker.style.top = (parseInt(resizeTracker.style.top)-heightShift) +"px";
			commento.style.height = newHeight +"px";
		}
	}
	lastClientY = e.clientY;
	return false;
}

function resizeTracker_endDrag(e){
	e = resizeTracker_fixE(e);
	document.onmousemove = null;
	document.onmouseup   = null;
	lastClientY = e.clientY;
	return false;
}

function resizeTracker_fixE(e){
	if (typeof e == 'undefined') e = window.event;
	if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
	if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
	return e;
}

function initResizeTracker(){
	resizeTracker = document.getElementById("resizeTracker");
	if( resizeTracker ){
		var commentResizebar = document.getElementById("comment-resizebar")
		commento  = document.getElementById("comment");
		
		if( is_gecko ){
			// browsers basati su Gecko (prevalentemente Firefox)
			commento.style.height = minHeight+"px";
			resizeTrackerY = findPosY(commento) + parseInt(commento.style.height) + 1;
			resizeTrackerX = findPosX(commento) + parseInt(commento.style.width) - 16;
			commentResizebar.style.width = "675px";
			resizeTracker.style.top = resizeTrackerY +"px";
			resizeTracker.style.left = resizeTrackerX +"px";
			resizeTracker.onmousedown = resizeTracker_mouseDown;
			
		}else if( is_safari ){
			// browsers basati su AppleWebKit (prevalentemente Safari)
			commento.style.height = minHeight+"px";
			resizeTrackerY = findPosY(commento) + parseInt(commento.style.height) + 10;
			resizeTrackerX = findPosX(commento) + parseInt(commento.style.width) - 19;
			commentResizebar.style.width = "674px";
			resizeTracker.style.top = resizeTrackerY +"px";
			resizeTracker.style.left = resizeTrackerX +"px";
			resizeTracker.onmousedown = resizeTracker_mouseDown;
			
		}else if( is_ie ){
			// IE
			commento.style.height = minHeight+"px";
			resizeTrackerY = findPosY(commento) + parseInt(commento.style.height) - 2;
			resizeTrackerX = findPosX(commento) + parseInt(commento.style.width) - 17;
			commentResizebar.style.width = "675px";
			resizeTracker.style.top = resizeTrackerY +"px";
			resizeTracker.style.left = resizeTrackerX +"px";
			resizeTracker.onmousedown = resizeTracker_mouseDown;
			
		}else if( is_opera ){
			// Opera
			commento.style.height = minHeight+"px";
			resizeTrackerY = findPosY(commento) + parseInt(commento.style.height) + 8;
			resizeTrackerX = findPosX(commento) + parseInt(commento.style.width) - 18;
			commentResizebar.style.width = "674px";
			resizeTracker.style.top = resizeTrackerY +"px";
			resizeTracker.style.left = resizeTrackerX +"px";
			resizeTracker.onmousedown = resizeTracker_mouseDown;
			
		}else{
			// browser non riconosciuto, nascondo il resize tracker
			document.getElementById("comment-resizebar").style.display = "none";
			document.getElementById("resizeTracker").style.display = "none";
		}	
	}
}

function findPosX(obj){
	var curleft = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj){
	var curtop = 0;
	if (obj.offsetParent){
		while (obj.offsetParent){
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}else if (obj.y)
		curtop += obj.y;
	return curtop;
}

