// seleziona e deseleziona un gruppo di checkbox
function setCheckboxes(form_name, do_check) {
	var numberOf_elements = document.forms[form_name].elements.length;

	for (var i = 0; i < numberOf_elements; i++) {
		var this_element = document.forms[form_name].elements[i];
		if (this_element.type == "checkbox")
			this_element.checked = do_check;
	}
	return true;
}

// seleziona e deseleziona tutte le righe di una select multipla
function set_all_selected(field_name, selected_value) {
	var this_element = document.getElementById(field_name);

	for (var i = 0; i < this_element.length; i++) {
		this_element.options[i].selected = selected_value;
	}
	return true;
}

// funzioni per la generazione di una password casuale
function get_random_pass(password_field, password2_field) {
	var num_pass_tries = 0;
	
	document.getElementById(password_field).value = generate_random_pass(num_pass_tries);
	if (document.getElementById(password2_field))
		document.getElementById(password2_field).value = document.getElementById(password_field).value;
}
function generate_random_pass(num_pass_tries) {
	num_pass_tries++;

	if (num_pass_tries >= 20) {
		alert("Unable to generate a password with a number, upper and lower case characters in it. Tried 20 times");
		return "error1";
	}

	var length = 8;
	var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

	var pass = "";
	var i=0;

	for (i=0; i<length; i++)
		pass = pass + random_char(chars);

	//this basically just says "ok, we need a number" so it recursivly tries again.
	if (!has_number(pass) || !has_lower_case(pass) || !has_upper_case(pass))
		return generate_random_pass(num_pass_tries);

	return pass;
}
function random_char(charlist) {
	var now = new Date();
	var seed = now.getSeconds();
	var num = Math.floor(Math.random(seed) * charlist.length);
	return charlist.charAt(num);
}
function has_number(pass) {
	var num_count = 0;

	for (i=0; i<pass.length; i++) {
		ch=pass.charAt(i);
		if ('0' <= ch && ch <= '9')
			num_count++;
	}
	
	return num_count;
}
function has_lower_case(pass) {
	var num_count = 0;

	for (i=0; i<pass.length; i++) {
		ch=pass.charAt(i);
		if ('a' <= ch && ch <= 'z')
			num_count++;
	}

	return num_count;
}
function has_upper_case(pass) {
	var num_count = 0;

	for (i=0; i<pass.length; i++) {
		ch=pass.charAt(i);
		if ('A' <= ch && ch <= 'Z')
			num_count++;
	}

	return num_count;
}

// visualizza l'anteprima di una icona
function icon_preview(preview_element, icon_path, select_name) {
	//alert(select_name.value);
	//alert(document.getElementById(preview_element).src);
	//alert(document.getElementById(preview_element).style.visibility);
	if (select_name.value!='') {
	   document.getElementById(preview_element).style.visibility='visible';
	   document.getElementById(preview_element).style.position='relative';
	   document.getElementById(preview_element).src = icon_path + select_name.value;
	}
	else {
	   document.getElementById(preview_element).style.visibility='hidden';
	   document.getElementById(preview_element).style.position='absolute';
	}
}

// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function HasClassName(objElement, strClass) {

	// if there is a class
	if (objElement.className) {

		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');

		// get uppercase class for comparison purposes
		var strClassUpper = strClass.toUpperCase();

		// find all instances and remove them
		for (var i = 0; i < arrList.length; i++) {
			// if class found
			if (arrList[i].toUpperCase() == strClassUpper) {
				// we found it
				return true;
			}
		}
	}

	// if we got here then the class name is not there
	return false;

}
// 
// HasClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function AddClassName(objElement, strClass, blnMayAlreadyExist) {

	// if there is a class
	if (objElement.className) {
		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');

		// if the new class name may already exist in list
		if (blnMayAlreadyExist) {
			// get uppercase class for comparison purposes
			var strClassUpper = strClass.toUpperCase();

			// find all instances and remove them
			for (var i = 0; i < arrList.length; i++) {
				// if class found
				if (arrList[i].toUpperCase() == strClassUpper) {
					// remove array item
					arrList.splice(i, 1);

					// decrement loop counter as we have adjusted the array's contents
					i--;

				}
			}
		}

		// add the new class to end of list
		arrList[arrList.length] = strClass;

		// add the new class to beginning of list
		//arrList.splice(0, 0, strClass);
      
		// assign modified class name attribute
		objElement.className = arrList.join(' ');

	}
	// if there was no class
	else {
		// assign modified class name attribute
		objElement.className = strClass;

	}
}
// 
// AddClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//
function RemoveClassName(objElement, strClass) {

	// if there is a class
	if (objElement.className) {

		// the classes are just a space separated list, so first get the list
		var arrList = objElement.className.split(' ');

		// get uppercase class for comparison purposes
		var strClassUpper = strClass.toUpperCase();

		// find all instances and remove them
		for (var i = 0; i < arrList.length; i++) {

			// if class found
			if (arrList[i].toUpperCase() == strClassUpper) {
				// remove array item
				arrList.splice(i, 1);

				// decrement loop counter as we have adjusted the array's contents
				i--;

			}
		}

		// assign modified class name attribute
		objElement.className = arrList.join(' ');

	}
	// if there was no class
	// there is nothing to remove

}
// 
// RemoveClassName
// ----------------------------------------------------------------------------

// visualizza o nascondi un oggetto
function show_hide(object_id, icon_element, icon_path){
	div = document.getElementById(object_id);
	
	if (icon_element != '' && icon_element != undefined) {
		image = document.getElementById(icon_element);
	}

	/*alert(HasClassName(div, 'hidden'));
	alert('Prima: ' + div.className);*/

	if (HasClassName(div, 'hidden') == true) {
		/*AddClassName(div, 'show', true);*/
	   RemoveClassName(div, 'hidden');
	   if (icon_element != '' && icon_element != undefined) {
	   	//image.src = icon_path + "view_right.gif";
	   	image.src = icon_path + "view_down.gif";
	   }
	}
	else {
	   AddClassName(div, 'hidden', true);
	   /*RemoveClassName(div, 'show');*/
	   if (icon_element != '' && icon_element != undefined) {
	   	//image.src = icon_path + "view_down.gif";
	   	image.src = icon_path + "view_right.gif";
	   }
	}
	/*alert('Dopo: ' + div.className);*/
}

function image_is_loaded(img) {
	// During the onload event, IE correctly identifiesany images that
	// weren’t downloaded as not complete. Others should too. Gecko-based
	// browsers act like NS4 in that they report this incorrectly.
	if (!img.complete)
		return false;
	
	// However, they do have two very useful properties: naturalWidth and
	// naturalHeight. These give the true size of the image. If it failed
	// to load, either of these should be zero.
	if (typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0)
		return false;
	
	// No other way of checking: assume it’s ok.
	return true;
}

// modifica il src di una immagine in caso sia visualizzata
function change_src(object_id, image_id, image_path){
	div = document.getElementById(object_id);
	
	if (HasClassName(div, 'hidden') == true) {
	   if (image_id != '' && image_id != undefined) {
	   	document.getElementById(image_id).src = image_path;
	   }
	}
	else {
	   if (image_id != '' && image_id != undefined) {
	   	document.getElementById(image_id).src = '';
	   }
	}
}

// limita i caratteri presenti in una textarea o in un textbox
function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
	else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

function dynamicSelect(id1, id2) {
	// Browser and feature tests to see if there is enough W3C DOM support
	var agt = navigator.userAgent.toLowerCase();
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	var is_mac = (agt.indexOf("mac") != -1);
	if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) {
		// Obtain references to both select boxes
		var sel1 = document.getElementById(id1);
		var sel2 = document.getElementById(id2);
		// Clone the dynamic select box
		var clone = sel2.cloneNode(true);
		// Obtain references to all cloned options 
		var clonedOptions = clone.getElementsByTagName("option");
		// Onload init: call a generic function to display the related options in the dynamic select box
		refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
		// Onchange of the main select box: call a generic function to display the related options in the dynamic select box
		sel1.onchange = function() {
			refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
		};
	}
}
function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {
	// Delete all options of the dynamic select box
	while (sel2.options.length) {
		sel2.remove(0);
	}
	// Create regular expression objects for "select" and the value of the selected option of the main select box as class names
	var pattern1 = /( |^)(select)( |$)/;
	var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
	// Iterate through all cloned options
	for (var i = 0; i < clonedOptions.length; i++) {
		// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
		if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) {
			// Clone the option from the hidden option pool and append it to the dynamic select box
			sel2.appendChild(clonedOptions[i].cloneNode(true));
		}
	}
}

