var isNS4=document.layers?true:false;
var isIE=document.all?true:false;
var isNS6=!isIE&&document.getElementById?true:false;
var isDOM = (document.getElementById) ? true : false;

function isNumeric(x) {
   var RegExp = /^(-)?(\d*)(\.?)(\d*)$/; // Note: this WILL allow a number that ends in a decimal: -452.
   // compare the argument to the RegEx
   // the 'match' function returns 0 if the value didn't match
   var result = x.match(RegExp);
   return result;
}

function oggi(element){
    var mD = new Date();
    var el=document.getElementById(element);
    //el.value=mD.getFullYear() + "-" + (mD.getMonth()+1) + "-" + mD.getDate();
	el.value=mD.getDate() + "/" + (mD.getMonth()+1) + "/" + mD.getFullYear();
}

function doPassVar(pag){
    HM_DOM = (document.getElementById) ? true : false;
    HM_NS4 = (document.layers) ? true : false;
    HM_IE = (document.all) ? true : false;

	
    
	if (HM_IE){   //IE
		//alert('IE');
		var mF = document.getElementById("myFlash");
		mF.SetVariable("menu", pag);        
    }else{
        if (HM_DOM){
			var mF = document.getElementById("myFlash");
			mF.SetVariable("menu", pag);
            alert('DOM');
        }else{  //Netscape
			alert('NS');
            var mF=document.myFlash;
			mF.SetVariable("menu", pag);
			alert('NS');
        }
    }	
}

function delCheck(){
	if(window.confirm("You're delete this record. Are you sure?"))
		return true;
	else
		return false;
}

function isblank(s){
	for (var i=0; i < s.length; i++){
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\t')) return false;
	}
	return true;
}

function checkDelSelected(){
	//usata onSubmit per delSelected....
	if(window.confirm("Deleting selected records. Are you sure?"))
		return true;
	else
		return false;
}

function delRows(scheda){
// 	var mF=document.getElementById("scheda");
// 	alert(document.forms['scheda'].elements.length)
	
	
	if(window.confirm("Stai cancellando le righe selezionate. Sei sicuto?"))
		doAction(scheda);
		
		
}

function delcheck(){
	if(window.confirm("Deleting selected record. Are you sure?"))
		return true;
	else
		return false;
}

function checkDirExists() {
	if($F('f_Descrizione').length<1){
			return false;			
	}
	for (var i = 0; i < dirList.length; i++) {
		if( $F('f_Descrizione') == dirList[i]){
			$('addFolder_msg').innerHTML='Attenzione! La cartella esiste gia\'';
			return false;			
		}
   }
	doAction('schedaFolder');
}

function checkFileExists(o) {
	//alert(o.value);
	for (var i = 0; i < fileList.length; i++) {
		if(o.value == fileList[i]){
			return true;			
		}
   }
	return false;
}

function checkMail(src) {
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	return regex.test(src);
}

function aggiorna(){
	location.reload(true);
}

function vaia(url){
    if (isIE){
		document.URL=url;
	}else{
		window.location=url;
	}
}

function vaiaSelected(sel){
	// come vaia, ma con la gestione di selectedItem
	var mS = document.getElementById(sel);
	url=mS.selectedIndex;
	url=mS.options[url].value;
	//alert(url);
	vaia(url);
}

function focusOn(id){
	var mF=document.getElementById(id);
	mF.focus();
}

function over(obj,bgcolor){
	obj.style.backgroundColor=bgcolor;
}

function login(f) {
	//attenzione, lunghezza PSW 
	if( f['psw'].value.length > 4){
		f['psw'].value = f['id'].value + hex_md5(f['psw'].value);
		return true;
	}else{
		alert('Password lunga solo '+f['psw'].value.length + ' caratteri!')
	}
	return false;
}

function login_old(f) {
	//attenzione, lunghezza PSW 
	if( f['psw'].value.length > 4){
		f['psw'].value = f['id'].value + hex_md5(f['psw'].value);
// 		alert(f['psw'].value)
		doAction(f);
		return false;
	}else{
		alert('Password lunga solo '+f['psw'].value.length)
	}
	return false;
}

function editPsw(f) {
	if(f['new'].value==f['retype'].value){
		f['old'].value = f['id'].value + hex_md5(f['old'].value);
		f['new'].value = f['id'].value + hex_md5(f['new'].value);
		return true;
	}else{
		alert('RE-TYPE non corrisponde a NEW! Verifica la correttezza del dato');
		return false;
	}
}

function MM_findObj(n, d) { //v4.0
	var p,i,x;  
	if(!d) d=document;
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; 
		n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) 
		x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++) 
		x=d.forms[i][n];
  	for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
		x=MM_findObj(n,d.layers[i].document);
	if(!x && document.getElementById) 
		x=document.getElementById(n);
	return x;
}

