/**
 * @author corey
 */
$(function(){
// Spostamento bottoni for in fondo
  $("#form-buttons").appendTo($("#anag-form"));
  menu_start();
  general_start($('body'));
// pagina utente
  user_start();
// pagina visualizzazione servizi: modUserServ
  modUserServ_start();
// pagina associazione utente servizio: assocServ.php
  assocServ_start();
// pagina associazione referenti, riferimenti etc	
  assocRef_start();
// pagina visualizza le associazioni ad att speciali: modAttSpe.php
  modAttSpe_start();
// pagina associazione utenteServizio ad attività Speciale: AttSpe.php
  assocAttSpe_start();
// pagina ricerca ente
  searchEnte_start()
// pagina inserimento ente
  saveEnte_start();
// pagina che setta le presenze presunte
  reg_pre_start();
// esportazione generica
  report_gen_start();
//esportazione amministrativa
  report_amm_start();
// inserimento servizio
  servizio_start();
// pager
   pager_clicks();
// numeric
reportTable();
// odd even class
  odd_even_heading_report();
  
  search_start();
// warning
  theme_warnings();
//aggiunta onmouseover onmouseout alle immagini	
  add_img_effects("img.mover");
// link alla ricerca e ai risultati per modifica anagrafica	
  back_bt_start();
// aggiunge il bottone per il controllo del CF nell'inserimento utente 
  ctrl_cf_bt_start();
// aggiunge l'onclick al bottone per l'invio della mail con i dati dell'utente da associare al servizio
  ctrl_cf_assServ_start();
// popola le date, dopo aver scelto il servizio, nella compilazione del registro presenze
  regPresenza_start();
// Funzione che permette di associare l'ente dalla schermata referente abilita il bottone cerca e l'apertura del popup con i risultati
  enteFromRef_start();
});

function menu_start(){
  $("#menulev:not(.processed)").each(function(){
      var formObj = $(this).parents('form');
      $("li[id]", this).each(function(){
        var id = get_elementId(this);
        $(this).click(function(){
          selLev(formObj, id);
        });
      });
    $("#menulogout", this).click(function(){
      window.location.href = "admframe.php?kc=1";
    });
    $(this).addClass('processed');
  });
}

/**
 * Bottoni di ritorno alla ricerca
 */
function back_bt_start(){
  $("#ctrl-buttons").each(function(){
    if ($(this).hasClass('ente-ctrl')) {
      var link = 'hr/cercaEnte.php';
    }
    else {
      var link = 'hr/searchUser.php';
    }
    $("#link-result", this).attr('href', '#').click(function(){
      $("input[name=flagSearch]").val(1);
      $("input[name=link]").val(link);
      $(this).parents("form").submit();
    });
    $("#link-search", this).attr('href', '#').click(function(){
			$("input[name=toSearch_X]").remove();
      $("input[name=flagSearch]").val(0);
      $("input[name=link]").val(link);
      $(this).parents("form").submit();
    });
  });
}

/**
 * Pulsanti di ricerca
 */
function search_start(){
	$('#search-result:not(.processed)').each(function(){
    $('> div', this).each(function(){
      var container = this;
      var id = get_elementId(this);
      $('img.bt-usermod', this).each(function(){
				title = 'Modifica utente ' + id + ' - ' + $('.name', container).text();;
        $(this).attr('alt', title).attr('title', title);
        $(this).click(function(){
          mod_user('user', id);
          
        });
      });
      $('img.bt-userview', this).each(function(){
        title = 'Visualizza utente ' + id + ' - ' + $('.name', container).text();;
        $(this).attr('alt', title).attr('title', title);
        $(this).click(function(){
          view_user('user', id);
          
        });
      });
      $('img.bt-entemod', this).each(function(){
				title = 'Modifica ente ' + id + ' - ' + $('.name', container).text();;
        $(this).attr('alt', title).attr('title', title);
        $(this).click(function(){
          mod_ente(id);
          
        });
      });      
    });
    $(this).addClass('processed');
  });
}

/**
 * Modificatori sulle form
 * @param {Object} parent_el
 */
