/*
	param1 stringa sulla quale fare substring
	param2 sottostringa da individuare
	return dall'indexOf fino alla fine della stringa
*/
function chunker() {
	pos = arguments[0].indexOf(arguments[1]);
	return arguments[0].substring(pos + 2, arguments[0].length);
}

//Stick del footer alla base delle pagine
function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}
function setFooter() {
	if (document.getElementById) {
		var windowHeight = getWindowHeight();
		if (windowHeight > 0) {
			var contentHeight = document.getElementById('container').offsetHeight;
			var footerElement = document.getElementById('footer');
			if (footerElement) {
				var footerHeight  = footerElement.offsetHeight;
				if (windowHeight - (contentHeight + footerHeight) >= 0) {
					footerElement.style.position = 'relative';
					footerElement.style.top = (windowHeight - (contentHeight + footerHeight - footerHeight)) + 'px';
				}
				else {
					footerElement.style.position = 'static';
				}
			}
		}
	}
}

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function deleteCookie(NameOfCookie) {
	if (getCookie(NameOfCookie)) {
		document.cookie = NameOfCookie + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function getCookie(NameOfCookie) {
	if (document.cookie.length > 0) {
		begin = document.cookie.indexOf(NameOfCookie + "=");
		if (begin != -1) {
			begin += NameOfCookie.length + 1;
			end = document.cookie.indexOf(";", begin);
			if (end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(begin, end));
		}
	}
	return null;
}

/* ora non piu utilizzata */
/* Aggiunge la pseudoclasse :hover sui paragrafi anche ad internet explorer */
function phover(){
  if (!document.getElementById) return

  var p = document.getElementsByTagName('p');
  for(var i = 0; i < p.length; i++){
   p[i].onmouseover = function(){
    this.className = 'hover';
   }
   p[i].onmouseout  = function(){
    this.className = '';
   }
  }
}

/*
 * Copia il valore del titolo della pagina sul document name solo se document name è vuoto
 */
function copytitle(docTitle) {
	var Aname = document.getElementById('Aname');
	if (Aname.value.length==0) {
		if (docTitle.value.length>60) {
			Aname.value = docTitle.value.substring(0,60) + "...";
		} else {
			Aname.value = docTitle.value;
		}
		Aname.value = Aname.value.trim();
	}
}

/**
 * Apre una finestra popup a centro pagina della dimensione dell'immagine da mostrare
 * NB: E' duplicata in fckeditor
 */
function popup(vedi) {
	var addr = '';
	var obj = vedi.previousSibling;
	if (obj.tagName=='DIV' || obj.tagName=='SPAN') {
		// e possibile che l'oggetto stia dentro un DIV per AJAX
		for (var i=0; i<obj.childNodes.length; i++) {
			if (obj.childNodes[i].tagName) {
				addr = obj.childNodes[i].value;
			}
		}
	} else {
		addr = obj.value;
	}
	
	if (addr!='') {
		if (addr.toLowerCase().indexOf(".xml")>0) {
			var l = (window.screen.width - 800) / 2;
			var t = (window.screen.height - 600) / 2;
			_popup=window.open("cmd-preview?entity=" + addr,"","width=800,height=600,scrollbars=1,resizable=1,top="+t+",left="+l);
			_popup.focus();
		} else {
			window.location = "/download/" + addr;
		}
	}
};

/**
 * Apre un popup a centro pagina contente la pagina indicata nell'indirizzo passato come parametro
 */
function popupurl(addr) {
	var l = (window.screen.width - 800) / 2;
	var t = (window.screen.height - 600) / 2;
	_popup=window.open(addr,"","width=800,height=600,scrollbars=1,resizable=1,top="+t+",left="+l);
	_popup.focus();
};

function resourcesLookup() {
	if (jQuery.browser.version.substr(0,3)=='1.9' 
		|| jQuery.browser.version.substr(0,2)=='52'
		|| jQuery.browser.version.substr(0,2)=='9.') {
		
		// Firefox 3, Chrome (525), Safari (522), Opera (9.52)
		var ee =	$.ajax({
	  	type: 'GET',
	  	dataType: 'xml',
	  	url: document.baseURI+'action-invoke?xq=lookup-entity-list&c='+$('#_c').val()+'&n='+$('#_n').val()+'&type='+$('#Aentity').val(),
	  	async: false
		}).responseText;
		$('#entityResultset').html($(ee).children('ul'));

	} else {
		
		// IE6, IE7, Firefox2
		$('#entityResultset').html(
			$.ajax({
		  	type: 'GET',
		  	url: document.baseURI+'action-invoke?xq=lookup-entity-list&c='+$('#_c').val()+'&n='+$('#_n').val()+'&type='+$('#Aentity').val(),
		  	async: false
			}).responseText
		).html($('#entityResultset').children('ul'));
	}
	$('#q').focus();
};

function assignRes(linkId, sourceId) {
	var root = $('#t').val();
	var completeName = $(linkId).text();
	$('#'+root+'source').val(sourceId);
	$('#'+root+'alias').val(chunker(completeName,':'));
	$('#'+root+'name').val(completeName).focus();
	tb_remove();
};

/**
 * Attiva l'editor grafico FCKeditor
 */
function startup(pulsante, mode, _heigth, _locale) {
	var _heigth = (20 * _heigth) + 70;
	var oFCKeditor = new FCKeditor(pulsante.previousSibling.id, '100%', _heigth, mode);
	oFCKeditor.Config.DefaultLanguage = _locale.toLowerCase();
	oFCKeditor.ReplaceTextarea();
	pulsante.parentNode.removeChild(pulsante);
}

function simplelookup(lookupURL, pulsante) {
	var obj = pulsante;
	if (obj.tagName=='SELECT') obj = obj.parentNode;
	while(true) {
		for (var i=0; i<obj.childNodes.length; i++) {
			var subobj = obj.childNodes[i];
			if (subobj.tagName=='INPUT' || subobj.tagName=='SELECT') {
				lookup(lookupURL, obj.id, subobj.value, subobj.id);
				return;
			}
		}
		obj = obj.previousSibling;
	}
}

function lookup(lookupURL, tobereplaced, valore, htmlname) {
	$('#'+tobereplaced).html(
		$.ajax({
	  	type: "GET",
	  	url: lookupURL + '?dir=' + valore + '&name=' + htmlname,
	  	async: false
		}).responseText);
}

function invoke(lookupurl, pars, callbackfunction) {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: lookupurl + "?" + pars,
	  success: function(xml){
	  	alert($("message", xml).text());
	  	if (callbackfunction && typeof callbackfunction=='function') {
	  		callbackfunction();
	  	}
		}
	});
}

