﻿function MM_findObj(n, d) { //v4.01
  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 && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

//---------------------------------------------------------------------------------------------------------------------------
function IsEntier(str)
{
  if((typeof(str)=='undefined') || str == '') return false;

  if(isNaN(str) == false) return true;
  else return false;

  /*
  var len= str.length;
  if (len==0)
    return false;
  var p=0;
  var ok= true;
  var ch= "";
  while (ok && p<len)
  {
    ch= str.charAt(p);
    if ('0'<=ch && ch<='9')
      p++;
    else
      ok= false;
  }
  return ok;
  */
}

//---------------------------------------------------------------------------------------------------------------------------
function PrintArticleSelection()
{
  $('#PrintSelectionIFrame').attr('src', 'printselection.php');
}

//---------------------------------------------------------------------------------------------------------------------------
function EmptyArticleSelection()
{
	if (confirm("Are you sure you want to empty your selection ?"))
	{
		$.ajax({ url: "ajax.php?Action=EmptyArticleSelection", success: function(data)
			{
					if(!IsEntier(data)) alert(data);
					else
					{
						UpdateInterfaceForSelectionState(data, 1);
						$('.cont-article-selection').remove();
					}
			}});
	}
	
}

//---------------------------------------------------------------------------------------------------------------------------
function AddArticleToSelection(p_ID, p_SmallSize)
{
	if(p_SmallSize == 1)
	{
		p_ImgPref = 'small_';
		p_SmallSize = '1';
	}
	else
	{
		p_ImgPref = '';
		p_SmallSize = '0';
	}
	
	$.ajax({ url: "ajax.php?Action=AddArticleToSelection&ArchContenuID="+p_ID, success: function(data)
	{
			if(!IsEntier(data)) alert(data);
			else UpdateInterfaceForSelectionState(data, 0);

      // Ne marche pas sous IE (9 et autre ?)
			//$('#BoutonAddArticleToSelection_'+p_ID).html('<span id="BoutonRemoveArticleFromSelection_'+p_ID+'"><a title="Remove from my selection" href="javascript:void(0);" onclick="RemoveArticleFromSelection('+p_ID+', 0, '+p_SmallSize+');"><img src="images/'+p_ImgPref+'removefromselection.png" /></a></span>');

      $('#BoutonAddArticleToSelection_'+p_ID).css('display', 'none');
      $('#BoutonRemoveArticleFromSelection_'+p_ID).css('display', 'block');
      
      
		}});
}

/*function AddArticleToSelection(p_ID)
{
	$.ajax({ url: "ajax.php?Action=AddArticleToSelection&ArchContenuID="+p_ID, success: function(data)
	{
			if(!IsEntier(data)) alert(data);
			else UpdateInterfaceForSelectionState(data, 0);

			$('#BoutonAddArticleToSelection_'+p_ID).html('<span id="BoutonRemoveArticleFromSelection_'+p_ID+'"><a title="Remove from my selection" href="javascript:void(0);" onclick="RemoveArticleFromSelection('+p_ID+', 0);"><img src="images/removefromselection.png" /></a></span>');

		}});
}
*/


//---------------------------------------------------------------------------------------------------------------------------
// Supprime un article p_ID de la sélection.
// Si on reçoit un entier en retour ajax, c'est le nombre d'éléments restants dans la sélection,
// on demande alors un update du texte "x items in your selection".
//
// Si p_FromSelectionList = 1, on se trouve sur la page de sélection. Après une suppression,
// on supprime le bloc conteneur de l'article.
// Si p_FromSelectionList est différent de 1, on est sur une vue d'article seul, on remplace
// le bouton "Remove" par un bouton "Add".
//---------------------------------------------------------------------------------------------------------------------------
/*function RemoveArticleFromSelection(p_ID, p_FromSelectionList)
{
	$.ajax({ url: "ajax.php?Action=RemoveArticleFromSelection&ArchContenuID="+p_ID, success: function(data)
	{
			if(!IsEntier(data)) alert(data);
			else UpdateInterfaceForSelectionState(data, p_FromSelectionList);

			// Met à jour les boutons ou la visibilité de l'article supprimé
			if(p_FromSelectionList != 1)
			{
				$('#BoutonRemoveArticleFromSelection_'+p_ID).html('<span id="BoutonAddArticleToSelection_'+p_ID+'"><a title="Add to my selection" href="javascript:void(0);" onclick="AddArticleToSelection('+p_ID+');"><img src="images/addtoselection.png" /></a></span>');
			}
			else
			{
				$('#SelectionArticle_'+p_ID).remove();
			}

	}});
}*/
//---------------------------------------------------------------------------------------------------------------------------
function RemoveArticleFromSelection(p_ID, p_FromSelectionList, p_SmallSize)
{
	if(p_SmallSize == 1)
	{
		p_ImgPref = 'small_';
		p_SmallSize = '1';
	}
	else
	{
		p_ImgPref = '';
		p_SmallSize = '0';
	}
	
	$.ajax({ url: "ajax.php?Action=RemoveArticleFromSelection&ArchContenuID="+p_ID, success: function(data)
	{
			if(!IsEntier(data)) alert(data);
			else UpdateInterfaceForSelectionState(data, p_FromSelectionList);

			// Met à jour les boutons ou la visibilité de l'article supprimé
			if(p_FromSelectionList != 1)
			{
        // Ajout dynamique marche pas sous IE
				//$('#BoutonRemoveArticleFromSelection_'+p_ID).html('<span id="BoutonAddArticleToSelection_'+p_ID+'"><a title="Add to my selection" href="javascript:void(0);" onclick="AddArticleToSelection('+p_ID+', '+p_SmallSize+');"><img src="images/'+p_ImgPref+'addtoselection.png" /></a></span>');

        $('#BoutonAddArticleToSelection_'+p_ID).css('display', 'block');
        $('#BoutonRemoveArticleFromSelection_'+p_ID).css('display', 'none');
        
			}
			else
			{
				$('#SelectionArticle_'+p_ID).remove();
			}

	}});
}


//---------------------------------------------------------------------------------------------------------------------------
// Met à jour le texte "x items in your selection (page sélection seulement)
// et dans le menu latéral gauche.
// Dans la page de vue de la sélection, désactive les boutons "Print" et
// "Empty all" si la sélection est vide.
//---------------------------------------------------------------------------------------------------------------------------
function UpdateInterfaceForSelectionState(p_NbItems, p_FromSelectionList)
{
	nb = parseInt(p_NbItems);
	switch(nb)
	{
		case 0 : str = 'no item'; break;
		case 1 : str = '1 item'; break;
		default: str = p_NbItems + ' items';
	}
	
	if(p_FromSelectionList == 1)
	{
		$('#nav-selection-nb').html(str);

		if(p_NbItems == 0)
		{
			$('#BoutonEmptyArticleSelection').html('<img src="images/removeallfromselection_off.png" />');
			$('#BoutonPrintArticleSelection').html('<img src="images/printselection_off.png" />');
		}

    SetModifiedSelectionState(true);    
	}

	$('#menu-selection-nb').html(' ('+str+')');

  //Nom de la selection dans le menu
  //existingName = $("#AbonneSelectionID option[value='"+$('#PreviousAbonneSelectionID').val()+"']").text();
  //existingName = $("#AbonneSelectionID option[value='"+$('#AbonneSelectionID').val()+"']").text();
  existingName = $('#SelectionNameToShow').val();
  if(existingName != '') $('#menu_selection_name').html(existingName);

}

function SetModifiedSelectionState(p_Etat)
{
  if(p_Etat == false)
  {
    $('#BoutonSaveArticleSelection').html('<img src="images/saveselection_off.png" />');
    $('#IsModified').val(0);
  }
  else
  {
    // On ne regarde pas dans la session, on check direct dans l'interface...
    // Note: on ne vérifie plus si c'est empty ou pas, on sauve toujours
    /*isEmpty = $('#nav-selection-nb').html();
    if(IsEntier(isEmpty[0]) && isEmpty[0] != 0) isEmpty = false;
    else isEmpty = true;*/
    isEmpty = false;

    IsCurrentSelectionAlreadyExists = DoesCurrentSelectionAlreadyExists();
    
    /*IsCurrentSelectionAlreadyExists = $('#AbonneSelectionID').val();
    if(IsEntier(IsCurrentSelectionAlreadyExists[0]) && IsCurrentSelectionAlreadyExists[0] != 0) IsCurrentSelectionAlreadyExists = true;
    else IsCurrentSelectionAlreadyExists = false;*/
    
    html = '<a title="Save the current selection" href="javascript:void(0);" onclick="SaveCurrentSelection('+isEmpty+', '+IsCurrentSelectionAlreadyExists+')"><img src="images/saveselection.png" /></a>';
    $('#BoutonSaveArticleSelection').html(html);
    $('#IsModified').val(1);
    
  }
}

//---------------------------------------------------------------------------------------------------------------------------
function LoadSavedSelectionFromListe()
{
  $('#SelectionName').attr('disabled', 'disabled');
  $('#SelectionAction').val('load');
  $('#selectionform').submit();
}

function SaveCurrentSelection(p_IsEmpty, p_IsCurrentSelectionAlreadyExists)
{
 // alert(p_IsCurrentSelectionAlreadyExists);
  /*if(p_IsEmpty)
  {
    alert('You can\'t save an empty selection !');
  }
  else
  {*/
    // Si la sélection existe déjà en DB
    if(p_IsCurrentSelectionAlreadyExists)
    {
    //  alert('selection existe');
      $('#SelectionAction').val('update');
      $('#selectionform').submit();
    }
    // La sélection n'existe pas encore en DB (demande nom)
    else
    {
// alert('selection existe PAS');
      
      var name = prompt('Type a name for your selection', '');
      if(name != null)
      {    
        $('#SelectionName').val(name);
        $('#SelectionAction').val('save');
        $('#selectionform').submit();        
      }
    }
 /* } // check empty */
  
}

//-----------------------------------------------------------------------------------------------------------------
function CreateEmptySelectionWithoutPrompts()
{
  $('#AbonneSelectionID, #SelectionName').attr('disabled', 'disabled');
  $('#SelectionAction').val('new');
  $('#IsModified').val('0');
  $('#selectionform').submit();

  return;
}


//-----------------------------------------------------------------------------------------------------------------
function DeleteSelection()
{
  res = confirm('You are about to delete the current selection. Are you sure ?');
  if(res == true)
  {
    $('#SelectionName').attr('disabled', 'disabled');
    $('#SelectionAction').val('delete');
    $('#selectionform').submit();
  }
}

//-----------------------------------------------------------------------------------------------------------------
function CreateSaveUpdateSelection(p_Action)
{
  p_IsCurrentSelectionModified      = IsSelectionModified();
  p_IsCurrentSelectionAlreadyExists = DoesCurrentSelectionAlreadyExists();
  
  // Si sélection courante modifiée
  if(p_IsCurrentSelectionModified)
  {
    // Si elle existe déjà (elle a déjà un nom)
    if(p_IsCurrentSelectionAlreadyExists)
    {
      if(p_Action == 'load')
        promptTxt = 'Your current selection "'+existingName+'" has been modified. Would you like to save it before loading a new one ?';
      else if (p_Action == 'new')
        promptTxt = 'Your current selection "'+existingName+'" has been modified. Would you like to save it before creating a new one ?';
      
      res = confirm(promptTxt);

      if(res == true)
      {
          // si AbonneSelectionID non passé en GET, on le récupère depuis la session
          // pour updater la sélection précédente au changement
          if(p_Action == 'load') $('#AbonneSelectionID, #SelectionName').attr('disabled', 'disabled');
        
          $('#SelectionAction').val('update');
          $('#selectionform').submit();
      }
      else
      {
        if(p_Action == 'new') CreateEmptySelectionWithoutPrompts();
        else  if(p_Action == 'load') LoadSavedSelectionFromListe();
      }
    }
    // Si elle n'existe pas déjà (on demande un nom)
    else
    {
      if(p_Action == 'load')
        promptTxt = 'Your current selection has been modified. Would you like to save it before loading a new one ?';
      else if (p_Action == 'new')
        promptTxt = 'Your current selection has been modified. Would you like to save it before creating a new one ?';

      res = confirm(promptTxt);
      
      if(res == true)
      {
        var name = prompt('Type a name for your selection', '');
        if(name != null)
        {
          $('#SelectionName').val(name);
          $('#SelectionAction').val('save');
          $('#selectionform').submit();
        }
      }
      else
      {
        if(p_Action == 'new') CreateEmptySelectionWithoutPrompts();
        else  if(p_Action == 'load') LoadSavedSelectionFromListe();
      }
    }
  }
  // Si sélection courante non modifiée
  else
  {
    if(p_Action == 'new') CreateEmptySelectionWithoutPrompts();
    else  if(p_Action == 'load') LoadSavedSelectionFromListe();
  }

}


//----------------------------------------------------------------------------------------------------------------
function IsSelectionModified()
{
  if($('#IsModified').val() == 1) return true;
  else return false;
}

function DoesCurrentSelectionAlreadyExists()
{
 // IsCurrentSelectionAlreadyExists = $('#AbonneSelectionID').val();
  IsCurrentSelectionAlreadyExists = $('#PreviousAbonneSelectionID').val();

   // marche pas sous IE 9
  /*  if(IsEntier(IsCurrentSelectionAlreadyExists[0]) && IsCurrentSelectionAlreadyExists[0] != 0)
      IsCurrentSelectionAlreadyExists = true;
    else
      IsCurrentSelectionAlreadyExists = false;*/

     /* if(IsEntier(IsCurrentSelectionAlreadyExists[0]) && IsCurrentSelectionAlreadyExists[0] != 0)
      IsCurrentSelectionAlreadyExists = true;
    else
      IsCurrentSelectionAlreadyExists = false;*/

     if(IsEntier(IsCurrentSelectionAlreadyExists) && IsCurrentSelectionAlreadyExists != '0') IsCurrentSelectionAlreadyExists = true;
     else IsCurrentSelectionAlreadyExists = false;


  //alert('existe :'+IsCurrentSelectionAlreadyExists);
    
  return IsCurrentSelectionAlreadyExists;
}