function general_start(parent_el){
	// campi richiesti
  var i = 0;
  $(".item:not(fieldset):not(.processed)", parent_el).each(function() {
    if ($(this).hasClass('required')) {
      $("label", this).html($("label", this).html() + "*");
      $("input", this).each(function() {
        $(this).attr("id", "req" + i);
        i = i + 1;
      });
    }
    $(this).addClass('processed');
  });
	// campi data
	$(".datepicker:not(.hasDatepicker)", parent_el).each(function(){
		$(this).datepicker( {
	    dateFormat : 'dd-mm-yy',
	    appendText : '(dd-mm-yyyy)',
	    showOn : 'button',
	    buttonImage : 'images/cal2.gif',
	    buttonImageOnly : true
	  });
		$('img', $(this).parents('div.item')).click(function(){
	    var zindex = 1;
	    $(".ui-dialog").each(function(){
	      if ($(this).css('z-index') > zindex) {
	        zindex = $(this).css('z-index');
	      }
	    });
	    zindex = zindex + 1;
	    $(".ui-datepicker").css('z-index', zindex);
	  });
		$(this).attr('maxlength', 10);
	});
	//aggiunta recapiti
	$("fieldset.contacts-items:not(.processed)").each(function(){
		var container = this;
		$("img.img-recapito", this).unbind('click');
		$("img.img-recapito", this).attr('onclick', '');
		$("img.img-recapito", this).click(function(){
			addRecapiti(container, 4);
		}); 
		$(this).addClass('processed');
	});
	// collassati
	$(".collapsed > legend a", parent_el).click(function() {
		fieldset_collapse(this)
	});
	$(".collapsed > *", parent_el).hide();
	$(".collapsed", parent_el).removeClass('collapsible');
	$(".collapsed > legend", parent_el).show().addClass("collapse-processed");
}

/**
 * Modifica le funzioni per la form di inserimento Anagrafiche
 * @return
 */
function user_start() {
	$("input[name=username]:not(.processed)").each(function(){
			//disable username mod
		if ($(this).val() != "") {
			$(this).attr("disabled", "disabled");
		}
		$(this).after('<a class="username_bt">Verifica</a>');
		$(this).addClass('processed');
	});
  $("#re-reg-mail").each(function(){
    var error = true;
    $(this).click(function(){
      error = resend_regmail();
    });
    if (error === false) {
      $(this).remove();    
    }
  });
  $("#decfield").each(function(){
    var container = this;
    $("input.form-radio", this).each(function(){
      $(this).change(function(){
        decreto_field(container)
      });
    });
    decreto_field(container);
  });
  function decreto_field(container) {
    if ($("input:checked", container).attr('id') == "edit-dec-0") {
      $(".decretotipo", container).attr('disabled', 'disabled');
      return;
    }
    $(".decretotipo", container).removeAttr('disabled');
  }
}


/**
 * Setta i bottoni sulla pagina di visualizzazione dei servizi associati
 * all'utente
 * @return
 */
function modUserServ_start(){
	$("#us-view:not(.processed)").each(function(){
		var idUser = get_idUser(this);	//id utente	
		$("img.img-add-usrserv", this).click(function(){
			mod_userserv('new', 0, idUser);
		});
		$(".user-serv div.item").each(function(){
			var id  = get_elementId(this);
			$("img.img-mod-usrserv", this).click(function(){
				mod_userserv('mod', id, idUser);
			});
		});		
		$(this).addClass('processed');
	});
}

/**
 * Setta i bottoni sulla pagina di associazione dei servizi
 * all'utente
 * @return
 */
function assocServ_start(){
	$("#userserv-assoc:not(.processed)").each(function(){
		var form_obj = $(this).parents("form");
		var idUser = get_idUser(this);	//id utente
			//salvataggio associazione utente servizio
		$("img.img-asserv", this).click(function(){
			var url='hr/assocServ.php';
			var errors = new Array();
			errors = ctrl_req(form_obj);
			if ($(errors).length == 0) {
				if ($(this).hasClass("new")) {
					$("input[name=newFromMod]", form_obj).val(1)
				}
				$("input[name=flag]", form_obj).val(1)
				// inserimento nella form degli id degli utenti facenti parte del gruppo
				$("#userserv-assoc #servUsrGrp > div.item-user").each(function(){
					$(document.createElement('input')).attr('type', 'hidden').attr('name', 'utenteGroup[]').val(get_elementId(this)).appendTo(form_obj);
				});
				$("input#linkURL", form_obj).val(url);
				$(form_obj).submit();
			}
		});
		//rimozione utenti del gruppo
		add_usrGrp_remove_bt(this);
		//bottone ricerca utente da inserire in gruppo
		$("img.img-asgroupsearch", this).click(function(){
			var parent = $(this).parents('fieldset')
      var type = 5;
      var str = $("input[name=toSearch]", parent).val();
      var list_container = $(".user-list", parent);
      src_user_assoc(str, type, list_container, 0);
		});
		$(this).addClass('processed');
	});
	var idUsrServAss = $("input[name=idUsrServAss]").val();
}

