var xhr = null;
var interval = null;
var gsBCName = 'bodycover';

/* Fonction de récupération de la hauteur du contenu du navigateur */
function getWindowInnerHeight(pbAll)
{
  var myHeight = 0;
  var yInner = 0;

  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientHeight ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }

  if (pbAll==undefined)
  return myHeight;

  if (window.innerHeight && window.scrollMaxY) {
    yInner = window.innerHeight + window.scrollMaxY;
  }
  else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    yInner = document.body.scrollHeight;
  }
  else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
    yInner = document.documentElement.scrollHeight;
  }
  else { // Explorer Mac...would also work in Mozilla and Safari
    yInner = document.body.offsetHeight;
  }

  // for small pages with total height less then height of the viewport
  return (yInner < myHeight) ? myHeight : yInner;
}

/* Fonction de récupération de la largeur du contenu du navigateur */
function getWindowInnerWidth(pbAll)
{
  var myWidth = 0;
  var xInner = 0;

  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }

  if (pbAll==undefined)
  return myWidth;

  if (window.innerWidth && window.scrollMaxX) {
    xInner = window.innerWidth + window.scrollMaxX;
  }
  else if (document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
    xInner = document.body.scrollWidth;
  }
  else if (document.documentElement && document.documentElement.scrollWidth > document.documentElement.offsetWidth){ // Explorer 6 strict mode
    xInner = document.documentElement.scrollWidth;
  }
  else { // Explorer Mac...would also work in Mozilla and Safari
    xInner = document.body.offsetWidth;
  }

  // for small pages with total height less then height of the viewport
  return (yInner < myWidth) ? myWidth : yInner;
}

/* Masque le contenu du navigateur via un voile noir */
function coverBody()
{
  if (document.getElementById(gsBCName) != undefined) return;

  var div = document.createElement('div');
  div.id = gsBCName;
  div.style.height = getWindowInnerHeight(true) + 'px';

  document.body.appendChild(div);

  SelectComboVisible(false);

  document.documentElement.style.overflow = 'hidden';

  interval = window.setInterval(refreshCover, 2000);
}

function SelectComboVisible(pbVisible)
{
  //elem = document.getElementsByTagName('select');
  $("select").each(function(nKey)
  {  
	// bug s'il y a un multiselect + un Qis ds le meme form
	// la fonction affiche le select cache de la liste
	
	// On ne masque pas les champs mois et date des calendriers
	if( $(this).attr("tag")!= "stay_hidden" && $(this).attr("name").indexOf('month')==-1 && $(this).attr("name").indexOf('year') == -1 && $(this).attr("name").indexOf('pfrmpaymod[]') == -1)
	{
	  if (pbVisible)
		$(this).show();
	  else
	    $(this).hide();
	}
	
  });
}

/* Rafraîchit l'affichage du voile */
function refreshCover()
{
  if (document.getElementById(gsBCName) != undefined)
  document.getElementById(gsBCName).style.height = getWindowInnerHeight(true) + 'px';
}

/* Retire le masque le contenu du navigateur via un voile noir */
function uncoverBody()
{
  if (interval!=undefined)
  {
    window.clearInterval(interval);
    SelectComboVisible(true);
  }
  else
  {
    if (parent.interval!=undefined)
    {
      parent.clearInterval(parent.interval);
      parent.SelectComboVisible(true);
    }
  }

  if (document.getElementById(gsBCName) != undefined)
  {
    document.documentElement.style.overflow = '';
    document.body.removeChild(document.getElementById(gsBCName));
  }
  else
  {
    if (parent.document.getElementById(gsBCName) != undefined)
    {
      parent.document.body.removeChild(parent.document.getElementById(gsBCName));
      parent.document.documentElement.style.overflow = '';
    }
  }
}

