//JS Functions @0-7884768D
var isNN = (navigator.appName.indexOf("Netscape") != -1);
var isIE = (navigator.appName.indexOf("Microsoft") != -1);
var IEVersion = (isIE ? getIEVersion() : 0);
var NNVersion = (isNN ? getNNVersion() : 0);
var EditableGrid = false;
var disableValidation = false;

function functionExists(functionName)
{
  var exists = true;
  try{
    exists = typeof(eval(functionName))=="function";
  }catch(e){
    exists = false;
  }
  return exists;
}

function ccsShowError(control, msg)
{
  alert(msg);
  control.focus();
  return false;
}

function getNNVersion()
{
  var userAgent = window.navigator.userAgent;
  var isMajor = parseInt(window.navigator.appVersion);
  var isMinor = parseFloat(window.navigator.appVersion);
  if (isMajor == 2) return 2;
  if (isMajor == 3) return 3;
  if (isMajor == 4) return 4;
  if (isMajor == 5) 
  {
    if (userAgent.toLowerCase().indexOf('netscape')!=-1)
    {
      isMajor = parseInt(userAgent.substr(userAgent.toLowerCase().indexOf('netscape')+9));
      if (isMajor>0) return isMajor;
    }
    return 6;
  }
  return isMajor;
}

function getIEVersion()
{
  var userAgent = window.navigator.userAgent;
  var MSIEPos = userAgent.indexOf("MSIE");
  return (MSIEPos > 0 ? parseInt(userAgent.substring(MSIEPos+5, userAgent.indexOf(".", MSIEPos))) : 0);
}

function inputMasking(evt)
{
  if (isIE && IEVersion > 4)
  {
    if (window.event.altKey) return false;
    if (window.event.ctrlKey) return false;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = window.event.keyCode;
      this.value = applyMask(keycode, mask, this.value);
    }
    return (window.event.keyCode==13?true:false);
  } else if (isNN && NNVersion<6)
  {
    if (evt.ALT_MASK) return false;
    if (evt.CONTROL_MASK) return false;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = evt.which;
      this.value = applyMask(keycode, mask, this.value);
    }
    return (evt.which==13?true:false);
  } else if (isNN && NNVersion==6)
  {
    if (evt.altKey) return false;
    if (evt.ctrlKey) return false;
    var cancelKey = evt.which==13;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = evt.which;
      if (keycode >= 32)
        this.value = applyMaskToValue(mask, this.value);
    }
    return cancelKey || evt.which==13;
  } else if (isNN && NNVersion==7)
  {
    if (evt.altKey) return false;
    if (evt.ctrlKey) return false;
    var cancelKey = evt.which==13;
    if (typeof(this.ccsInputMask) == "string")
    {
      var mask = this.ccsInputMask;
      var keycode = evt.which;
      cancelKey = keycode < 32;
      if (!cancelKey)
        this.value = applyMask(keycode, mask, this.value);
    }
    return cancelKey || evt.which==13;
  } else
    return true;
}

function applyMaskToValue(mask, value)
{
  var oldValue = String(value);
  var newValue = "";
  for (var i=0; i<oldValue.length; i++)
  {
    newValue = applyMask(oldValue.charCodeAt(i), mask, newValue);
  }
  return newValue;
}

function applyMask(keycode, mask, value)
{
  var digit = (keycode >= 48 && keycode <= 57);
  var plus = (keycode == 43);
  var dash = (keycode == 45);
  var space = (keycode == 32);
  var uletter = (keycode >= 65 && keycode <= 90);
  var lletter = (keycode >= 97 && keycode <= 122);
  
  var pos = value.length;
  switch(mask.charAt(pos))
  {
    case "0":
      if (digit)
        value += String.fromCharCode(keycode);
      break;
    case "L":
      if (uletter || lletter)
        value += String.fromCharCode(keycode);
      break;
    default:
      var isMatchMask = (String.fromCharCode(keycode) == mask.charAt(pos));
      while (pos < mask.length && mask.charAt(pos) != "0" && mask.charAt(pos) != "L")
        value += mask.charAt(pos++);
      if (!isMatchMask && pos < mask.length)
        value = applyMask(keycode, mask, value);
  }  
  return value;
}

