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, "");
}

/*
	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();
};

/**
 * Image crop: apre l'area visibile dell'immagine 
 */
function showImageArea() {
	$('#nascondi').show();
	$('#mostra').hide();
	$(new Image()).load(function(){
		$(this).hide().attr('id', 'cropbox').unbind('load'); // ie bug fix!
		$('#imagecroparea').append(this);
		$(this).fadeIn(600, function(){
			cropCoords();
			$('#imagecroparea').slideDown('fast', function(){
				window.jcrop_api = $.Jcrop('#cropbox', {
					onChange: cropCoords,
					onSelect: cropCoords
				});
			});
		});
	}).attr('src', '/images/' + window.lastselection + '?' + Math.random()*1000);
}

/**
 * Image crop: apre l'area visibile dell'immagine 
 */
function hideImageArea() {
	$('#mostra').show();
	$('#nascondi').hide();
	window.jcrop_api.destroy();
	$('#imagecroparea').fadeOut(600, function(){
		$('#cropbox').remove();
	});
}

/**
 * Image crop: riporta le coordinate 
 */
function cropCoords(c) {
	if (c) {
		$('#x').val(c.x);
		$('#y').val(c.y);
		$('#w').val(c.w);
		$('#h').val(c.h);
	} else {
		$('#x').val('');
		$('#y').val('');
		$('#w').val('');
		$('#h').val('');
	}
};

function resourcesLookup() {
	if (jQuery.browser.msie) {
		$('#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'));
	} else {
		// Firefox 3, Chrome, Safari, Opera, etc...
		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'));
	}
	$('#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 + '&fix=' + parseInt(Math.random()*99999),
	  	async: false
		}).responseText);
}

function invoke(lookupurl, pars, callbackfunction) {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: lookupurl + "?" + pars + "&fix=" + parseInt(Math.random()*99999),
	  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=''});
  }
}

/**
 * Usata nella creazione dei form
 * Funzione generica di aggiunta nuovi componenti da modello
 * Se pos = -1, clona l'oggetto corrente accodandolo
 */
function add(pulsante, pos) {
	
	var clone = (pos==-1)?true:false;
	
	if (clone) {
		// rintraccia il modello dell'oggetto corrente
		var fieldtype = $(pulsante).parents('.model:eq(0)').find(':input:hidden[name$=_Atype]').val();
		var model = $('ol#models').find(':input:hidden[value=' + fieldtype + ']').parents('li');
		pos = ($('ol#models > li').index(model));
	}
	
	// trova il modello nella posizione indicata
	var masterCopy = $('ol#models > li:eq(' + pos + ')');	
	// trova il contenitore piu prossimo del pulsante
	var currentContainer = $(pulsante).parents('.model:eq(0)');
	// 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;
	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");
		
	if (clone) {
		duplicatedObj = currentContainer.clone();
		replaceWith = radice + modelRoot + num3;
		re = new RegExp(radice + modelRoot + num1, "g");
	}
	
	// [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 + "'");

	// 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();
	
	duplicatedObj.find('.fieldlabel').toggle(
		function() { $(this).next('div').slideDown('slow'); },
		function() { $(this).next('div').slideUp('slow'); }
	);
}

/**
 * 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(); } );
}

/**
 * Aggiunge apertura/chiusura ai campi dei form durante la creazione (edit)
 */
function slider() {
	$(document).find('.fieldlabel').each(
		function() {
			$(this).toggle(
					function() { $(this).next('div').slideDown('slow'); },
					function() { $(this).next('div').slideUp('slow'); }
			)
		}
	);
}

/**
 * Apre chiude una sezione marcata con class='openclose'
 */
function openclose(elem) {
	var div = $(elem).parent().find('.openclose');
	if (div.is(':visible')) {
		div.slideUp('slow');
	} else {
		div.slideDown('slow');
	}
};

/**
 * 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>';
};

/**
 * Sostituisce gli apici singoli con \'
 */