/**
 * Setta le funzioni da chiamare per la pagina di associazione riferimenti
 * @return
 */
function assocRef_start() {
	var url = 'hr/addReferente.php';
	$("#ass_servizio_ref_form:not(.processed)").each(function(){
		add_usrGrp_remove_bt(this);
		var form_obj = $(this).parents("form");
		var grandContainer = this;
		$(".img-asrefsearch", this).each(function(){
			var parent = $(this).parents('fieldset')
			var type = get_elementId(parent);
			$(this).click(function(){
				var str = $("input[name=toSearch]", parent).val();
				var list_container = $(".user-list", parent);
				src_user_assoc(str, type, list_container, 0);
			});
		});
		$(".img-asservref", this).click(function(){
			$("input[name='ref_save']", form_obj).remove();
			$("fieldset", grandContainer).each(function(){
				var type = get_elementId(this);
				$("input[name='assRef" + type + "[]']", form_obj).remove();
				$(".user-list > div.item-user", this).each(function(){
					var idref = get_elementId(this);
					if (type == 1) {
						var perc = $("input[name*=perc]", this).val()
						if (perc > 0 && perc <= 100) {
							idref = idref + ':' + $("input[name*=perc]", this).val()
						}
					}
					$(document.createElement('input')).attr('type', 'hidden').attr('name', 'assRef' + type + '[]').val(idref).appendTo(form_obj);
				});
			});
			$(document.createElement('input')).attr('type', 'hidden').attr('name', 'ref_save').val(1).appendTo(form_obj);
			$("input#linkURL", form_obj).val(url);
			$(form_obj).submit();
		});
		$(this).addClass('processed');
	});
}

/**
 * Setta i bottoni sulla pagina di visualizzazione delle attività associate
 * all'utente
 * @return
 */
function modAttSpe_start(){
  $("#servattspe-view:not(.processed)").each(function(){
	var idUser = get_idUser(this);	//id utente
	var idUserServAssoc = get_elementId($("> div.user-serv-att", this));
    var form_obj = $(this).parents("form");
    $("img.img-add-servattspe", this).click(function(){
    	mod_userservatt('new', 0, idUserServAssoc, idUser);
    });
    $(".user-serv-att div.item").each(function(){
    	var id  = get_elementId(this);
    	$("img.img-mod-servattspe", this).click(function(){
    		mod_userservatt('mod', id, idUserServAssoc, idUser);
    	});
    });   
    $(this).addClass('processed');
  });
}

/**
 * Modificatore della form per inserimento in popup
 * @param {Object} popup
 */
function ins_popup_start(popup){
	popup_title(popup);
	general_start(popup);
	$("img.img-salva", popup).each(function(){
		$(this).unbind('click');
	  $(this).attr('onclick','');
		$(this).click(function(){
			$(".datepicker.hasDatepicker", popup).datepicker('destroy');
			var clone_popup = $("> div", popup);
			var form_obj = $(document.createElement('form'))
			$(clone_popup).appendTo(form_obj);
      var type = get_elementId($("div.ins-popup", form_obj));
      var url='ajax/ajax.php';
      var errors = new Array();
      errors = ctrl_req(form_obj);
			if ($(errors).length == 0) {
				$(document.createElement('input')).attr('type', 'hidden').attr('name', 'type').val(type).appendTo(form_obj);
				saveUser(form_obj, 'inspopup');
      }
      else {
				/*
				$("div.ins-popup", popup).remove();
				$("div.ins-popup", clone_popup).appendTo(popup);
				*/
				$(clone_popup).appendTo(popup);
				$(form_obj).remove();
        var alert_msg = '';
		    $(errors).each(function(){
		      alert_msg = alert_msg + this + "\r\n";
		    });
		    alert (alert_msg);
				ins_popup_start(popup);
		  }
		});
	});
}

/**
 * Setta il bottone di inserimento sulla pagina di associazione delle attività speciali
 * all'utente-servizio
 * @return
 */