function validate_control(control)
{
/*
ccsCaption - string
ccsErrorMessage - string

ccsRequired - boolean
ccsMinLength - integer
ccsMaxLength - integer
ccsRegExp - string

ccsValidator - validation function

ccsInputMask - string
*/
  if (disableValidation) return true;
  var errorMessage = control.ccsErrorMessage;
  var customErrorMessage = (typeof(errorMessage) != "undefined");
   
  if (typeof(control.ccsRequired) == "boolean" && control.ccsRequired)
    if (control.value == "")
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is required.");

  if (typeof(control.ccsMinLength) == "number")
    if (control.value != "" && control.value.length < parseInt(control.ccsMinLength))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The length in field " + control.ccsCaption + " can't be less than " + parseInt(control.ccsMinLength) + " symbols.");

  if (typeof(control.ccsMaxLength) == "number")
    if (control.value != "" && control.value.length > parseInt(control.ccsMaxLength))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The length in field " + control.ccsCaption + " can't be greater than " + parseInt(control.ccsMaxLength) + " symbols.");

  if (typeof(control.ccsInputMask) == "string")
  {
    var mask = control.ccsInputMask;
    var maskRE = new RegExp(stringToRegExp(mask).replace(/0/g,"\\d").replace(/L/g,"[A-Za-z]"), "i");
    if (control.value != "" && (control.value.search(maskRE) == -1))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is not valid.");
  }

  if (typeof(control.ccsRegExp) == "string")
    if (control.value != "" && (control.value.search(new RegExp(control.ccsRegExp, "i")) == -1))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is not valid.");

  if (typeof(control.ccsDateFormat) == "string")
  {
    if (control.value != "" && !checkDate(control.value, control.ccsDateFormat))
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is not valid. Use the following format: "+control.ccsDateFormat);
  }

  if (typeof(control.ccsValidator) == "function")
    if (!control.ccsValidator())
      return ccsShowError(control, customErrorMessage ? errorMessage :
        "The value in field " + control.ccsCaption + " is not valid.");

  return true;
}