/**
 * Usata solo nella gestione combobox di sistema
 */
function addChild(objToDuplicate, prefix) {
	var obj = $(objToDuplicate);
	var re = new RegExp("("+prefix+")(\\d*)", "g");
  var m = re.exec(obj.html());
  if (m==null) {
    alert("Error!");
  } else {
		var duplicatedObj = obj.clone();
  	var replaceWith = prefix + (parseInt(m[2])+100);
		if (obj.css('display')=='none') {
			duplicatedObj.find("*[@name^=_], *[@for^=_]").each(
				function() {
					if (this.id) this.id=this.id.substring(1);
					if (this.name) {
						this.name=this.name.substring(1);
						// Bugfix: ie6/7 shit
						if (document.all) this.outerHTML=this.outerHTML.replace("_"+this.name, this.name);
					}
					if (this.htmlFor) this.htmlFor=this.htmlFor.substring(1);
				}
			);
		}
  	duplicatedObj.html(duplicatedObj.html().replace(re, replaceWith)).hide().appendTo(obj.parent()).slideDown("slow").find(':text, select').each(function() {this.value=''});
  }
}

/**
 * Funzione generica di aggiunta nuovi componenti da modello
 */
function add(pulsante, pos) {
	
	// trova il contenitore piu prossimo del pulsante
	var currentContainer = $(pulsante).parents('.model:eq(0)');
	// trova il modello nella posizione indicata
	var masterCopy = $('ol#models > li:eq('+pos+')');
	
	// nome del primo campo dell'oggetto corrente
	var currId = currentContainer.find("*[@name]").attr('id');
	// nome del primo campo dell'oggetto successivo
	var nextId = currentContainer.next().find("*[@name]").attr('id');
	// nome del primo campo del modello selezionato
	var masterId = masterCopy.find("*[@name]").attr('id');
	
	// estraggo la radice dall'oggetto corrente, tramite il nome del campo del modello
	var matcherId = masterId.substring(1, masterId.length).replace("XXX", "\\d*");	
	var terminazione = new RegExp(matcherId).exec(currId);
	var radice = (terminazione==null)?currId.substring(0, currId.lastIndexOf('_')+1):currId.substring(0, currId.indexOf(terminazione));
	
	// ricavo il numeratore successivo dalla terminazione dell'oggetto corrente in base al numero del successivo
	var m1 = new RegExp("(_)(\\d*)(_)").exec(terminazione);
	var terminazioneNext = (nextId==null)?"":new RegExp(matcherId).exec(nextId);
	var m2 = new RegExp("(_)(\\d*)(_)").exec(terminazioneNext);
	var num1 = m1==null?(m2==null?100:parseInt(m2[2])/2):(parseInt(m1[2]));
	var num2 = m2==null?(parseInt(num1)+200):parseInt(m2[2]);
	var num3 = parseInt(num1) + parseInt((parseInt(num2)-parseInt(num1))/2);
	var modelRoot = masterId.substring(1, masterId.indexOf("XXX"));
	var replaceWith = radice + modelRoot + num3;

	// [DEBUG] alert("currId: '" + currId + "'\nnextId: '" + nextId + "'\nmasterId: '" + masterId + "'\nmatcherId: '" + matcherId + "'\nterminazione: '" + terminazione + "'\nradice: '" + radice + "'\nterminazioneNext: '" + terminazioneNext + "\nm1: '" + m1 + "\nm2: '" + m2 + "'\nnum1: '" + num1 + "'\nnum2: '" + num2 + "'\nnum3: '" + num3 + "'\nmodelRoot: '" + modelRoot + "'\nreplaceWith: '" + replaceWith + "'");

	var duplicatedObj = masterCopy.clone();
	// sostituisce tutti i nomi escludendo sempre il primo eventuale underscore in caso nel trovi due consecutivi
	var re = new RegExp("(?![_]{2})([a-zA-Z0-9_\-]*_XXX)","g");
	// sostituisce gli ID su tutti gli elementi, accoda il nuovo oggetto e assegna il focus al primo input per l'accessibilita
	duplicatedObj.html(duplicatedObj.html().replace(re,replaceWith)).hide().insertAfter(currentContainer).slideDown("slow").find(':text:eq(0)').focus();
}

