// JavaScript Document
jQuery.fn.extend({
  findPos : function() {
    obj = $j(this).get(0);
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
    }
    return {x:curleft,y:curtop};
  } 
});
function computeNavJsHor() {
  $j('.navjs-hor-top').find('ul').each(function() {
    var pos = 0;
    $j(this).parents('li:first').prevAll().each(function() {
      pos += $j(this).width();
    });
    $j(this).css({left: '-'+pos+'px', top: $j(this).parents('.navjs-hor-top').children('li:first').height()});
  });
}
function myJqueryInit() {  
  //Supprime cursor hand des dates agenda si pas event  
  $j('#datepicker').find('td:not(.PEND) a').css('cursor', 'default');
  //Hauteur container colonne
	$j('.wuc_col').each(function() {  
    $j(this).equalHeight();
  });	
  //Hauteur comp ergo
  $j(this).ergoHeight();
  //Hauteur div fond 2 du body
  $j(this).bodyFondHeight();
  $j(window).bind('resize', function() {
    computeNavJsHor();
  });
  // Nav tiroirs
  computeNavJsHor();   
  // Hauteur navigation slidedeck
  $j('.wuSlidedeck_page').each(function() {
    $j(this).width($j(this).parents('.wuSlidedeck_nav_content').outerWidth());
    $j(this).equalHeight($j(this)[0].tagName.toLowerCase(), '.wuSlidedeck_pages'); 
    $j('.wuSlidedeck_pages').each(function() {   
      $j(this).height($j(this).css('minHeight'));
      $j(this).parent('.wuSlidedeck_nav_content').height($j(this).css('minHeight'));
    });      
  });
  $j('.wuChooseLng').change(function() {
    var q = '';
    var l = String(window.location);
    if (l.indexOf('?')>=0) {
      q = '&wuLngCode=';
    } else {
      q = '?wuLngCode=';
    }
    window.location.href = l + q + $j(this).val();
  });
}  
//Reinitialisation des hauteurs 
function wuCleanUpHeight() {  
	$j('.wuc_col,.wu_object,[id=wuRub],[id^=wuContent],[id^=wuColExt],[id^=wuColInt],[id^=wuHeader],[id^=wuFooter]').each(function() {
	  $j(this).css('min-height', '');
		$j(this).height('auto'); 
	});
}	

//Auto ref
function wuGetAutoRef() {
	$j('input[name="wuAutoRef"]').val($j('input[name="wuAutoRefValue"]').val());
}

$j(document).ready(function(){    
  // Recalcul hauteur sur click treeview
	$j('div[class^="hitarea"]').live("click", function(){  	
		setTimeout("wuCleanUpHeight();myJqueryInit(); ",100);		
	});       
	//navigation css
	$j(".navjs-h li,.navjs-v li").hover(
		function() { $j(this).addClass("iehover"); },
		function() { $j(this).removeClass("iehover"); }
	);  
  //Affichage masque + popup type ajax
  $j("*[id^=wuOpenPopup]").click(function () {
    var Tid = $j(this).attr("id").split("__");
    //var
    var wuID = Tid[2];
    var wuWidth = Tid[3];
    var wuHeight = Tid[4];
    var wuMasqueClass = Tid[5];
    var wuMasqueOpacity = Tid[6]; 
    //Tableau post pour ajax
    var wuParams = new Array();
    wuParams['phpFile'] = 'plugins/wuPlugin_ajaxPopup.php';
    wuParams['location'] = '1';
    wuParams['wuPopupID'] = wuID;
    //appel ajax
    wuContentAjax("#wuPopup_"+wuID, wuParams);
    //ouverture popup + masque
    wuOpenPopup("#wuPopup_"+wuID, wuWidth, wuHeight);
    wuOpenMasque("#masque", wuMasqueClass, wuMasqueOpacity);    
    return false;
  });  
  // fermeture popup sur click masque (out popup)
  $j("#masque").live("click", function(){
    $j("*[id^=wuPopup_]").fadeOut("fast"); 
    $j("#masque").fadeOut("slow"); 
  });      
  //Fermeture masque + popup list components
  $j("*[id^=wuClosePopup]").live("click", function(){
    var Tid = $j(this).attr("id").split("__");
    var wuID = Tid[2];
    $j("#wuPopup_"+wuID).fadeOut("fast"); 
    $j("#masque").fadeOut("slow"); 
  });
  //Validation formulaire popup type ajax + affichage
  $j("*[id^=wuSubmitFormAjax]").live("click", function(){
    var Tid = $j(this).attr("id").split("__");
    var wuID = Tid[2];
    var wuForm = Tid[3];
    var wuSubmitFct = Tid[4];
    var wuVerifFct = Tid[5];
    if(wuVerifFct != '') return eval(wuVerifFct)(wuSubmitFct, wuForm, wuID);
    else { eval(wuSubmitFct)(wuForm, wuID); }
  }); 	
});