function stringToRegExp(string, arg)
{
  var str = String(string);
  str = str.replace(/\\/g,"\\\\");
  str = str.replace(/\//g,"\\/");
  str = str.replace(/\./g,"\\.");
  str = str.replace(/\(/g,"\\(");
  str = str.replace(/\)/g,"\\)");
  str = str.replace(/\[/g,"\\[");
  str = str.replace(/\]/g,"\\]");
  return str;
}

function checkDate(dateValue, dateFormat)
{
  var DateMasks = new Array(
                    new Array("MMMM", "[a-z]+"),
                    new Array("mmmm", "[a-z]+"),
                    new Array("yyyy", "[0-9]{4}"),
                    new Array("MMM", "[a-z]+"),
                    new Array("mmm", "[a-z]+"),
                    new Array("HH", "([0-1][0-9]|2[0-4])"),
                    new Array("hh", "(0[1-9]|1[0-2])"),
                    new Array("dd", "([0-2][0-9]|3[0-1])"),
                    new Array("MM", "(0[1-9]|1[0-2])"),
                    new Array("mm", "(0[1-9]|1[0-2])"),
                    new Array("yy", "[0-9]{2}"),
                    new Array("nn", "[0-5][0-9]"),
                    new Array("ss", "[0-5][0-9]"),
                    new Array("w", "[1-7]"),
                    new Array("d", "([1-9]|[1-2][0-9]|3[0-1])"),
                    new Array("y", "([1-2][0-9]{0,2}|3([0-5][0-9]|6[0-5]))"),
                    new Array("H", "(00|0?[1-9]|1[0-9]|2[0-4])"),
                    new Array("h", "(0?[1-9]|1[0-2])"),
                    new Array("M", "(0?[1-9]|1[0-2])"),
                    new Array("m", "(0?[1-9]|1[0-2])"),
                    new Array("n", "[0-5]?[0-9]"),
                    new Array("s", "[0-5]?[0-9]"),
                    new Array("q", "[1-4]")
                  );
  var regExp = "^"+stringToRegExp(dateFormat)+"$";
  for (var i=0; i<DateMasks.length; i++)
  {
    regExp = regExp.replace(DateMasks[i][0], DateMasks[i][1]);
  }
  var regExp = new RegExp(regExp,"i");
  return String(dateValue).search(regExp)!=-1;
}

function validate_row(rowId, form)
{
  var result = true;
  var isInsert = false;
  if (disableValidation) return true;
  if(typeof(eval(form + "EmptyRows")) == "number")
    if(eval(form + "Elements").length - rowId <= eval(form + "EmptyRows"))
      isInsert = true;
    for (var i = 0; i < eval(form + "Elements")[rowId].length && isInsert; i++)
      isInsert = GetValue(eval(form + "Elements")[rowId][i]) == "";
  if(isInsert) return true;

  if(typeof(eval(form + "DeleteControl")) == "number")
    {
      var control = eval(form + "Elements")[rowId][eval(form + "DeleteControl")];
      if(control.type == "checkbox")
        if(control.checked == true ) return true;
      if(control.type == "hidden")
        if(control.value != "" ) return true;
    }

  for (var i = 0; i < eval(form + "Elements")[rowId].length && (result = validate_control(eval(form + "Elements")[rowId][i])); i++);
  return result;
}

function GetValue(control) {
    if (typeof(control.value) == "string") {
        return control.value;
    }
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
        var j;
        for (j=0; j < control.length; j++) {
            var inner = control[j];
            if (typeof(inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
                return inner.value;
            }
        }
    }
    else {
        return GetValueRecursive(control);
    }
    return "";
}

function GetValueRecursive(control)
{
    if (typeof(control.value) == "string" && (control.type != "radio" || control.status == true)) {
        return control.value;
    }
    var i, val;
    for (i = 0; i<control.children.length; i++) {
        val = GetValueRecursive(control.children[i]);
        if (val != "") return val;
    }
    return "";
}


function validate_form(form)
{
  var result = true;
  if (disableValidation) return true;
  if(typeof(form) == "object" && String(form.tagName).toLowerCase()!="form" && form.form!=null) form = form.form;
  if(typeof(form) == "object" && document.getElementById(form.name + "Elements")) {
    if (typeof(eval(form.name + "Elements")) == "object") 
      for (var j = 0; j < eval(form.name + "Elements").length && result; j++) result = validate_row(j, form.name);
    else 
      for (var i = 0; i < form.elements.length && (result = validate_control(form.elements[i])); i++);
  }else if(typeof(form) == "string" && document.getElementById(form.name + "Elements"))
  {
    if(typeof(eval(form + "Elements")) == "object"){
      for (var j = 0; j < eval(form + "Elements").length && result; j++)
        result = validate_row(j, form);
    }
  }else if (typeof(form) == "object")
          for (var i = 0; i < form.elements.length && (result = validate_control(form.elements[i])); i++);
        else	
          for (var i = 0; i < document.forms[form].elements.length && (result = validate_control(document.forms[form].elements[i])); i++);
  return result;
}

function forms_onload()
{
  var forms = document.forms;
  var i, j, elm, form;
  for(i = 0; i < forms.length; i++)
  {
    form = forms[i];
    if (typeof(form.onLoad) == "function") form.onLoad();
    for (j = 0; j < form.elements.length; j++)
    {
      elm = form.elements[j];
      if (typeof(elm.onLoad) == "function") elm.onLoad();
    }
  }
  return true;
}

//
// If element exist than bind function func to element on event.
// Example: check_and_bind('document.NewRecord1.Delete1','onclick',page_NewRecord1_Delete1_OnClick);
//
function check_and_bind(element,event,func) {
  var htmlElement = eval(element);
  if (htmlElement) {
    if (typeof(htmlElement)=="object" && !htmlElement.tagName && htmlElement.length > 0)
    {
      for (var i=0; i < htmlElement.length; i++)
        eval(element+"["+i+'].'+event+'='+func);
    }else eval(element+'.'+event+'='+func);
  }
}

//End JS Functions

// ritorna un riferimento all'oggetto obj
// @parameter	string	obj		id dell'oggetto
function getObj(obj) {
	return ( document.getElementById ? document.getElementById(obj) : ( document.all ? document.all[obj] : null ) );
}

// ritorna un array contenente tutti gli oggetti con name=obj
// @parameter	string	obj		nome degli oggetti
function getObjN(obj) {
	return ( document.getElementsByName ? document.getElementsByName(obj) : ( document.all ? document.all[obj] : null ) );
}

/* funzione che seleziona tutte le checkbox del form
* mode:
* 		all		seleziona tutti i checkbox
*		none	deseleziona tutti i checkbox
*		inv		inverte la selezione corrente
*/
function sel(theCkbox) {
	var form = theCkbox.form;
	for (i=0; i<form.elements.length; i++) {
		if (form.elements[i].type == "checkbox") {
			if (form.elements[i].name.slice(0,9) == "cb_delete" ) {
				if (form.elements[i].checked)
					form.elements[i].checked = false;
				else
					form.elements[i].checked = true;
			}
		}
    }
	theCkbox.checked = true;
}

/*
 * rowHL function by Xscratch
 * www.sgamevoli.com
 * mailto: xscratch[at]gmail[dot]com
*/
/**
 * Questo array serve per tenere lo storico della classe precedente alla modifica,
 * questo perché solitamente la riga non ha le celle sempre della stessa classe
 */
var rowClassHistory = new Array;

/**
 * Setta/Re-setta la classe di una <tr> di una tabella
 *
 * @param   object    la riga
 * @param   string    l'azione che ha richiamato l'evento
 *            l'azione seive solo per tenere lo storico delle classi della riga:
 *            - se l'azione è over prima di modificare le celle salvo la classe attuale
 *            - se l'azione è out risetto la classe precedente
 * @param   string    la classe da settare
 *
 * @return  boolean  l'esito della funzione
 */
function rowHL(theRow, theAction, theMarkClass)
{
    var theCells = null;
	
    // 1. Controllo che i parametri siano validi
     // altrimenti non richiamo la funzione
    if ((theMarkClass == '') || (typeof(theRow) == 'undefined')) {
        return false;
    }

    // 2. Controllo l'esistenza della riga e se il browser riesce ad ottenere i suoi dati
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
      return false;
    }

    // 3. Salvo le classi attuali e imposto la theMarkClass
    var rowCellsCnt  = theCells.length;
    var currentClass = null;
	if (theAction == 'over') {
		for (c = 0; c < rowCellsCnt; c++) {
			rowClassHistory[c] = theCells[c].className;
			theCells[c].className = theMarkClass;
		} // end for
	}else if (theAction == 'out') {
		for (c = 0; c < rowCellsCnt; c++) {
			theCells[c].className = rowClassHistory[c];
		} // end for
	}else{
		return false;
	}
	return true;
}

