/******************************************************************************
*     @desc       MooTools scripts for Trefle's advanced search
*     @author     Robin Scherberich  
*     @copyright  (C) Nalis
******************************************************************************/

/**
* @desc       Toggle the advanced search div
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*/
function setAdvancedSearchScript()
{
  showAllCriterias();
  
	var clic = 1;
	
	var mySlide = new Fx.Slide('advancedSearchBloc');
	mySlide.hide();
	
	$('searchToggleLink').addEvent('click', function(e){
	  e = new Event(e);
	  
	  if(clic % 2)
	  {
        mySlide.slideIn();
        clic++;
	  }
	  else
	  {
        mySlide.slideOut();
	    clic++;
	  }
 
	  e.stop();
	});

  $('closeButton').addEvent('click', function(e){
    e = new Event(e);
    mySlide.slideOut();
    clic++;
    e.stop();
  });
  
  $('calqueul').addEvent('mouseup', function(e){
    e = new Event(e);
    mySlide.slideIn();
    clic++;
    e.stop();
  });

}

function check_content()
{
	$('search').submit();
}

/**
* @desc       Ask ajax to change the dynamic select of subcategory & co
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-04
*/
function showAllCriterias()
{
  generateDivStructure(true);
  if($('categorieSelect').value == 0)
  {
  	  showLocalizationInput();
  }
  else
  {
	  showSubcategoriesSelect($('categorieSelect').value);
  }
}

/**
* @desc       Send ajax request to generates the subcategory <select> element
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*
* @param      int     categoryId
*/
function showSubcategoriesSelect(categoryId)
{
  if(categoryId != 9)
  {
	  var url='index.php?do=get_subcategory_for_select&id='+categoryId;
	  var ajaxRequest = new Ajax(url,{method: 'get',encoding: 'utf-8', onSuccess: constructSubcatArray});
	  ajaxRequest.request();
	}
	else
	{
	 // cas de Job/CV
	 showLocalizationInput();
	}
}

/**
* @desc       Send ajax request to generates the subcategory <select> element
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*
* @param      int     categoryId
*/
//var waitResponse = 0;
var wait = 0;
function showLocalisationSelect(string, country_code, unique)
{
	if(wait == 0)
	{
		wait = 1;

		var url='/soundex.php?string='+string+'&country_code='+country_code+'&unique='+unique;
		var ajaxRequest = new Ajax(url,{method: 'get',encoding: 'utf-8', update: $('calqueLocalisation')});
		ajaxRequest.request();

		wait = 0;
	}
}

/**
* @desc       Send ajax request to generates the subcategory <select> element
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*
* @param      int     categoryId
*/
//var waitResponse = 0;
function hideLocalisationSelect()
{
	$('calqueLocalisation').style.display = 'none';
}

/**
* @desc       Parse ajax response to construct an array of its values
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*
* @param      String    textResponse
* @param      XML       xmlResponse
*/
function constructSubcatArray(textResponse, xmlResponse)
{
  var lengthTab = xmlResponse.getElementsByTagName("subcategory").length;
  var subcategoryNames = new Array();
  var subcategoryIds = new Array();
  
  for (var i=0; i<lengthTab; i++)
  {
    subcategoryNames[i] = xmlResponse.getElementsByTagName("name")[i].firstChild.nodeValue;
    subcategoryIds[i] = xmlResponse.getElementsByTagName("id")[i].firstChild.nodeValue;
  }
  var categoryId = xmlResponse.getElementsByTagName("category")[0].firstChild.nodeValue;
  
  generateSubcategorySelect(subcategoryNames, subcategoryIds, categoryId);
}