function assocAttSpe_start(){
   var url = 'hr/AttSpe.php';
  $("#servattspe-assoc:not(.processed)").each(function(){
    add_usrGrp_remove_bt(this);
    form_obj = $(this).parents("form");
    grandContainer = this;
    $(".img-asrefsearch", this).each(function(){
      var parent = $(this).parents('fieldset')
      var type = get_elementId(parent);
      $(this).click(function(){
        var str = $("input[name=toSearch]", parent).val();
        var list_container = $(".user-list", parent);
        src_user_assoc(str, type, list_container, 0);
      });
    });
    $(".img-asserv", this).click(function(){
      $("input[name='atspe_save']", form_obj).remove();
			var errors = new Array();
      errors = ctrl_req(form_obj);
			if ($(errors).length == 0) {
		  	$("fieldset", grandContainer).each(function(){
		  		var type = get_elementId(this);
		  		$("input[name='assRef" + type + "[]']", form_obj).remove();
		  		$(".user-list > div.item-user", this).each(function(){
		  			var idref = get_elementId(this);
		  			$(document.createElement('input')).attr('type', 'hidden').attr('name', 'assRef' + type + '[]').val(idref).appendTo(form_obj);
		  		});
		  	});
		  	$(document.createElement('input')).attr('type', 'hidden').attr('name', 'atspe_save').val(1).appendTo(form_obj);
		  	$("input#linkURL", form_obj).val(url);
		  	$(form_obj).submit();
		  }
			else {
        var alert_msg = '';
			  $(errors).each(function(){
			    alert_msg = alert_msg + this + "\r\n";
        });
        alert (alert_msg);
      } 
    });
    $(this).addClass('processed');
	});
}

/**
 * Setta il bottone di inserimento sulla pagina di associazione delle attività speciali
 * all'utente-servizio
 * @return
 */

function saveEnte_start(){
  var url = 'hr/addEnte.php';
  $("#ente-insert:not(.processed)").each(function(){
		grandContainer = this;
		add_usrGrp_remove_bt(this);
		form_obj = $(this).parents("form");
    $("img.img-asrefsearch", this).each(function(){
      var parent = $(this).parents('fieldset')
      var type = get_elementId(parent);
      $(this).click(function(){
        var str = $("input[name=toSearch]", parent).val();
        var list_container = $(".user-list", parent);
        src_user_assoc(str, type, list_container, 0);
      });
    });
		$("img.img-salva", this).each(function(){
		  $(this).click(function(){
				saveEnte(grandContainer);
			});
		});
    $(this).addClass('processed');
  });
}

/**
 * Ricerca Ente
 */
function searchEnte_start(){
	$("#src-ente:not(.processed)").each(function(){
		form_obj = $(this).parents("form");
	  $("img.img-searchente").click(function(){
			$("input#linkURL").val('hr/cercaEnte.php');
			$(document.createElement('input')).attr('type', 'hidden').attr('name', 'flagSearch').val(1).appendTo(form_obj);
			$(form_obj).submit();
		});
		
		$("#search-result .cf,.data").remove();
		$(this).addClass('processed');
	})
}

/**
 * Setta la checkbox per ogni utente ??????????
 * @return
 */
function reg_pre_start(){
	var url = 'compReg.php';
	$("#compilazione-registro:not(.processed)").each(function(){
		var date = $('#dati-servizio input[name=dateServ]', this).val(); 
		$(".form.presenza-item > fieldset", this).each(function(){
			var thisFieldset = this;
			$(":checkbox", this).change(function(){
				var idUserServ = get_elementId(thisFieldset);
				var idPresenza = get_elementId(this);
				regPre(date, idUserServ, idPresenza);
			});
			if ($(":checkbox:checked", this).length == 1) {
				addPresenza_bt(this, date);
				$(":checkbox:checked", this).attr('disabled', 'disabled');
			}
		});
		$(this).addClass('processed')
	});
}


function report_gen_start() {
	$("#report-gen:not(.processed)").each(function(){
		var formObj = $(this).parents("form");
		$("img.img-export", this).click(function(){
			$("input[name='report_request']", formObj).val(1);
			$(formObj).submit();
		});
		$(this).addClass('processed')
	});
}
/* Author: Marco 
Aggiungo l'azione al bottone del report amministrativo
*/
function report_amm_start() {
	$("#report-amm:not(.processed)").each(function(){
		var formObj = $(this).parents("form");
		$("img.img-export", this).click(function(){
			$("input#link").val('Report/reportAmm.php');
			$(document.createElement('input')).attr('type', 'hidden').attr('name', 'flag').val(1).appendTo(formObj);
			$(document.createElement('input')).attr('type', 'hidden').attr('name', 'queryNum').val(1).appendTo(formObj);
			$(document.createElement('input')).attr('type', 'hidden').attr('name', 'link').val('Report/reportAmm.php').appendTo(formObj);
			$(formObj).submit();
		});
		$(this).addClass('processed')
	});
}