/**
 * data una checkbox seleziona quella e deseleziona le altre all'interno del form
 */
function selectOne(checkBox) {
	try {
		theForm = checkBox.form;
		for (i=0; i<theForm.elements.length; i++) {
			if (theForm.elements[i].name != checkBox.name)
				theForm.elements[i].checked = false;
			else
				theForm.elements[i].checked = true;
		}
	} catch (e) {}
}

function apriEditor_old(campo)
{
		var editor=null;
		editor = new HTMLArea(campo);
    	editor.registerPlugin(TableOperations);
    	editor.registerPlugin(ImageManager);
		editor.registerPlugin(InsertFile);
	  // register the CSS plugin
	  editor.registerPlugin(CSS, {
		combos : [
		  { label: "Syntax:",
					   // menu text       // CSS class
			options: { "None"           : "",
					   "Code" : "code",
					   "String" : "string",
					   "Comment" : "comment",
					   "Variable name" : "variable-name",
					   "Type" : "type",
					   "Reference" : "reference",
					   "Preprocessor" : "preprocessor",
					   "Keyword" : "keyword",
					   "Function name" : "function-name",
					   "Html tag" : "html-tag",
					   "Html italic" : "html-helper-italic",
					   "Warning" : "warning",
					   "Html bold" : "html-helper-bold"
					 },
			context: "pre"
		  },
		  { label: "Info:",
			options: { "None"           : "",
					   "Quote"          : "quote",
					   "Highlight"      : "highlight",
					   "Deprecated"     : "deprecated"
					 }
		  }
		]
	  });
		// load the stylesheet used by our CSS plugin configuration
		editor.config.pageStyle = "@import url('/doimodesign/doimoStile.css');";
		editor.generate();

}