/**
* @desc       Generates the subcategory <select> element
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*
* @param      array   subcategoryNames
* @param      array   subcategoryIds
* @param      itn     categoryId
*/
function generateSubcategorySelect(subcategoryNames, subcategoryIds, categoryId)
{
  var numberOfSubcat = subcategoryIds.length;

 if($('divLabel1') != undefined)
 { 
	  var subcatDivLabel = document.createElement("div");
	  subcatDivLabel.setAttribute("id", "subcat_div_label");
	  subcatDivLabel.className = "divCellule";
	  $('divLabel1').appendChild(subcatDivLabel);
	  
	  var subcatDivInput = document.createElement("div");
	  subcatDivInput.setAttribute("id", "subcat_div_input");
	  subcatDivInput.className = "divCellule";
	  $('divInput1').appendChild(subcatDivInput);
  }
  
  if($('subcat_div_label') != undefined)
  {
	  var label = document.createElement("label");
	  label.setAttribute("for", "select_subcat");
	  label.innerHTML = "Sous-catégorie";
	  $('subcat_div_label').appendChild(label);
	  
	  var select = document.createElement("select");
	  select.id = "select_subcat";
	  select.setAttribute("name", "subcategory");
	  select.onchange = function(){ displayCriterias()};
	  
	  var option = document.createElement("option");
	  option.setAttribute("value", "all");
	  option.innerHTML = "- indifférent -";
	  select.appendChild(option);
	  
	  for(var i=0; i<numberOfSubcat; i++)
	  {
	    var option = document.createElement("option");
	    option.setAttribute("value", subcategoryIds[i]);
	    option.innerHTML = subcategoryNames[i];
	    select.appendChild(option);
	  }
	  
	  $('subcat_div_input').appendChild(select);
	}
	  
  /** pas super propre mais fonctionnel  **/
  showLocalizationInput();
  showCriterias($('categorieSelect').value);
  
  /*
  if(categoryId == 10)
  {
    showConditionSelect();
  }
  */
}

/**
* @desc       Generates the condition state
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-10
*/
function showConditionSelect()
{
  var conditionDivLabel = document.createElement("div");
  conditionDivLabel.setAttribute("id", "condition_div_label");
  conditionDivLabel.className = "divCellule";
  $('divLabel1').appendChild(conditionDivLabel);

  var label = document.createElement("label");
  label.setAttribute("for", "select_condition");
  label.innerHTML = "État";
  $('condition_div_label').appendChild(label);
  
  var conditionDivInput = document.createElement("div");
  conditionDivInput.setAttribute("id", "condition_div_input");
  conditionDivInput.className = "divCellule";
  $('divInput1').appendChild(conditionDivInput);
  
  var select = document.createElement("select");
  select.id = "select_condition";
  select.setAttribute("name", "condition");
  
  var option = document.createElement("option");
  option.setAttribute("value", "all");
  option.innerHTML = "- indifférent -";
  select.appendChild(option);
  
  var option = document.createElement("option");
  option.setAttribute("value", "neuf");
  option.innerHTML = "neuf";
  select.appendChild(option);
  
  var option = document.createElement("option");
  option.setAttribute("value", "occasion");
  option.innerHTML = "occasion";
  select.appendChild(option);
  
  $('condition_div_input').appendChild(select);
}

/**
* @desc       Clean or Build the div's structure
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-08
* @param      true (construct) or false (destruct)    action
*/
function generateDivStructure(action)
{
  if(action)
  {
    emptyHTML($("dynamicDiv"));
    generateLabelAndInputDiv();
  }
  else
  {
    emptyHTML($("dynamicDiv"));
  }
}

/**
* @desc       Generates the divs
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-08
*/

function generateLabelAndInputDiv()
{
  if($("dynamicDiv") != undefined)
  {
	  var divLabel1 = document.createElement("div");
	  divLabel1.setAttribute("id", "divLabel1");
	  divLabel1.className = "label";
	  $("dynamicDiv").appendChild(divLabel1);
	  
	  var divInput1 = document.createElement("div");
	  divInput1.setAttribute("id", "divInput1");
	  divInput1.className = "input";
	  $("dynamicDiv").appendChild(divInput1);
	  
	  var divLabel2 = document.createElement("div");
	  divLabel2.setAttribute("id", "divLabel2");
	  divLabel2.className = "label";
	  $("dynamicDiv").appendChild(divLabel2);
	  
	  var divInput2 = document.createElement("div");
	  divInput2.setAttribute("id", "divInput2");
	  divInput2.className = "input";
	  $("dynamicDiv").appendChild(divInput2);
  }
}