function escapeQuotes(str) {
	return (str == null || str=='') ? str : str.replace(/\'/g, "\'");
};

/**
 * Newsletter email configuration
 */
function toggleNewsletterEmail() {
	if (document.getElementById('email_Ause-alternative').checked) { $('#emailconf').slideDown(); } else { $('#emailconf').slideUp(); }
};

/**
 * Newsletter scheduling
 */
function toggleNewsletterSchedule() {
	if ($('input:radio[name=sendmode]:checked').val() == 'scheduled') { $('#sched').slideDown(); } else { $('#sched').slideUp(); }
};

/**
 * Newsletter css display
 */
function toggleNewsletterCSS() {
	if ($('input:radio[name=mime]:checked').val() == 'text/html') { $('#cssinput').slideDown(); } else { $('#cssinput').slideUp(); }
};

/**
 * Imagelist directory display
 */
function toggleImagelist() {
	if ($('input:radio[name=autoload_Amode]:checked').val() == 'none') {
		$('#autoloadzip').slideUp();
		$('#autoloadfolders').slideUp();
	}
	if ($('input:radio[name=autoload_Amode]:checked').val() == 'zip') {
		$('#autoloadzip').slideDown();
		$('#autoloadfolders').slideUp();
	}
	if ($('input:radio[name=autoload_Amode]:checked').val() == 'folders') {
		$('#autoloadzip').slideUp();
		$('#autoloadfolders').slideDown();
	}	
};

/**
 * File manager: copia
 */
function copy() {
	window.filecopy = window.lastselection;
	if (window.filecopy != '') {
		$('#paste').removeAttr('disabled');
	}
};

/**
 * File manager: incolla
 */
function paste() {
	if (window.confirm('Confirm copy operation?\nfrom: \'' + window.filecopy + '\'\nto: \'' + window.lastselection + '\'')) {
		invoke('action-copy-file-or-directory', 'from=' + window.filecopy + '&to=' + window.lastselection, function(){
			$('#paste').attr('disabled', 'true');
			window.refreshParentNode();
			window.filecopy = '';
		});
	}		
};

/**
 * Imagelist: azione di rotazione immagine
 */
function rotate(large, thumb, clockwise) {
	$.ajax({
	  type: "GET",
	  dataType: "xml",
	  url: "action-rotate-imagelist" + "?large=" + large + "&thumb=" + thumb + "&clockwise=" + clockwise + "&fix="+parseInt(Math.random()*99999),
	  success: function(xml){
	  	window.location.reload();
	  }
	});	
};


/**
 * FileUpload: gestione progressbar avanzamento upload
 */

var pct = 0;
var handler = null;

function uploadFile(tform, turi, callbackfunction) {
	$('#progressbar').reportprogress(0);
	$.ajaxUpload({
		uploadform: tform,
		url: turi,
		secureuri: false,
		dataType: 'xml',
		success: function(xml) {
			window.clearTimeout(handler);
			alert($('message', xml).text());
			$('#progressbar').reportprogress(0);
			var fileName = $('message', xml).attr('file');
	  		if (callbackfunction && typeof callbackfunction=='function') {
	  			callbackfunction(xml);
	  		}
		},
		error: function (msg, status, e) {
			window.clearTimeout(handler);
			alert(e);
			$('#progressbar').reportprogress(0);
		}
	});
	handler = window.setTimeout(uploadProgress, 2000);
}

function uploadProgress() {
	$.ajax({
		url: '/cmd-uploadprogress',
		cache: false,  // this is important, otherwise there's no progress in IE!
		success: function(response) {
			var s = response.split('/');
			pct = parseFloat(100*s[0]/s[1]);
			if (isNaN(pct)) pct = 0;
			$('#progressbar').reportprogress(pct);
			if (pct<100) {
				handler = window.setTimeout(uploadProgress, 3000);
			}
		}
	});
};

var newsletterinprogress = true;
var newslettersendingstop = false;
function newsletterAgentMonitor() {
	$.ajax({
		url: '/cmd-newsletteragentmonitor?source=' + $('#Asource').val() + '&stop=' + newslettersendingstop,
		cache: false,  // this is important, otherwise there's no progress in IE!
		success: function(response) {
			var s = response.split('/');
			if (s.length==4) {
				var bg = $('#sendcounter').css('background-color');
				$('#sendcounter').html(s[0]).animate({ backgroundColor: 'silver' }, 200).animate({ backgroundColor: bg, color: 'green' }, 200);
				$('#senderror').html(s[1]).animate({ backgroundColor: 'silver' }, 200).animate({ backgroundColor: bg, color: 'green' }, 200);
				$('#sendtotal').html(s[2]).animate({ backgroundColor: 'silver' }, 200).animate({ backgroundColor: bg, color: 'green' }, 200);
				$('#sendlastupdate').html(s[3]).animate({ backgroundColor: 'silver' }, 200).animate({ backgroundColor: bg, color: 'green' }, 200);
			} else {
				newsletterinprogress = false;
				window.location.reload();
			}
			if (newsletterinprogress) {
				handler = window.setTimeout(newsletterAgentMonitor, 3000);
			}
		}
	});
};