//Ouverture popup
function wuOpenPopup(wuEl, wuWidth, wuHeight) {
  $j(wuEl).width(wuWidth+'px');
  $j(wuEl).height(wuHeight+'px');
  wuPosPopup(wuEl, wuWidth, wuHeight);
  $j(wuEl).fadeIn("fast");   
}
//Positionnement popup
function wuPosPopup(wuEl, wuWidth, wuHeight) {
  $j(wuEl).css("left", ($j(window).width() - $j(wuEl).width()) / 2);  
  if($j(document).height() > $j(wuEl).height()) {
    $j(wuEl).css("top", (($j(window).height() - $j(wuEl).height()) / 2) + $j(document).scrollTop()); 
  }
}
//Contenu ajax
function wuContentAjax(wuEl, wuParams) {
  //Construction obj json pour post
  var params = '';  
  for(key in wuParams) {
    if(params != '') params += ", ";
    params += key+':"'+wuParams[key]+'"'; 
  }
  var params = '{'+params+'}';
  //ajax
  $j.post('wuAjax.php', eval('('+params+')'), function (jData) {
    var response = $j.evalJSON(jData);
    $j(wuEl).html(response.flow);
		if (response.functionCall) {			 
		  for(var i=0; i < response.functionCall.length; i++) {
        eval(response.functionCall[i]);
      }       
		}
		$j('.wuc_col').each(function() {  
	    $j(this).equalHeight();
	  });		
		wuGetAutoRef();			
  }); 
}
//Ouverture du masque gris
function wuOpenMasque(wuEl, wuClass, wuOpacity) {
  $j(wuEl).addClass(wuClass);
  $j(wuEl).css("opacity", wuOpacity/100);
  $j(wuEl).css("filter", "alpha(opacity="+wuOpacity+")");
  $j(wuEl).height($j(document).height());  
  $j(wuEl).width("100%");    
  $j(wuEl).fadeIn("slow"); 
}
//Verification champ sendFriend
function wuVerifSendFriend(wuSubmitFct, wuForm, wuID) {
  var alert_nom = $j('input[name="alert_nom"]').val();
  var alert_mail = $j('input[name="alert_mail"]').val();
  var alert_mail_friend = $j('input[name="alert_mail_friend"]').val();
  var filtreMail = /^[A-Za-z0-9.-_--]+@[A-Za-z0-9.-_--]+\.[A-Za-z]{2,5}$/;  
  if($j("#ami").val() == '') {
    alert(alert_nom);
    $j("#ami").focus(); 
    return false;
  } else {    
    if (filtreMail.test($j("#mailFrom").val()) != true) {
      alert(alert_mail);
      $j("#mailFrom").focus();
      return false; 
    } else {
      if (filtreMail.test($j("#mailDest").val()) != true) {
        alert(alert_mail_friend);
        $j("#mailDest").focus();
        return false;
      } 
      else { return eval(wuSubmitFct)(wuForm, wuID); }
    }  
  }
}
//Submit du sendFriend
function wuSubmitSendFriend(wuForm, wuID) {
  var wuParams = new Array();
  wuParams['phpFile'] = 'plugins/wuPlugin_ajaxPopup.php';
  wuParams['location'] = '1';
  wuParams['wuPopupID'] = wuID;
  $j("form[name="+wuForm+"]").ajaxSubmit({ url: "wuAjax.php", type: 'post', success: function() { wuParams['wuMess'] = 'ok'; wuContentAjax("#wuPopup_"+wuID, wuParams); }, error: function() { wuParams['wuMess'] = 'nok'; wuContentAjax("#wuPopup_"+wuID, wuParams); }});
  return false;   
}
 