// sostituto di 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.getAttribute("rel") == "external nofollow"))
			anchor.target = "_blank";
	}
}

// sleep per tot millisecondi
function sleep(delay) {
	var start = new Date().getTime();
	while (new Date().getTime() < start + delay);
}

// apre una connessione di richiesta con ajax
function open_request() {    
	// effettua una richiesta con ajax dentro la connessione appena aperta e setta il valore nel campo desiderato
	this.make_request = function (url, field, do_focus) {
		var xmlhttp = false;
		var self = this;
		// code for IE7+, Firefox, Chrome, Opera, Safari
		if (window.XMLHttpRequest)
			self.xmlhttp = new XMLHttpRequest();
		// code for IE6, IE5
		else
			self.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		// cannot create an XMLHTTP instance
		if (!self.xmlhttp)
			return false;
		// return contents
		self.xmlhttp.open("GET", url, true);
		self.xmlhttp.onreadystatechange = function() {
			if (self.xmlhttp.readyState == 4 && self.xmlhttp.status == 200)
				set_field_value(field, self.xmlhttp.responseText, do_focus);
		}
		self.xmlhttp.send();
	}
}
// effettua una richiesta con ajax e setta il valore nel campo desiderato
function make_request(url, field, do_focus) {
	xmlhttp = false;
	// code for IE7+, Firefox, Chrome, Opera, Safari
	if (window.XMLHttpRequest)
	  xmlhttp = new XMLHttpRequest();
	// code for IE6, IE5
	else
	  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	// cannot create an XMLHTTP instance
	if (!xmlhttp)
		return false;
	// return contents
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
			set_field_value(field, xmlhttp.responseText, do_focus);
	}
	xmlhttp.send();
}
// setta il valore ad un campo
function set_field_value(field, value, do_focus) {
	if (document.getElementById(field)) {
		if (document.getElementById(field) == '[object HTMLSelectElement]') {
			if (value != '' && value != undefined) {
				newdiv = document.createElement('div');
				newdiv.setAttribute('id', field + '_target');
				document.getElementById(field).parentNode.insertBefore(newdiv, document.getElementById(field));
				document.getElementById(field).parentNode.removeChild(document.getElementById(field));
				document.getElementById(field + '_target').innerHTML = value;
			}
		}
		else if (document.getElementById(field).value != undefined)
			document.getElementById(field).value = value;
		else if (document.getElementById(field).innerHTML != undefined)
			document.getElementById(field).innerHTML = value;
		if (do_focus == true)
			document.getElementById(field).focus();
	}
}