/**
 * Funzione generica di cancellazione componenti
 */
function del(obj) {
	$(obj).parents('.model:eq(0)').slideUp("slow", function(){ $(this).remove(); } );
}

/**
 * Usata in ACL
 */
function deleteChild(obj) {
	$(obj).parent().slideUp("slow", function(){ $(this).remove(); } );
}

function slider() {
	$(document).find('.fieldlabel').each(
		function() {
			$(this).toggle(
					function() { $(this).next('div').slideDown('slow'); },
					function() { $(this).next('div').slideUp('slow'); }
			)
		}
	);
}

/**
 * Risolve il problema di visualizzazione dei form sotto firefox perche non supporta 'inline-block',
 * quando la label finisce sotto il controllo perche troppo lunga
 */
function cmxform() {
	try {
	  $('form.cmxform').hide().end();
	  //$('form.cmxform').find('li > label') non intercettava il table-layout sui radio
	  $('form.cmxform').find('li label').not('.nocmx, .label-block').each(
	  	function(i){
		    var labelContent = this.innerHTML;
		    var labelWidth = document.defaultView.getComputedStyle(this, '').getPropertyValue('width');
		    var labelSpan = document.createElement('span');
		    labelSpan.style.display = 'block';
		    labelSpan.style.width = labelWidth;
		    labelSpan.innerHTML = labelContent;
		    this.style.display = '-moz-inline-box';
		    this.innerHTML = null;
		    this.appendChild(labelSpan);
		  }
		).end();
	  $('form.cmxform').show().end();
	} catch(e) {}
}

/**
 * Attenzione, funzione ricorsiva
 * Cancella il valore di default contenuto nel campo di input passato come parametro
 * Per capire che e' un default suppone che termini con '...'
 * Se non si passa alcun parametro resetta tutti i campi contenuti nei form di classe 'cmxform'
 */
function resetDefaultValue(field) {
	if (field) {
		if (field.value.endsWith('...')) field.value='';
	} else {
		// disabilito il submit immediatamente
		$(".cmxform input[type='submit']").attr('disabled', 'true').css('background', '#fff');
		$('.cmxform :input').not(':hidden').each(function(i) { resetDefaultValue(this); })
	}
}

function nospam(server, em, t) {
  var e = (em + '@' + server);
  return '<a href="mailto:' + e + '" title="' + t + '">' + e + '</a>';
}

String.prototype.startsWith = function(value) {
	return (this.substr(0, value.length)==value);
}

String.prototype.endsWith = function(s) {
 return (s == this.substring(this.length - s.length));
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}

/**
 * Invocata ad ogni caricamento della pagina
 */
window.onload = function() {
	/* @replace@ */
	// phover(); non piu utilizzata
	setFooter();
}                       

/**
 * Invocata ad ogni ridimensionamento della finestra
 */
window.onresize = function() {
	setFooter();
}

/**
 * Risolve il problema di visualizzazione dei form in modalita tabellare,
 * quando la label finisce sotto il controllo perche troppo lunga
 */
if (document.addEventListener) document.addEventListener( 'DOMContentLoaded', cmxform, false);