//gestione blocchi --------------------------------------------
var hasCookies = false;

// tests whether the user accepts cookies, and sets a flag.
if(document.cookie == '') {
	document.cookie = 'hasCookies=yes';
	if (document.cookie.indexOf('hasCookies=yes') != -1) hasCookies = true;
}
else hasCookies = true;

function blockState(divID) {
	var theCookie = readCookie(divID);
	var state="e";
	if ((theCookie == "e") || (theCookie == "")) {
		state="c";
	}
	setCookie(divID,state,'Wed 01 Jan 2020 00:00:00 GMT','/');
	return state;
}

// reads a cookie from the browser
function readCookie(name) {
	if (document.cookie == '') return '';
	else {
		var firstChar, lastChar;
		var theBigCookie = document.cookie;
		firstChar = theBigCookie.indexOf(name);
		if (firstChar != -1) {
			firstChar += name.length + 1;
			lastChar = theBigCookie.indexOf(';', firstChar);
			if (lastChar == -1) lastChar = theBigCookie.length;
			return unescape(theBigCookie.substring(firstChar, lastChar));
		}
	else return '';
	}
}

// sets a cookie in the browser.
function setCookie (name, value, hours, path) {
	if (hasCookies) {
	if(hours) {
		if ( (typeof(hours) == 'string') && Date.parse(hours) ) var numHours = hours;
		else if (typeof(hours) == 'number') var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
	}
	document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'');
	}
}