function ctrl_cf_bt_start() {
	$("#verify-cf-pg:not(.processed)").each(function(){
		$("img.img-prosegui",this).each(function(){
		  var formObj = $(this).parents("form");
		  $(this).click(function(){
			  var errors = ctrl_req(formObj);
		      if ($(errors).length == 0 ) { 
		    	
		    	$("input[name='flag']", formObj).val(1);
		        $(formObj).submit();
			  }
		      else {
				var alert_msg = '';
				$(errors).each(function() {
				  alert_msg = alert_msg + this + "\r\n";
				});
				alert(alert_msg);
			  }
		  });	
		});
	});
}

function ctrl_cf_assServ_start() {
	$("#verify-cf-pg-2:not(.processed)").each(function(){
		$("img.img-prosegui",this).each(function(){
		  var formObj = $(this).parents("form");
		  $(this).click(function(){
			  var errors = ctrl_req(formObj);
		      if ($(errors).length == 0 ){ 
		    	  $("input[name='flag']", formObj).val(2);
			      $(formObj).submit();
			  }
		      else {
				var alert_msg = '';
				$(errors).each(function() {
				  alert_msg = alert_msg + this + "\r\n";
				});
				alert(alert_msg);
			  }
		  });	
		});
	});
}

function servizio_start(){
  $("#pg-servizio:not(.processed)").each(function(){
    var formObj = $(this).parents("form");
    $("img.img-serv-save", this).click(function(){
      $("input[name='save']", formObj).val(1);
      $(formObj).submit();
    });
    $(this).addClass('processed')
  });
}

function pager_clicks(){
  $("div.pager:not(.processed)").each(function(){
    var pager = this;
    $("div.pager-ctrl > div", pager).each(function(){
      var pgnum = get_elementId(this);
        $(this).click(function(){
          var formObj = $(pager).parents('form'); 
          $("input", pager).val(--pgnum);
          $(formObj).submit();
        });
        $(this).attr('title', 'Vai alla pagina ' + (++pgnum));
    });
    $(this).addClass('processed');
  });
}

function odd_even_heading_report(){
  $("table tr:not(.header)").each(function(i){
    if(i%2 == 0){
      $(this).addClass('even');
    }else{
      $(this).addClass('odd');
    }
  })
}

function reportTable() {
  $("table.report tr.header").each(function(){
    $('th', $(this)).each(function(i){
       if ($(this).hasClass('number')) {
         $("table.report tr:not(.header)").each(function(){
           $("td", $(this)).each(function(j){
             if (j == i) {
               $(this).addClass('number');
             }
           });
         });
       }
    });
  });
}
/* Author: Marco 
Richiamo la funzione che popola il dropdown di date in base al servizio che è stato scelto.
*/
function regPresenza_start(){
	$("#presenza-form:not(.processed)").each(function(){
		//console.log(this);
		 $("#rpServ", this).each(function(){
				viewDatas($(this).val(),'#dateServ',2);
		});
	});
	$(this).addClass('processed');
}

/*Author: Marco
 * Funzione che permette di associare l'ente dalla schermata referente
 * abilita il bottone cerca e l'apertura del popup con i risultati
 * */
//function enteFromRef_start(){
//	  var url = 'hr/addUser.php';
//	  $("#anag-form:not(.processed)").each(function(){
//			grandContainer = this;
//			add_usrGrp_remove_bt(this);
//			form_obj = $(this).parents("form");
//	    $("img.img-asentsearch", this).each(function(){
//	      var parent = $(this).parents('fieldset')
//	      var type = get_elementId(parent);
//	      $(this).click(function(){
//	        var str = $("input[name=toSearch]", parent).val();
//	        var list_container = $(".user-list", parent);
//	        src_user_assoc(str, type, list_container, 1);
//	      });
//	    });
//	    $(this).addClass('processed');
//	  });
//	}
//Versione modificata da Corrado il 22/12
function enteFromRef_start(){
	   var url = 'hr/addUser.php';
	   $("#anag-form:not(.processed)").each(function(){
	   grandContainer = this;
	   add_usrGrp_remove_bt(grandContainer);
	//   form_obj = $(this).parents("form");
	     $("img.img-asentsearch", grandContainer).each(function(){
	       var parent = $(this).parents('fieldset')
	       var type = get_elementId(parent);
	       $(this).click(function(){
	         var str = $("input[name=toSearch]", parent).val();
	         var list_container = $(".user-list", parent);
	         src_user_assoc(str, type, list_container, 1);
	       });
	     });
	     $(this).addClass('processed');
	   });
	 }