//Hauteur des containers et colonnes 
jQuery.fn.equalHeight = function (objSelector, supObjSelector) {    
  if(objSelector == '' || objSelector == undefined) {	objSelector = '.wuc_col'; }  
  if(supObjSelector == '' || supObjSelector == undefined) {	supObjSelector = '.wu_object'; }
  var height       = 0;
  var maxHeight    = 0;  
	// recupere la hauteur maximale
  $j(this).siblings(objSelector).each(function() {   
    height       = $j(this).outerHeight(true);    
    maxHeight    = (height > maxHeight) ? height : maxHeight;         
    $j(this).setHeight(maxHeight);
  }); 
  $j(this).prevAll(objSelector).each(function() {  
    $j(this).setHeight(maxHeight);
  });
	if(maxHeight == 0) maxHeight = $j(this).outerHeight(true); 
  // Attribue la hauteur maximale aux colonnes et containers
  $j(this).setHeight(maxHeight);
  $j(this).parents(supObjSelector+':first').setHeight(maxHeight);       
};                   

//Hauteur des comp d ergo
jQuery.fn.ergoHeight = function () {  
	var contHeight = $j("#wuContentExt").outerHeight(true);
	//contenu ext
	$j("[id^=wuColExt],[id=wuContentInt]").each(function() {
	   $j(this).setHeight(contHeight);
	});
	//contenu int
	if($j("#wuHeaderInt").size() > 0) { var headerHeight = $j("#wuHeaderInt").outerHeight(true); }
	else var headerHeight = 0;
	if($j("#wuFooterInt").size() > 0) { var footerHeight = $j("#wuFooterInt").outerHeight(true); }
	else var footerHeight = 0;
	$j("[id^=wuColInt],[id=wuRub]").each(function() {  
	   $j(this).setHeight(Math.round(contHeight - headerHeight - footerHeight));
	});
};

//Hauteur de la div affichant le fond 2 du body
jQuery.fn.bodyFondHeight = function () {   
	bodyHeight = $j('body').outerHeight(true);  	
  windowHeight = $j(window).height();
  $j("[id^=wuBodyFond]").each(function() {
    if($j(this).hasClass('wuBackFixed')) {
  	  if(windowHeight > bodyHeight) { $j(this).height(windowHeight); }
    	else { $j(this).height(bodyHeight); } 
  	}    
  	else {
  	  $j(this).height(bodyHeight); 
  	}
  });  
};   

//Set height
jQuery.fn.setHeight = function(maxHeight) {          
  var minHeight   = maxHeight - ($j(this).outerHeight(true) - $j(this).height()); 
  var property    = $j.browser.msie && $j.browser.version < 7 ? 'height' : 'min-height';
	$j(this).css(property, minHeight + 'px');
} 

//Waiting form
function wuWaitingForm() {	  
	$j("#masque").css("background", "#000");
  wuOpenPopup("#wuWaitingPopup", '30', '28');
  wuOpenMasque("#masque", '', '50');    
} 

//Close Waiting form
function wuCloseWaitingForm() {	
	$j("#wuWaitingPopup").fadeOut("slow"); 
	$j("#masque").fadeOut("slow");      
}  

// Initialisation fancybox -> popup detail du fullcalendar 
function wuFullcalendar_fancybox_detail() {
  // Ajoute class fancyzoom sur events  	
  $j('[id^="wuFullcalendar_"]').find('.fc-event').find('a').each(function() {
    $j(this).addClass('wuFullcalendar_openEvent');                  
  });
  // Declare le fancybox pour detail event         
  $j(".wuFullcalendar_openEvent").fancybox({
    'transitionIn'	:	'fade',
    'transitionOut'	:	'fade',
    'speedIn'		:	300, 
    'speedOut'		:	300,
    'autoDimensions' : false,
    'width'    : 550,
    'height'  : 'auto', 		
    'titleShow'   : false,
    'hideOnOverlayClick' : true,     
    'overlayShow'	:	true
  });        
}  

// Initialisation fancybox -> popup erreur du fullcalendar 
function wuFullcalendar_fancybox_error(ID) { 
  $j('#wuFullcalendar_'+ID).find('[class*=fc-day],[class*=fc-slot]').each(function() {
    $j(this).addClass('wuFullcalendar_addEventErr');                  
  });
  // Declare le fancybox pour add event         
  $j(".wuFullcalendar_addEventErr").fancybox({
    'transitionIn'	:	'fade',
    'transitionOut'	:	'fade',
    'speedIn'		:	300, 
    'speedOut'		:	300,
    'titleShow'   : false,
    'hideOnOverlayClick' : true,     
    'overlayShow'	:	true,
    'content' : '<b>Cr&eacute;ation impossible. </b><br /><br />Aucun dossier parent sp&eacute;cifique d&eacute;fini.'
  });          
}  

// Refrech des events du fullcalendar
function wuFullcalendar_refrech() { 
  $j('[id^="wuFullcalendar_"]').fullCalendar('refetchEvents');
}       