/**
* @desc       Add the localisation criteria
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-07
*/
function showLocalizationInput()
{
	if($('divLabel1') != undefined)
	{
  var localizationDivLabel = document.createElement("div");
  localizationDivLabel.setAttribute("id", "localization_div_label");
  localizationDivLabel.className = "divCellule";
  $('divLabel1').appendChild(localizationDivLabel);

  var localizationDivInput = document.createElement("div");
  localizationDivInput.setAttribute("id", "localization_div_input");
  localizationDivInput.className = "divCellule";
  $('divInput1').appendChild(localizationDivInput);

  var label = document.createElement("label");
  label.setAttribute("for", "input_localization");
  label.innerHTML = "Localisation";
  $('localization_div_label').appendChild(label);
  
  var input = document.createElement("input");
  input.id = "input_localization";
  input.type = "text";
  input.name ="localization";
  input.className ="localization";
  $('localization_div_input').appendChild(input);
  
  
  var localizationDivLabel2 = document.createElement("div");
  localizationDivLabel2.setAttribute("id", "localization_div_label2");
  localizationDivLabel2.className = "divCellule";
  $('divLabel1').appendChild(localizationDivLabel2);

  var localizationDivInput2 = document.createElement("div");
  localizationDivInput2.setAttribute("id", "localization_div_input2");
  localizationDivInput2.className = "divCellule";
  $('divInput1').appendChild(localizationDivInput2);

  var label2 = document.createElement("label");
  label2.setAttribute("for", "input_localization2");
  label2.innerHTML = "Rayon de";
  $('localization_div_label2').appendChild(label2);
  
  var input2 = document.createElement("input");
  input2.id = "input_localization2";
  input2.type = "text";
  input2.name ="proximity";
  input2.className ="localization";
  input2.style.width = "25px";
  $('localization_div_input2').appendChild(input2);
  
  $('localization_div_input2').innerHTML += '<div class="km">Km</div>'; 
	}
}


function showCriterias(categoryId)
{
  var url='index.php?do=get_category_criterias&id='+categoryId;
  var ajaxRequest = new Ajax(url,{method: 'get',encoding: 'utf-8', onSuccess: constructCatCriteriasArray});
  ajaxRequest.request();
}

/**
* @desc       Parse ajax response to construct an array of its values
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-07
*
* @param      String    textResponse
* @param      XML       xmlResponse
*/
function constructCatCriteriasArray(textResponse, xmlResponse)
{
  var lengthTab = xmlResponse.getElementsByTagName("criteria").length;
  var criteriasIds = new Array();
  var criteriasNames = new Array();
  
  for (var i=0; i<lengthTab; i++)
  {
    criteriasIds[i] = xmlResponse.getElementsByTagName("id")[i].firstChild.nodeValue;
    criteriasNames[i] = xmlResponse.getElementsByTagName("name")[i].firstChild.nodeValue;
  }
  
  generateCatCriterias(criteriasIds, criteriasNames);
}

/**
* @desc       Generates dynamic criterias for a category
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-07
*
* @param      array   criteriasIds
* @param      array   criteriasNames
*/
function generateCatCriterias(criteriasIds, criteriasNames)
{
  var numberOfCatCriterias = criteriasIds.length;
  
  for(var i=0; i<numberOfCatCriterias; i++)
  {
  	if($('divLabel1') != undefined)
  	{
	    var criteriaDivLabel = document.createElement("div");
	    criteriaDivLabel.setAttribute("id", "criteria_div_label"+i);
	    criteriaDivLabel.className = "divCellule";
	    $('divLabel1').appendChild(criteriaDivLabel);
    }
    
    if($('divInput1') != undefined)
  	{
	    var criteriaDivInput = document.createElement("div");
	    criteriaDivInput.setAttribute("id", "criteria_div_input"+i);
	    criteriaDivInput.className = "divCellule";
	    $('divInput1').appendChild(criteriaDivInput);
	}
	
	if($("criteria_div_label"+i) != undefined)
  	{
	  var label = document.createElement("label");
	  label.setAttribute("for", "cat_criteria_"+criteriasIds[i]+"_min");
	  label.innerHTML = criteriasNames[i];
	  $("criteria_div_label"+i).appendChild(label);
	}

    if($("criteria_div_input"+i) != undefined)
  	{
	    var min_max = document.createElement("div")
	    min_max.className = "cat_min_max";
	    min_max.setAttribute("id", "cat_min_max_"+i);
	    $("criteria_div_input"+i).appendChild(min_max);
	}

	if($('cat_min_max_'+i) != undefined)
	{
	    insertSpanString($('cat_min_max_'+i), 'De');
	
	    var inputMin = document.createElement("input");
	    inputMin.type = "text";
	    inputMin.className = "min";
	    inputMin.id = "cat_criteria_"+criteriasIds[i]+"_min";
	    inputMin.name = "cat_criteria_"+criteriasIds[i]+"_min";
	    $("cat_min_max_"+i).appendChild(inputMin);
	    
	    insertSpanString($('cat_min_max_'+i), 'à');
	    
	    var inputMax = document.createElement("input");
	    inputMax.type = "text";
	    inputMax.className = "max";
	    inputMax.id = "cat_criteria_"+criteriasIds[i]+"_max";
	    inputMax.name = "cat_criteria_"+criteriasIds[i]+"_max";
	    $("cat_min_max_"+i).appendChild(inputMax);
	 }
  }
}