function openWindow(pagina,nome,w,h,scroll)
{
  var param = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=" + scroll +",resizable=yes,width=" + w + ",height=" + h;
  msg = self.window.open(pagina,nome,param);
  if (msg.opener == null) msg.opener = self;
}

function zoomImage(image_id) {
	if (image_id != "") {
		openWindow("../zoom_immagine.php?id_foto="+image_id, "Zoom", 780, 650);
	}
}

// funzione che mostra o nasconde un oggetto
// (Hide Or Show menu)
function HoS_obj(obj, transition)
{
	transition = (transition == false) ? false : true;
	try {
		var x = getObj(obj);
		if( x && x.style) {
/*			if (typeof fx != 'undefined' && transition) {
				var myEffect = new fx.Height(x.id, {duration: 100});
				myEffect.toggle();
			} else {*/
				if (x.style.display!='none') {
					x.style.display = 'none';
				} else {
					x.style.display = 'block';
				}
			//}
		}
	} catch (e) {
		alert(e);
	}
}

/*
* Function that replace a normal textare field with
* a FCK WYSIWYG editor 
* @param fieldId	id of the element to replace
*/
function apriEditor(fieldId)
{
	var project_path = "/";
	var editor_path = project_path + "includes/js/fckeditor/";
	var img_path = project_path + "media/Image/";
	var links_path = project_path + "media/File/";
	var flash_path = project_path + "media/Flash/";
	var myStylesheet = project_path + "editor_style.css.php";
	try {
		var editor = new FCKeditor(fieldId);	// Instantiate an editor with
												// the name of the TEXTAREA input.
		editor.BasePath = editor_path;	// This may need to change depending on the name
										// of the folder you have FCKeditor in.
		editor.Width = "580";
		editor.Height = "500";	// NOTE: do not put px, just leave the numbers as is

		editor.CheckBrowser = true ;
		
		editor.Config.AutoDetectLanguage = false ;
		editor.Config[ "DefaultLanguage" ] = "it" ;
		editor.Config['ImageBrowserURL'] = editor.BasePath + 'editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&Type=Image&ServerPath=' + img_path;
		editor.Config['LinkBrowserURL'] = editor.BasePath + 'editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&ServerPath=' + links_path;
		editor.Config['FlashBrowserURL'] = editor.BasePath + 'editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&Type=Flash&ServerPath=' + flash_path;
		
		editor.ToolbarSet = 'Styled'; // Toolbar with the style combo-box selector
		editor.Config['EditorAreaCSS'] = myStylesheet;

		// This line must come in last once all the configs have been made.
		editor.ReplaceTextarea() ;
	} catch (e) {
		alert(e);
	}
}