// Fonction permettant de passer une Div en visible en affichant dans cette div le contenu de la définition du Pk mot passé en parametre utilisé ici dans le glossaire
function AjaxBubble(poEvt, psServiceURL)
{

  if(window.XMLHttpRequest) // Ajax sur Firefox et autres
  xhr = new XMLHttpRequest();

  else if(window.ActiveXObject)//Ajax sur Internet Explorer
  {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  else { // XMLHttpRequest non supporté par le navigateur

    // alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
    xhr = false;
    return;
  }

  div = document.getElementById('divbubble');
  if (div==undefined)  return;

  //div.style.width = '350px';
  //div.style.height = '180px';
  


  if (navigator.appName != "Microsoft Internet Explorer")
  {
    nYMousePosition = poEvt.pageY ;
    nXMousePosition = poEvt.pageX;

    nYMouse = poEvt.clientY;
    nXMouse = poEvt.clientX;

    nHeight = window.innerHeight;
    nWidth = window.innerWidth;
  }
  else
  {
    nYMousePosition = event.clientY + document.documentElement.scrollTop;
    nXMousePosition = event.clientX + document.documentElement.scrollLeft;

    nYMouse = event.clientY;
    nXMouse = event.clientX;

    nHeight = screen.availHeight;
    nWidth = screen.availWidth;
  }

  
  
  MoveBubble(nXMousePosition, nYMousePosition, nYMouse, nXMouse, nHeight, nWidth);
  $('#divbubbleContent').hide();
  $('#divbubble').show();
  $('#loadingGif').show();

 
  $.get(psServiceURL, function(data) {
	  $('#loadingGif').hide();
	  $('#divbubbleContent').html(data);
	  
	  MoveBubble(nXMousePosition, nYMousePosition, nYMouse, nXMouse, nHeight, nWidth);
	  $('#divbubbleContent').fadeIn('slow');
	});

  /*
  xhr.onreadystatechange = function()
  { // gestionnaire d'evenement sur AJAX.
    // On ne fait quelque chose que si on a tout reçu et que le serveur est ok
    if(xhr.readyState == 4 && xhr.status == 200)
    {
      oDiv = document.getElementById('divbubble')
      if (oDiv != undefined)
      {
        oDiv.innerHTML = xhr.responseText;
        
      }
    }
  }
  xhr.open('GET', psServiceURL, true); // on appelle le contenu de la div par la méthode GET avec un ID correspondant au PK du mot
  xhr.send(null); // on envoie rien :p
*/
  document.onmousemove = moveToMousePosition; // pour chaque mouvement de la souris , on recupere sa position

}

/* Fonction de déplacement d'un div en même temps que la souris */
function moveToMousePosition(poEvt) //fonction permettant de connaitre de position de la souris sur l'axe des X et des Y
{
  if (navigator.appName != "Microsoft Internet Explorer")
  {
    nYMousePosition = poEvt.pageY;
    nXMousePosition = poEvt.pageX;

    nYMouse = poEvt.clientY;
    nXMouse = poEvt.clientX;

    nHeight = window.innerHeight;
    nWidth = window.innerWidth;
  }
  else
  {
    nYMousePosition = event.clientY + document.documentElement.scrollTop;
    nXMousePosition = event.clientX + document.documentElement.scrollLeft;

    nYMouse = event.clientY;
    nXMouse = event.clientX;

    nHeight = document.documentElement.clientHeight;
    nWidth = document.documentElement.clientWidth;
  }

  MoveBubble(nXMousePosition, nYMousePosition, nYMouse, nXMouse, nHeight, nWidth);
}

function MoveBubble(pnXMousePosition, pnYMousePosition, pnYMouse, pnXMouse, pnHeight, pnWidth)
{
  oDiv = document.getElementById('divbubble');
  if (oDiv != undefined)
  {
    
      if (pnYMouse + 10 + oDiv.offsetHeight  < pnHeight)
        oDiv.style.top = pnYMousePosition + 10 + 'px';
      else
        oDiv.style.top = (pnYMousePosition - 10 - oDiv.offsetHeight) + 'px';

      if (pnXMouse + 10 + oDiv.offsetWidth  < pnWidth)
        oDiv.style.left = pnXMousePosition + 10 + 'px';
      else
        oDiv.style.left = (pnXMousePosition - 10 - oDiv.offsetWidth) + 'px';
    
  }
}


function setDisplay(psDivName, pbState)
{
  if (pbState)
  {
    $('#' + psDivName).show();
  }
  else
  {
    $('#' + psDivName).hide();
  }
  return true;
}

function doResize(psDivName, pnWidth, pnHeight)
{
  e = document.getElementById(psDivName);
  if (e == undefined || e == null)
  {
    e = parent.document.getElementById(psDivName);
    if (e!=undefined && e!=null) return parent.doResize(psDivName, pnWidth, pnHeight);
  }

  if (pnWidth != null && pnWidth < 0 || pnHeight != null && pnHeight < 0)
  {
    $(e).hide();
    return;
  }

  scrollTop = document.documentElement.scrollTop;
  scrollLeft = document.documentElement.scrollLeft;

  nWidth = (pnWidth != null) ? pnWidth : 0;
  nHeight = (pnHeight != null) ? pnHeight : 0;

  if (nWidth == 0 && nHeight == 0)
  {
    nWidth = getWindowInnerWidth() - 100;
    nHeight = getWindowInnerHeight() - 100;
  }

  leftPos = (getWindowInnerWidth() - nWidth) / 2;
  topPos = (getWindowInnerHeight() - nHeight) / 2;

  //Sous IE, il faut ajouter le scroll pour le TopPos
  if (navigator.appVersion.indexOf("MSIE")!=-1)
  {
    // Sauf IE7
    if (!(document.all && !window.opera && window.XMLHttpRequest))
    {
      leftPos = leftPos + scrollLeft;
      topPos = topPos + scrollTop;
    }
  }

  $(e).show();

  e.style.top = topPos + 'px';
  e.style.left = leftPos + 'px';

  e.style.width = nWidth + 'px';
  e.style.height = nHeight + 'px';
}

function cancelAction()
{
  parent.setDisplay('divaction', false);
  parent.setDisplay('divwait', false);

  uncoverBody();
}

function ExecuteAction(page, pnWidth, pnHeight)
{
  coverBody();
  setDisplay('divwait', true);

  doResize('divaction', pnWidth, pnHeight);

  div = document.getElementById('divaction');

  // On charge la page si besoin
  if (page != '')
  {
    $(function(){div.src = page});
  }

  return true;
}

function ReloadOpener(sURL, psReturnTab)
{
  if (parent!=null)
  {
    if (sURL != '')
    {
      nPosAncre = sURL.indexOf('#')
      if (nPosAncre != -1)
      {
        var sTab = sURL.substring(nPosAncre+1);
        sURL = sURL.substring(0, nPosAncre) + '&hmpst=' + sTab;
      }
      
      parent.location.replace(sURL);
    }
    else
    {
      div = document.getElementById('divaction');
      if (div!=undefined)
      div.location = 'empty.html';

      sURL = parent.location.href;
      nPosAncre = sURL.indexOf('#')
      if (nPosAncre != -1)
      sURL = sURL.substring(0, nPosAncre);

      if (psReturnTab)
      sURL += '&hmpst=' + psReturnTab;

      parent.location.replace(sURL);
    }
  }
}

function trim(inputString)
{
  if (typeof inputString != "string")
  { return inputString; }
  var retValue = inputString;
  var ch = retValue.substring(0, 1);
  while (ch == " ")
  {
    retValue = retValue.substring(1, retValue.length);
    ch = retValue.substring(0, 1);
  }
  ch = retValue.substring(retValue.length-1, retValue.length);
  while (ch == " ")
  {
    retValue = retValue.substring(0, retValue.length-1);
    ch = retValue.substring(retValue.length-1, retValue.length);
  }
  while (retValue.indexOf("  ") != -1)
  {
    retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
  }
  return retValue;
}


function OpenSelector(psURL, psParamName, psIdReturnField, pnWidth, pnHeight)
{
  sParam = document.getElementById(psIdReturnField).value;
  sURL = psURL;
  if (sParam != '')
  sURL = psURL + "&" + psParamName + "=" + sParam;


  if (pnWidth == 0 || pnHeight == 0)
  {
    pnWidth = getWindowInnerWidth() - 100;
    pnHeight = getWindowInnerHeight() - 100;
  }

  ExecuteAction(sURL, pnWidth, pnHeight);
}

/*
* @Parameters : [in] psReturnFieldParent
* @Return <nothing>
* @desc : Valide le formulaire : envoie le résultat,
* @desc : au formulaire de la fenetre appelante dont l'id est passé en parametre
*/
function ValidMetaSelector(psDataFieldParent, psViewFieldParent, psDataResult, psViewResult)
{
  parent.document.getElementById(psDataFieldParent).value = psDataResult;
  parent.document.getElementById(psViewFieldParent).innerHTML = psViewResult;
  parent.cancelAction();
}

/*
* @Parameters : [in] psReturnFieldParent
* @Return <nothing>
* @desc : Valide le formulaire apres un QuickSaveAdd : envoie le résultat,
* @desc : au formulaire de la fenetre appelante dont l'id est passé en parametre
*/
function ValidMetaSelectorQuickAdd(psDataFieldParent, psViewFieldParent, psDataResult, psViewResult)
{
  parent.document.getElementById(psDataFieldParent).value = psDataResult;
  parent.document.getElementById(psViewFieldParent).innerHTML = psViewResult;
  parent.cancelAction();
}

/*
* @Parameters : [in] psReturnFieldParent
* @Return <nothing>
* @desc : Valide le formulaire : envoie le contenu du champ caché local,
* @desc : au formulaire de la fenetre appelante dont l'id est passé en parametre
*/
function EmptySelector(psDataFieldParent, psViewFieldParent, psViewValue, psConfirm)
{
  if (confirm(psConfirm))
  {
    document.getElementById(psDataFieldParent).value = '';
    document.getElementById(psViewFieldParent).innerHTML = psViewValue;
  }
}

/*
* @Parameters : [in] psReturnFieldParent
* @Return <nothing>
* @desc : Valide le formulaire : envoie le contenu du champ caché local,
* @desc : au formulaire de la fenetre appelante dont l'id est passé en parametre
*/
function ValidSelector(psDataFieldParent, psViewFieldParent)
{
  parent.document.getElementById(psDataFieldParent).value = document.getElementById(psDataFieldParent).value;
  parent.document.getElementById(psViewFieldParent).innerHTML = document.getElementById(psViewFieldParent).value;

  parent.cancelAction();
}

var nIdTimer;
/*
* Affiche le message principal de la page
*/
function ShowMessage(psId, pnWidth, pnTime)
{
  var object = document.getElementById(psId);

  // Calcul du centrage sur l'ecran
  var nAvailHeight = screen.availHeight;
  var nAvailWidth = screen.availWidth;
  //    var nTop = (nAvailHeight - 100)/2 - 100;
  var nTop = 200;
  var nLeft = (nAvailWidth - pnWidth)/2;

  object.onclick = HideThisMessage;

  object.style.display = '';

  nIdTimer = setTimeout('HideMessage("'+psId+'")', pnTime);
}

function HideMessage(psId)
{
  if (parent.document.getElementById(psId)!=undefined)
  parent.document.getElementById(psId).style.display='none';

  if (document.getElementById(psId)!=undefined)
  document.getElementById(psId).style.display='none';
}

function HideThisMessage()
{
  this.style.display='none';
}

function loadcharts()
{
  $('.chart').each(function ()
  {
    $(this).load(this.title);
  });
}

$(function()
{
  $('.htmlmaker_context_title').each(
  function()
  {
    if (ReadCookie($(this).text()) == 'hide')
    {
      $(this).siblings('.htmlmaker_context_block').hide();
      $(this).toggle(function()
      {
        $(this).siblings('.htmlmaker_context_block').animate({height:'show'}, 'normal');
        WriteCookie($(this).text(), 'show');
      },
      function()
      {
        $(this).siblings('.htmlmaker_context_block').animate({height:'hide'}, 'normal');
        WriteCookie($(this).text(), 'hide');
      })
    }
    else
    {
      $(this).toggle(function()
      {
        $(this).siblings('.htmlmaker_context_block').animate({height:'hide'}, 'normal');
        WriteCookie($(this).text(), 'hide');
      },
      function()
      {
        $(this).siblings('.htmlmaker_context_block').animate({height:'show'}, 'normal');
        WriteCookie($(this).text(), 'show');
      })
    }
  });
});

(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0){this.insertBefore(document.createElement(html),this.firstChild);}});}return this;};})(jQuery);