/**
* @desc       Send ajax request to check if this subcategory has criterias
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-04
*/
function displayCriterias()
{
  emptyHTML($('divLabel2'));
  emptyHTML($('divInput2'));

  var url='index.php?do=get_criterias&id='+ $('select_subcat').value;
  var ajaxRequest = new Ajax(url,{method: 'get',encoding: 'utf-8', onSuccess: constructCriteriasArray});
  ajaxRequest.request();
}

/**
* @desc       Parse ajax response to construct an array of its values
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*
* @param      String    textResponse
* @param      XML       xmlResponse
*/
function constructCriteriasArray(textResponse, xmlResponse)
{
  var lengthTab = xmlResponse.getElementsByTagName("criteria").length;
  var criteriasIds = new Array();
  var criteriasNames = new Array();
  var criteriasInputType = new Array();
  var criteriasInputValue = new Array();
  
  for (var i=0; i<lengthTab; i++)
  {
    criteriasIds[i] = xmlResponse.getElementsByTagName("id")[i].firstChild.nodeValue;
    criteriasNames[i] = xmlResponse.getElementsByTagName("name")[i].firstChild.nodeValue;
    var input = xmlResponse.getElementsByTagName("input")[i];
    
    criteriasInputType[i] = xmlResponse.getElementsByTagName("type")[i].firstChild.nodeValue;
    
    var j=0;
    while (input.getElementsByTagName("value")[j])
    {
      if(!criteriasInputValue[i])
      {
        criteriasInputValue[i] = new Array();
      }
      criteriasInputValue[i][j] = input.getElementsByTagName("value")[j].firstChild.nodeValue;
      j++;
    }
  }
  
  generateCriterias(criteriasIds, criteriasNames, criteriasInputType, criteriasInputValue);
}

/**
* @desc       Generates dynamic criterias
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-03
*
* @param      array   criteriasIds
* @param      array   criteriasNames
* @param      array   criteriasInputType
* @param      array   criteriasInputValues
*/
function generateCriterias(criteriasIds, criteriasNames, criteriasInputType, criteriasInputValues)
{
  var numberOfCriterias = criteriasIds.length;
  for( i=0; i<numberOfCriterias; i++)
  {
    if(criteriasInputType[i] == 1)
    {
      var subcatCriteriaDivLabel = document.createElement("div");
      subcatCriteriaDivLabel.setAttribute("id", "subcat_criteria_div_label"+i);
      if(i == 0)
      {
        subcatCriteriaDivLabel.className = "divCelluleClear";
      }
      else
      {
        subcatCriteriaDivLabel.className = "divCellule";
      }
      $('divLabel2').appendChild(subcatCriteriaDivLabel);
    
      var label = document.createElement("label");
      label.setAttribute("for", "subcat_criteria_"+criteriasIds[i]);
      label.innerHTML = criteriasNames[i];
      $("subcat_criteria_div_label"+i).appendChild(label);
       
      var subcatCriteriaDivInput = document.createElement("div");
      subcatCriteriaDivInput.setAttribute("id", "subcat_criteria_div_input"+i);
      if(i == 0)
      {
        subcatCriteriaDivInput.className = "divCelluleClear";
      }
      else
      {
        subcatCriteriaDivInput.className = "divCellule";
      }
      $('divInput2').appendChild(subcatCriteriaDivInput);
      
      var select = document.createElement("select");
      select.id = "subcat_criteria_"+criteriasIds[i];
      select.name = "subcat_criteria_"+criteriasIds[i];
      
      var option = document.createElement("option");
      option.value = "all";
      option.innerHTML = "- indifférent -";
      select.appendChild(option);
      
      var numberOfOptions = criteriasInputValues[i].length
      for(var j=0; j<numberOfOptions; j++)
      {
        var option = document.createElement("option");
        option.value = criteriasInputValues[i][j];
        option.innerHTML = criteriasInputValues[i][j];
        select.appendChild(option);
      }
      
      $("subcat_criteria_div_input"+i).appendChild(select);
    }
    else
    {
      var subcatCriteriaDivLabel = document.createElement("div");
      subcatCriteriaDivLabel.setAttribute("id", "subcat_criteria_div_label"+i);
      if(i == 0)
      {
        subcatCriteriaDivLabel.className = "divCelluleClear";
      }
      else
      {
        subcatCriteriaDivLabel.className = "divCellule";
      }
      $('divLabel2').appendChild(subcatCriteriaDivLabel);
      
	    var label = document.createElement("label");
	    label.setAttribute("for", "subcat_criteria_"+criteriasIds[i]+"_min");
	    label.innerHTML = criteriasNames[i];
	    $("subcat_criteria_div_label"+i).appendChild(label);
	    
	    var subcatCriteriaDivInput = document.createElement("div");
      subcatCriteriaDivInput.setAttribute("id", "subcat_criteria_div_input"+i);
      if(i == 0)
      {
        subcatCriteriaDivInput.className = "divCelluleClear";
      }
      else
      {
        subcatCriteriaDivInput.className = "divCellule";
      }
      $('divInput2').appendChild(subcatCriteriaDivInput);
	    
	    var min_max = document.createElement("div")
	    min_max.className = "min_max";
	    min_max.setAttribute("id", "min_max_"+i);
	    $("subcat_criteria_div_input"+i).appendChild(min_max);
	    
	    insertSpanString($('min_max_'+i), 'De');
	
	    var inputMin = document.createElement("input");
	    inputMin.type = "text";
	    inputMin.className = "min";
	    inputMin.id = "subcat_criteria_"+criteriasIds[i]+"_min";
	    inputMin.name = "subcat_criteria_"+criteriasIds[i]+"_min";
	    $("min_max_"+i).appendChild(inputMin);
	    
	    insertSpanString($('min_max_'+i), 'à');
	    
	    var inputMax = document.createElement("input");
      inputMax.type = "text";
      inputMax.className = "max";
      inputMax.id = "subcat_criteria_"+criteriasIds[i]+"_max";
      inputMax.name = "subcat_criteria_"+criteriasIds[i]+"_max";
      $("min_max_"+i).appendChild(inputMax);
    }
  } // end for
}