if (!isIE) document.captureEvents(Event.MOUSEMOVE)
function getMouseXY(e) {
  if (isIE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
	return tempY;
}

function showLayer(divID){
	var divIDobj = MM_findObj(divID);
	divIDobj.style.visibility = "visible"
}

function hideBlock(divID){
		
	var divIDobj = MM_findObj(divID);
	var toggleobj = MM_findObj(divID +"Toggle");
// alert(refer.offsetY);
// alert(getMouseXY());

	if(divIDobj.style.display == "none"){
		toggleobj.src = "gui/images/arClose.gif";
		divIDobj.style.display = "block";
		setCookie(divID,'e','Wed 01 Jan 2020 00:00:00 GMT','/');
	}else{
		toggleobj.src = "gui/images/arOpen.gif";
		divIDobj.style.display = "none";
		setCookie(divID,'c','Wed 01 Jan 2020 00:00:00 GMT','/');
	}
}

function hideBlock2(divID){

	var divIDobj = MM_findObj(divID);
//    alert(divIDobj.nodeName  )
	if(divIDobj.style.display == "none"){
		divIDobj.style.display = "block";
	}else{
		divIDobj.style.display = "none";
	}
}

function hideSub(divID){
	var divIDobj = MM_findObj(divID);
	var toggleobj = MM_findObj(divID +"Toggle");

	if(divIDobj.style.display == "none"){
		toggleobj.src = "images/subOpen.gif";
		divIDobj.style.display = "block";
	}else{
		toggleobj.src = "images/subClosed.gif";
		divIDobj.style.display = "none";
	}
}

//FINE gestione blocchi --------------------------------------------

function help(){

}

//gestione menu--------------------------------------------
function showMenu(menu){
	var mM=isDOM?document.getElementById(menu).style: isNS4 ? document.layers[menu]: document.all[menu].style;

	//alert(mM.visibility);

	if (mM.visibility == "hidden")
		mM.visibility =  "visible";
	else
		mM.visibility =  "hidden";


}

function closeMenu(menu){
	var mM=isDOM?document.getElementById(menu).style: isNS4 ? document.layers[menu]: document.all[menu].style;
	mM.visibility =  "hidden";
}
//FINE gestione menu--------------------------------------------

function overCal(id){
	alert(id);
}

function checkForm(f){
	var error="";
	
	for(var i=0; i< f.length; i++){
		var e=f.elements[i];
		
		if (e.name=="f_RiskID")
			if ( (e.value==null ) || (e.value<1) ) error +=" - Risk ID not present\n";
		if (e.name=="f_RiskDesc")
			if ( (e.value==null ) || (e.value=='') ) error +=" - Risk Description not present\n";
		if (e.name=="f_RiskOwner")
			if ( (e.value==null ) || (e.value=='') ) error +=" - Risk Owner not present\n";
		if (e.name=="f_Probability")
			if ( (e.value==null ) || (e.value=='') ) error +=" - Probability not present\n";
		if (e.name=="f_Impact")
			if ( (e.value==null ) || (e.value=='') ) error +=" - Impact not present\n";
		if (e.name=="f_MaxAmount"){
			if ( (e.value==null ) || (e.value=='') || (e.value<=0) ) error +=" - Max Amount can't be zero\n";
			max=e.value*1;
// 			alert(max*2);
		}
		
		if (e.name=="f_MinAmount"){
// 			alert(max + '<' + e.value);
			if (max < e.value) error +=" - Min Amount must be minor then Max Amount'\n";
			if ( (e.value==null ) || (e.value=='') || (e.value<=0) ) error +=" - Min Amount can't be zero\n";
		}
		
		if (e.name=="f_ActionPlan")
			if ( (e.value==null ) || (e.value=='') ) error +=" - Action Plan not present\n";
		if (e.name=="f_ActionOwner")
			if ( (e.value==null ) || (e.value=='') ) error +=" - Action Owner not present\n";
		if (e.name=="f_Rec3parties" && e.checked){
			var est = MM_findObj("f_EstimatedAmount");
// 			alert(e.value)
			if ( (e.value=='y') && est.value<=0) error +=" - Estimated amount recoverable from third parties not present\n";
		}
		

	}

	if (error!=''){
// 		alert (error!='' && head!='');
		var s="Form uncorrect due the following errors:\n";
		s +=error;
		s +="\nPlease Correct errors";
		alert(s);
		return false;
	}else{
		return true;
	}
}

function checkNumber(f,e){
	var code = (window.Event) ? e.which : e.keyCode;
	var myD = MM_findObj("f_MaxAmount2");
	

	n=f.value;
	if(  (code<47 || code>58) && (code<36 || code>41) &&  (code<15 || code>21) &&  (code<32 || code>36) && code!=0 && code!=13 && code!=8 && code!=45 && code!=27 && code!=46 &&  (code<111 || code>124)){
		
		if (code==190){
			punto=n.lastIndexOf(".") - n.indexOf(".");
			if(punto>0)
				n=n.substr(0,n.length-1)
		}else if (code==188){	
			punto=n.indexOf(".");
// 			alert(", p:"+punto)
			if(punto>0)
				n=n.substr(0,n.length-1)
			else
				n=n.replace(/,/,".");
// 		}else if (  (code>=37 || code<=40) || code==13 || code==8 || code==46        ){
			// 37-40 frecce
			// 13 invio
			// 8 del
			// 46 canc
		}else{
			n=n.substr(0,n.length-1)
// 			myD.value+="-"+code;
		}
		
	}
	f.value=n;
}

function _isDate(d){
   var date_regex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

// ^ indicates start of expression
// \d{1,2} - the \d means digits and {1,2} means 1 or 2 digits
// $ indicates end f expression

   if (!date_regex.test(d)){
      alert(d + " is NOT a valid date");
      return(false);
   }
   return(true);
}

function CheckDate(f){

   if(f.value=='')
      return;
   
   if (!/^\d{2}\/\d{2}\/\d{4}$/.test(f.value)) {
      alert("La date deve essere nel formato dd/mm/yyyy");
      return false;
   }
   
   //d=parseInt(f.value.substr(0,2));
   //m=parseInt(f.value.substr(3,2));
   //y=parseInt(f.value.substr(6,4));
   
   d=f.value.substr(0,2);
   m=f.value.substr(3,2);
   y=f.value.substr(6,4);
      
   //alert(f.value.substr(0,2))
   //alert(d + ' ' + m + ' ' + y)
   
   if (m<1 || m>12){
      alert("Il mese deve essere compreso tra 01 e 12!");
      return(false);
   } 
   if (d<1 || d>31){
      alert("Il giorno deve essere compreso tra 01 e 31!");
      return(false);
   } 

   if (y<1900 || y>2050){
      alert("Se sicuro dell'anno?!");
   }    
   
   if (m==4 || m==6 || m==9 || m==11)
      if (d==31){
         alert("La data non � corretta. Controlla il giorno del mese!");
         return(false);
      } 
         
   if (m==2){
      var b=parseInt(y/4);
      if (isNaN(b)){
         alert("La data non � corretta. Controlla l'anno!");
         return(false);
      }
      if (d>29){
         alert("La data non � corretta. Controlla i giorni del mese!");
         return(false);
      } 
      if (d==29 && ((y/4)!=parseInt(y/4))){
         alert("La data non � corretta. Controlla i giorni del mese!");
         return(false);
      } 
   }
   
   if(f.id='f_dataNascita')
      calcola_eta(f.value); 
   
}
//###############################################################################

function calcola_eta(nascita){
   
   var d=nascita.split('/');
   var oggi = new Date();
   var anni=oggi.getFullYear() - d[2]-1;
   //alert(anni);
   if ( (oggi.getMonth()+1 - d[1])>0 )
      anni++;
   else if ( (oggi.getMonth()+1 - d[1])==0 ){
      if( oggi.getDate()>=d[0] )
         anni++;
   }
   if( $('f_dataNascita2') )
      $('f_dataNascita2').value=anni;
}

function cercaNome(f){
   if(f.value!=''){
      loadHTML('cercaNome&nome='+f.value,'tipsBox');
   }
}

function proponiCodice(){
   loadHTML('proponiCodice','tipsBox');
}

function cercaCodice(f){
   if(!isNumeric(f.value)){
      alert('Il valore non pu� essere alfanumerico..');
      return;
   }
   if(f.value!=''){
      alert('x')
      loadData('cercaCodice&cod='+f.value,'msgBox');
   }
}

function hideMsgBox(){
   $('msgBox').style.visibility='hidden';
}


/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
 
//################ esplicita posAziendali ##############################
function esplicita_posAziendali(pos,t){
	var pars = 'cmd=resolvePos&pos='+pos+'&t='+t;
	
	var myAjax = new Ajax.Updater(
		'posAzienda2', 
		'main.php', 
		{
			method: 'post', 
			parameters: pars
		});
}

function esplicita_setMerceologico(sm,t){
	var pars = 'cmd=resolveSetMerc&sm='+sm+'&t='+t;
	
	var myAjax = new Ajax.Updater(
		'setMerceologico2', 
		'main.php', 
		{
			method: 'post', 
			parameters: pars
		});
}

function updateRicerca(pars){
   // maschera in trasparenza in loading
   if( $('maschera_loading') ){
      $('maschera_loading').style.visibility='visible';
   }else{
      var container=$('scheda2');
      //alert( 'w:'+$('scheda2').clientWidth )
   	var div1=document.createElement('DIV');
   	div1.id='maschera_loading';
   	
      div1.style.cssText = 'z-index:110;position:absolute;top:0;left:0;height:1200px;width:' + container.offsetWidth + 'px;background-color:#fff;filter:alpha(opacity=90);-moz-opacity:0.90;';   
      div1.innerHTML='<img style="padding-left:40%;padding-top:60px;" src="gui/images/loading2.gif"/>';
      container.appendChild(div1);
   }
   // #########################################
   
   //alert(pars)
   //return;
   //alert(container.id)
	var url = 'main.php';
	
	
   var myAjax = new Ajax.Request(
		url, 
		{
			method: 'get', 
			parameters: pars, 
			onComplete: aggiornaSchedaRicerca
		}
   );
}



//######################################################################

function img_over(img) { 
	if( typeof img  == 'object' )
		img=img;
	else
		img=MM_findObj(img);

	if(img==null) return;
	
	src=img.src;
	est=src.substring(src.length-4);
	src=src.substring(0,(src.length-4)) + '_o'+est;
	
	img.src=src;
}
function img_out(img) { 
	if( typeof img  == 'object' )
		img=img;
	else
		img=MM_findObj(img);
		
	if(img==null) return;
	
	src=img.src;
	est=src.substring(src.length-4);
	src=src.substring(0,(src.length-6)) + est;
// 	alert(src)
	img.src=src;
}

function ridimensionamento(quando){
   /*
      quando=1 dopo un loadHTML
      quando=2 dopo un resize
   */
   
   var h=document.documentElement.clientHeight;
   //alert(quando)
   
   $('msgWindow').style.cssText='height:'+h+'px;';
     
   if(isIE){
      $('mainContent').style.height=( h - 155)+'px';
   
      if( $('explorerContainer') ){
         $('explorerContainer').style.height=(h - 170)+'px';
      
         if( $('explorerTreeContent') ) 
            $('explorerTreeContent').style.height=(h - 198)+'px';
            
         if( $('explorerFiles') )  
            $('explorerFiles').style.height=(h - 204)+'px';
            
         if( $('eventList') )
            $('eventList').style.height=(h - 206)+'px'; 
             
         if( $('ricercaSx') )   
            $('ricercaSx').style.height=(h - 206)+'px';                            
      }            
   }else if(!isIE) {
      
      $('mainContent').style.height=( h - 155)+'px';
      
      if( $('explorerContainer') )
         $('explorerContainer').style.height=(h - 154)+'px';
         
      if( $('explorerTreeContent') )   
         $('explorerTreeContent').style.height=(h - 206)+'px';
         
      if( $('explorerFiles') )   
         $('explorerFiles').style.height=(h - 202)+'px';
      
      if( $('eventList') )
         $('eventList').style.height=(h - 206)+'px';
         
      if( $('ricercaSx') )   
         $('ricercaSx').style.height=(h - 180)+'px';                
   }
   
   if( $('logs') ){
      
      $('logs').style.height=(h - 189)+'px';
      
   }
      

         
      
         
}


function leaveMe(){
	var pars='cmd=updateSession';
	new Ajax.Request(
		'main.php', 
		{
			method: 'post', 
			parameters: pars, 
			onSuccess: function(resp){
				if(resp.responseText!='ok')
					alert('update complete: ' + resp.responseText);
			},
			onFailure: function(resp){
				alert('update error: ' + resp.responseText);
			}
		});
	return true;
}