// trova lo stile leggendo nel css
function getStyleProp(x,prop){
	if(x.currentStyle)
   	return(x.currentStyle[prop]);
	if(document.defaultView.getComputedStyle)
   	return(document.defaultView.getComputedStyle(x,'')[prop]);
	return(null);
}
// crea un cookie
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=/';
}
// legge i dati di un cookie
function readCookie(name) {
  var nameEQ = name + '=';
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
// setta il font size
function setFontSize(action) {
	var body = document.getElementsByTagName("body")[0];
	var default_size = "62.5%";
	var min_size = 62.5;
	var max_size = 100;
	var size_unit = 6.25;
	
	// trovo la dimensione dei font in uso
	if (readCookie('dg_font_size') == null)
		var current_size = ( getStyleProp(body, "fontSize") == "" || getStyleProp(body, "fontSize") == "undefined" ? default_size : getStyleProp(body, "fontSize") );
	else
		var current_size = unescape ( readCookie('dg_font_size') )
	
	// in caso la dimensione sia salvata in pixel, la trasformo in percentuale
	if (current_size.match("px"))
		var current_size = String ( ( parseFloat ( current_size ) * size_unit ) ) + "%";
	
	// trovo la nuova dimensione dei font
	if (action == "increase" && parseFloat ( current_size ) < max_size)
		var new_font_size = String ( ( parseFloat ( current_size ) + size_unit ) ) + "%";
	
	else if (action == "decrease" && parseFloat ( current_size ) > min_size)
		var new_font_size = String ( ( parseFloat ( current_size ) - size_unit ) ) + "%";
		
	else {
		var new_font_size = current_size;
	}
	
	// imposto la nuova dimensione dei font
	//alert(new_font_size);
	body.style.fontSize = new_font_size;
	
	// salvo la nuova dimensione dei font nel cookie
	if (action == "increase" || action == "decrease" || readCookie('dg_font_size') == null)
		createCookie('dg_font_size', escape ( body.style.fontSize ), 365);
}

// carica le funzioni che devono essere caricate onload
window.onload = function() {
	setFontSize('read');
	externalLinks();
}

// casella che si cancella al click del mouse
function delDefaultValue(elem) {
	elemChange = document.getElementById(elem);
	if (elemChange.value == elemChange.defaultValue) {
		elemChange.value='';
	}
	elemChange.style.color = '#000';
}

function checkEmptyValue(elem) {
	elemChange = document.getElementById(elem);
	if (elemChange.value == '') {
		elemChange.style.color = '#bbb';
		elemChange.value = elemChange.defaultValue;
	}
}

// Copyright (C) 2005 Ilya S. Lyubinskiy. All rights reserved.
// Technical support: http://www.php-development.ru/
//
// YOU MAY NOT
// (1) Remove or modify this copyright notice.
// (2) Distribute this code, any part or any modified version of it.
//     Instead, you can link to the homepage of this code:
//     http://www.php-development.ru/javascripts/tabview.php.
//
// YOU MAY
// (1) Use this code on your website.
// (2) Use this code as a part of another product.
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind, either
// expressed or implied, including, but not limited to, the implied warranties
// of merchantability and fitness for a particular purpose. You expressly
// acknowledge and agree that use of this code is at your own risk.


// ----- Auxiliary -------------------------------------------------------------

function tabview_aux(TabViewId, id)
{
  var TabView = document.getElementById(TabViewId);

  // ----- Tabs -----

  var Tabs = TabView.firstChild;
  while (Tabs.className != "dinamic_tabs" ) Tabs = Tabs.nextSibling;

  var Tab = Tabs.firstChild;
  var i   = 0;

  do {
    if (Tab.tagName == "A") {
      i++;
      Tab.href      = "javascript:tabview_switch('"+TabViewId+"', "+i+");";
      Tab.className = (i == id) ? "selected" : "";
      Tab.blur();
    }
  }
  while (Tab = Tab.nextSibling);

  // ----- Pages -----

  var Pages = TabView.firstChild;
  while (Pages.className != 'dinamic_pages') Pages = Pages.nextSibling;

  var Page = Pages.firstChild;
  var i    = 0;

  do {
    if (Page.className == 'dinamic_page') {
      i++;
      //if (Pages.offsetHeight) Page.style.height = (Pages.offsetHeight-2)+"px";
      Page.style.display  = (i == id) ? 'block' : 'none';
    }
  }
  while (Page = Page.nextSibling);
}

// ----- Functions -------------------------------------------------------------

function tabview_switch(TabViewId, id) { tabview_aux(TabViewId, id); }

function tabview_initialize(TabViewId) { tabview_aux(TabViewId,  1); }
function show_map(MapFrameId, src) {
	document.getElementById(MapFrameId).src = src;
	return false;
}

// aggiungere ai preferiti
function add_bookmark(title, url) {
	if (document.all)
		window.external.AddFavorite(url, title);
	else if (window.sidebar)
		window.sidebar.addPanel(title, url, "");
}