/**
* @desc       Insert the string in a <span> into the element
* @param      DOM   element
* @param      String string
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-08
*/
function insertSpanString(element, string)
{
	if(element != undefined)
	{
		var span = document.createElement("span");
		span.innerHTML = string;
		element.appendChild(span);
	}
}


/**
* @desc       Empty innerHTML of a DOM element
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-04
* @param      DOM element
*/
function emptyHTML(element)
{
  if(element != undefined)
  {
  	element.innerHTML = "";
  }
}

/**
* @desc       Advanced removeChild function
* @author     Robin Scherberich
* @copyright  (C) Nalis
* @version    2008-04-09
* @param      node
*/
function removeNode(node)
{
  node.parentNode.removeChild(node);
}

/*************** SELECT ***************/

function validAndHide(txt, obj, input, select)
{
	$('subcategorieSelect').value = 0;
	document.getElementById(input).value = txt;
	obj.parentNode.parentNode.parentNode.style.display = 'none';
	document.getElementById(select).innerHTML = obj.innerHTML;
}

function cmdSelect()
{
	setTimeout("altern()",1);
}

function altern()
{
	var calque = $('calqueSelect');
	if(calque.style.display !== 'block')
	{ calque.style.display = 'block'; }
	else
	{ calque.style.display = 'none'; }
}

function hideSelect()
{
	if($('calqueSelect').style.display !== "none")
	{
		$('calqueSelect').style.display = "none";
	}
}

function setDisplayNone(element)
{
	element.style.display = "none";
}

/* Guy */
function showSubcategories(id)
{
	if((id > 0) && (id != 9))
	{
		// On affiche le div principal des sous-categories
		$('calqueulsub').style.display='block';
		// On cache toutes les sous-categories
		var arrSubcategories = new Array('10','3','11','20','5','19','1','6');
		for(i=0;i<arrSubcategories.length;i++){
	  	eval("$('calqueulsub_" + arrSubcategories[i] +"').style.display='none';");
		}
		// On affiche la sous-categorie demandee	
		eval("$('calqueulsub_" + id +"').style.display='block';");
	}
	else
	{
		// On cache le div principal des sous-categories (toutes les catégories)
		$('calqueulsub').style.display='none';
	}
}
function validAndHideSubCategories(txt, obj, input, select)
{
	document.getElementById(input).value = txt;
	obj.parentNode.parentNode.parentNode.parentNode.style.display = 'none';
	document.getElementById(select).innerHTML = obj.innerHTML;
}

window.addEvent('domready', function() {setDisplayNone($('calqueSelect'));});
