
var MenuActFamSfam = jQuery.Class.create({
  init: function() {
    this.currentAct = null;
		this.currentActSelected = null;
  
    this.actMenuDiv = $('#cat_menu_act_div');
    this.actMenuUl = $('ul#cat_menu_act');
    this.actMenuList = this.actMenuUl.children();
    
    this.actMenuListByCode = [];
    this.famMenusList = [];
		
		this.actMenuUl.mouseleave(function(event) {
			this.mouseLeftElem(event.pageX, event.pageY);
		}.bind(this));
    
    this.actMenuList.each(function(index, actLI) {
      var code = actLI.id.substring(8);
      this.actMenuListByCode[code] = actLI;
      this.famMenusList[code] = new MenuFamSfam(code, this);
      $(actLI).mouseover(function() {
        this.actMenuOver(code);
      }.bind(this));
      $(actLI).click(function() {
        this.actMenuClick(code);
      }.bind(this));
    }.bind(this));
  },
  
  actMenuOver: function(code) {
    this.moveActMenuTo(code);
    //this.hideSfamMenu();
  },
  
  moveActMenuTo: function(code) {
    if (this.currentAct == code) {
      return;
    }
    if (this.famMenusList[this.currentAct] != undefined) {
      this.famMenusList[this.currentAct].hide();
    }
    if (this.famMenusList[code] != undefined) {
      this.famMenusList[code].show();
    }
    if (this.actMenuListByCode[this.currentAct] != undefined) {
      $(this.actMenuListByCode[this.currentAct]).removeClass('selected');
    }
    if (this.actMenuListByCode[code] != undefined) {
      $(this.actMenuListByCode[code]).addClass('selected');
    }
    this.currentAct = code;
  },
	
  getActiviteLabelFromCode: function(code) {
    if (this.actMenuListByCode[code] != undefined) {
      return $($(this.actMenuListByCode[code]).children()[0]).html();
    }
    return ("");
  },
  
  getSelectedActiviteLabel: function() {
    return this.getActiviteLabelFromCode(this.currentAct);
  },
	
	setSelected: function(code) {
		this.moveActMenuTo(code);
		this.currentActSelected = code;
	},
	
  setSelectedTree: function(act, fam, sfam) {
		this.setSelected(act);
		if (this.famMenusList[this.currentAct] != undefined) {
			this.famMenusList[this.currentAct].setSelectedTree(fam, sfam);
	  }
	},
	
	actMenuClick: function(code) {
		if (catalogueNav != undefined && catalogueNav != null) {
			catalogueNav.navTo(code);
	  }
		this.currentActSelected = code;
	},
	
	mouseLeftElem: function(mouseX, mouseY) {
		// Are we still on our menu ?
    if (this.isOverMeOrMyChildren(mouseX, mouseY) == true) {
	    // We do nothing.
		  return;
    }
		// If we get there, it means that we got out the menu.
		this.mouseLeaveMenu();
	},
	
  isOverMeOrMyChildren: function(mouseX, mouseY) {
    // First, we need to know our own position.
    var offset = this.actMenuUl.offset();
    if (mouseX < offset.left || mouseX >= offset.left + this.actMenuUl.width()
        || mouseY < offset.top || mouseY >= offset.top + this.actMenuUl.height()) {
          // We need to test our children.
          if (this.famMenusList[this.currentAct] != undefined) {
            if (this.famMenusList[this.currentAct].isOverMeOrMyChildren(mouseX, mouseY) == true) {
              return true;
           } else {
             return false;
           }
          } else {
            return false;
          }
    } else {
      return true;
    }
    return false;
  },
	
	getCurrentSelectionsLabels: function() {
		var thisLabel = this.getSelectedActiviteLabel();
		if (this.famMenusList[this.currentAct] != undefined) {
		  var labels = this.famMenusList[this.currentAct].getCurrentSelectionsLabels();
		  labels['act'] = thisLabel;
	  } else {
			labels = {'act': thisLabel, 'fam': null, 'sfam': null};
		}
		
		return labels;
	},
	
	getCurrentSelectionsCodesAndLabels: function() {
		var thisCode = this.currentAct;
    var thisLabel = this.getSelectedActiviteLabel();
    if (this.famMenusList[this.currentAct] != undefined) {
      var codesAndLabels = this.famMenusList[this.currentAct].getCurrentSelectionsCodesAndLabels();
      codesAndLabels['act'] = {'code': thisCode, 'label': thisLabel};
    } else {
      codesAndLabels = {'act': {'code': thisCode, 'label': thisLabel}, 'fam': null, 'sfam': null};
    }
		
		return codesAndLabels;
	},
	
  mouseLeaveMenu: function() {
    this.moveActMenuToSelected();
  },
	
	moveActMenuToSelected: function() {
		if (this.currentActSelected != null) {
			this.moveActMenuTo(this.currentActSelected);
			if (this.famMenusList[this.currentActSelected] != undefined) {
	  	  this.famMenusList[this.currentActSelected].moveFamMenuToSelected();
	    }
		} else {
			this.moveActMenuToNone();
		}
	},
	
	moveActMenuToNone: function() {
    if (this.famMenusList[this.currentAct] != undefined) {
      this.famMenusList[this.currentAct].hide();
    }
    if (this.actMenuListByCode[this.currentAct] != undefined) {
      $(this.actMenuListByCode[this.currentAct]).removeClass('selected');
    }
    this.currentAct = null;
	},
	
	setCurrentOverAsSelected: function() {
		this.currentActSelected = this.currentAct;
	},
	
	getCurrentCode: function() {
		return this.currentAct;
	}
});

var MenuFamSfam = jQuery.Class.create({
  init: function(actCode, parent) {
    this.currentFam = null;
		this.currentFamSelected = null;
		
		this.parent = parent;
  
    this.famMenuDiv = $('#cat_menu_fam_div_'+actCode);
    this.famMenuUl = $(this.famMenuDiv.children()[0]);
    this.famMenuList = this.famMenuUl.children();
    
    this.famMenuListByCode = [];
    this.sfamMenusList = [];
		
		this.famMenuUl.mouseleave(function(event) {
      this.mouseLeftElem(event.pageX, event.pageY);
    }.bind(this));
    
    this.famMenuList.each(function(index, famLI) {
      var code = famLI.id.substring(8);
      this.famMenuListByCode[code] = famLI;
      this.sfamMenusList[code] = new MenuSfam(code, this);
      $(famLI).mouseover(function() {
        this.famMenuOver(code);
      }.bind(this));
      $(famLI).click(function() {
        this.famMenuClick(code);
      }.bind(this));
    }.bind(this));
  },
  
  show: function() {
    //this.famMenuDiv.fadeIn(300);
    this.famMenuDiv.css('display', 'block');
  },
  
  hide: function() {
    this.moveFamMenuTo(null);
    this.famMenuDiv.css('display', 'none');
    //this.famMenuDiv.fadeOut(300);
    
  },
  
  famMenuOver: function(code) {
    this.moveFamMenuTo(code);
  },
  
  moveFamMenuTo: function(code) {
    if (this.currentFam == code) {
      return;
    }
    if (this.sfamMenusList[this.currentFam] != undefined) {
      this.sfamMenusList[this.currentFam].hide();
    }
    if (this.sfamMenusList[code] != undefined) {
			// Let's get our LI top position :
			var minBottomPos = 0;
			if (this.famMenuListByCode[code] != undefined) {
				var famLI = this.famMenuListByCode[code];
        var pos = $(famLI).position();
				var minBottomPos = pos.top + $(famLI).height();
			}
      this.sfamMenusList[code].show(minBottomPos);
    }
    if (this.famMenuListByCode[this.currentFam] != undefined) {
      $(this.famMenuListByCode[this.currentFam]).removeClass('selected');
    }
    if (this.famMenuListByCode[code] != undefined) {
      $(this.famMenuListByCode[code]).addClass('selected');
			/*$($(this.famMenuListByCode[code]).children()[0]).css('display', 'none');
			$($(this.famMenuListByCode[code]).children()[0]).css('display', 'block');*/
    }
    this.currentFam = code;
  },
	
  getFamilleLabelFromCode: function(code) {
    if (this.famMenuListByCode[code] != undefined) {
      return $($(this.famMenuListByCode[code]).children()[0]).html();
    }
    return ("");
  },
	
  getCurrentSelectionsLabels: function() {
    var thisLabel = this.getSelectedFamilleLabel();
		var childLabel = null;
		if (this.sfamMenusList[this.currentFam] != undefined) {
			childLabel = this.sfamMenusList[this.currentFam].getSelectedSousFamilleLabel();
	  }
		return {'fam': thisLabel, 'sfam': childLabel};
  },
	
	getCurrentSelectionsCodesAndLabels: function() {
		var thisCode = this.currentFam;
		var thisLabel = this.getSelectedFamilleLabel();
    if (this.sfamMenusList[this.currentFam] != undefined) {
      var childCodeAndLabel = this.sfamMenusList[this.currentFam].getSelectedSousFamilleCodeAndLabel();
    }
		return {'fam': {'code': thisCode, 'label': thisLabel}, 'sfam': childCodeAndLabel};
	},
	
	getSelectedFamilleLabel: function() {
		return this.getFamilleLabelFromCode(this.currentFam);
	},
	
  getActiviteLabel: function() {
    return this.parent.getSelectedActiviteLabel();
  },
	
  setSelected: function(code) {
    this.moveFamMenuTo(code);
    this.currentFamSelected = code;
  },
  
  setSelectedTree: function(fam, sfam) {
    this.setSelected(fam);
    if (this.sfamMenusList[this.currentFam] != undefined) {
      this.sfamMenusList[this.currentFam].setSelected(sfam);
    }
  },
	
  famMenuClick: function(code) {
    if (catalogueNav != undefined && catalogueNav != null) {
			var parentCode = this.parent.getCurrentCode();
      catalogueNav.navTo(parentCode+'/'+code);
    }
    this.currentFamSelected = code;
		this.parent.setCurrentOverAsSelected();
  },
	
	isOverMeOrMyChildren: function(mouseX, mouseY) {
		// First, we need to know our own position.
		var offset = this.famMenuUl.offset();
		if (mouseX < offset.left || mouseX >= offset.left + this.famMenuUl.width()
		    || mouseY < offset.top || mouseY >= offset.top + this.famMenuUl.height()) {
					// We need to test our children.
          if (this.sfamMenusList[this.currentFam] != undefined) {
						if (this.sfamMenusList[this.currentFam].isOverMe(mouseX, mouseY) == true) {
				      return true;
			     } else {
					 	 return false;
					 }
          } else {
						return false;
					}
		} else {
			return true;
		}
		return false;
	},
	
  mouseLeftElem: function(mouseX, mouseY) {
    this.parent.mouseLeftElem(mouseX, mouseY);
  },
	
  moveFamMenuToSelected: function() {
    if (this.currentFamSelected != null) {
      this.moveFamMenuTo(this.currentFamSelected);
    } else {
      this.moveFamMenuToNone();
    }
  },
  
  moveFamMenuToNone: function() {
    if (this.sfamMenusList[this.currentFam] != undefined) {
      this.sfamMenusList[this.currentFam].hide();
    }
    if (this.famMenuListByCode[this.currentFam] != undefined) {
      $(this.famMenuListByCode[this.currentFam]).removeClass('selected');
    }
    this.currentFam = null;
  },
	
  setCurrentOverAsSelected: function() {
    this.currentFamSelected = this.currentFam;
		this.parent.setCurrentOverAsSelected();
  },
	
  getCurrentCode: function() {
    return this.currentFam;
  }
});

var MenuSfam = jQuery.Class.create({
  init: function(sfamCode, parent) {
    this.currentSfam = null;
		this.currentSfamSelected = null;
		
		this.parent = parent;
  
    this.sfamMenuDiv = $('#cat_menu_sfam_div_'+sfamCode);
    this.sfamMenuUl = $(this.sfamMenuDiv.children()[0]);
    this.sfamMenuList = this.sfamMenuUl.children();
    
    this.sfamMenuListByCode = [];
		
    this.sfamMenuUl.mouseleave(function(event) {
      this.mouseLeftElem(event.pageX, event.pageY);
    }.bind(this));
    
    this.sfamMenuList.each(function(index, sfamLI) {
      var code = sfamLI.id.substring(9);
      this.sfamMenuListByCode[code] = sfamLI;
      $(sfamLI).click(function() {
        this.sfamMenuClick(code);
      }.bind(this));
    }.bind(this));
  },
  
  show: function(minBottomPos) {
		if (minBottomPos > 0) {
      var pos = this.sfamMenuUl.position();
			var paddingTop = parseInt(this.sfamMenuUl.css('padding-top'));
      var curBottomPos = pos.top + this.sfamMenuUl.height() + paddingTop;
			//alert(minBottomPos+" : "+curBottomPos);
			if (curBottomPos < minBottomPos) {
				this.sfamMenuUl.css('padding-top', ''+((minBottomPos - curBottomPos + 4))+'px');
			}
		}
    this.sfamMenuDiv.css('visibility', 'visible');
  },
  
  hide: function() {
    this.sfamMenuDiv.css('visibility', 'hidden');
    this.loadSfamDatas(null);
  },
	
	moveSfamMenuTo: function(code) {
    if (this.sfamMenuListByCode[this.currentSfam] != undefined) {
      $(this.sfamMenuListByCode[this.currentSfam]).removeClass('selected');
    }
    if (this.sfamMenuListByCode[code] != undefined) {
      $(this.sfamMenuListByCode[code]).addClass('selected');
    }
    this.currentSfam = code;
	},
  
  sfamMenuClick: function(code) {
		/*this.currentSfamSelected = code;
    this.parent.setCurrentOverAsSelected();
    this.loadSfamDatas(code);
		this.moveSfamMenuTo(code);*/
		
		
    if (catalogueNav != undefined && catalogueNav != null) {
      var parentCode = this.parent.getCurrentCode();
			var grandParentCode = this.parent.parent.getCurrentCode();
			if (code == null || code == '') {
				catalogueNav.navTo(grandParentCode+'/'+parentCode);
			} else {
        catalogueNav.navTo(grandParentCode+'/'+parentCode+'/'+code);
			}
    }
    this.currentSfamSelected = code;
    this.parent.setCurrentOverAsSelected();
  },
  
  loadSfamDatas: function(code) {
    if (this.currentSfam == code) {
      //return;
    }
    if (catContent != undefined && catContent != null && code != null) {
      catContent.loadContent('/catalogue/ajaxListProds?sous_famille_code='+code);
      if (catalogueTitle != undefined && catalogueTitle != null) {
        catalogueTitle.setActFamSfam(this.getActiviteLabel(), this.getFamilleLabel(), '');
        //catalogueTitle.setMainTitle(this.getSousFamilleLabelFromCode(code));
				catalogueTitle.setMainTitle('');
      }
    }
    if (catalogueTitle != undefined && catalogueTitle != null) {
      //catalogueTitle.setMainTitle(this.getSousFamilleLabelFromCode(code));
			catalogueTitle.setMainTitle('');
    }
  },
  
  getSousFamilleLabelFromCode: function(code) {
    if (this.sfamMenuListByCode[code] != undefined) {
      return $($(this.sfamMenuListByCode[code]).children()[0]).html();
    }
    return ("");
  },
	
	getSelectedSousFamilleLabel: function() {
		return this.getSousFamilleLabelFromCode(this.currentSfam);
	},
	
	getSelectedSousFamilleCodeAndLabel: function() {
		thisCode = this.currentSfam;
		thisLabel = this.getSelectedSousFamilleLabel();
		
		return {'code': thisCode, 'label': thisLabel};
	},
	
	getFamilleLabel: function() {
		return this.parent.getSelectedFamilleLabel();
	},
	
  getActiviteLabel: function() {
    return this.parent.getActiviteLabel();
  },
	
  setSelected: function(code) {
    this.moveSfamMenuTo(code);
    this.currentSfamSelected = code;
  },
	
  isOverMe: function(mouseX, mouseY) {
    // First, we need to know our own position.
    var offset = this.sfamMenuUl.offset();
		var paddingTop = parseInt(this.sfamMenuUl.css('padding-top'));
		var height = this.sfamMenuUl.height() + paddingTop;
		//alert(offset.left+" - "+offset.top+" - "+this.sfamMenuUl.width()+" - "+this.sfamMenuUl.height());
    if (mouseX < offset.left || mouseX >= offset.left + this.sfamMenuUl.width()
        || mouseY < offset.top || mouseY >= offset.top + height) {
					return false;
    } else {
      return true;
    }
    return false;
  },
	
	mouseLeftElem: function(mouseX, mouseY) {
		this.parent.mouseLeftElem(mouseX, mouseY);
	},
	
  moveSfamMenuToSelected: function() {
    if (this.currentSfamSelected != null) {
      this.moveSfamMenuTo(this.currentSfamSelected);
    } else {
      this.moveSfamMenuToNone();
    }
  },
  
  moveSfamMenuToNone: function() {
    if (this.sfamMenuListByCode[this.currentSfam] != undefined) {
      $(this.sfamMenuListByCode[this.currentSfam]).removeClass('selected');
    }
    this.currentSfam = null;
  },
  
  setCurrentOverAsSelected: function() {
    this.currentSfamSelected = this.currentSfam;
  }
});

var CatalogueTitle = jQuery.Class.create({
  init: function() {
		this.pathDiv = $('#catalogue_path');
    this.mainTitleDiv = $('#catalogue_main_title');
		
		this.pathActSeparator = $('#cat_title_separator_act');
		this.pathFamSeparator = $('#cat_title_separator_fam');
		this.pathSfamSeparator = $('#cat_title_separator_sfam');
		
		this.pathAct = $('#cat_title_act');
		this.pathFam = $('#cat_title_fam');
		this.pathSfam = $('#cat_title_sfam');
  },
  
  setMainTitle: function(main_title) {
    if (main_title == this.mainTitleDiv.html()) {
      return;
    }
    this.mainTitleDiv.fadeOut(100, function() {
        this.mainTitleDiv.html(main_title);
        this.mainTitleDiv.fadeIn(250);
      }.bind(this));
  },
	
	refresh: function() {
		// Thanks to IE
		var content = $('#catalogue_path').html();
		this.pathDiv.html('');
		this.pathDiv.html(content);
		
    this.pathActSeparator = $('#cat_title_separator_act');
    this.pathFamSeparator = $('#cat_title_separator_fam');
    this.pathSfamSeparator = $('#cat_title_separator_sfam');
    
    this.pathAct = $('#cat_title_act');
    this.pathFam = $('#cat_title_fam');
    this.pathSfam = $('#cat_title_sfam');
	},
	
  setActFamSfamWithCodes: function(actLabel, actCode, famLabel, famCode, sfamLabel, sfamCode) {
		//this.setActFamSfam(actLabel, famLabel, sfamLabel);
		this.setActLabelAndURL(actLabel, actCode);
		this.setFamLabelAndURL(famLabel, actCode+'/'+famCode);
		this.setSfamLabelAndURL(sfamLabel, actCode+'/'+famCode+'/'+sfamCode);
		this.refresh();
	},
	
	setActFamSfam: function(act, fam, sfam) {
		this.setAct(act);
		this.setFam(fam);
		this.setSfam(sfam);
		this.refresh();
	},
	
	setAct: function(act) {
		if (act == null || trim(act) == '') {
			this.pathActSeparator.css('display', 'none');
			this.pathAct.html('');
		} else {
			this.pathActSeparator.css('display', 'inline');
      this.pathAct.html(act);
		}
	},
	
	setActLabelAndURL: function(act, nav_url) {
    if (act == null || trim(act) == '') {
      this.pathActSeparator.css('display', 'none');
      this.pathAct.html('');
			this.pathAct[0].href='#';
    } else {
      this.pathActSeparator.css('display', 'inline');
      this.pathAct.html(act);
			this.pathAct[0].href="/catalogue#"+nav_url;
    }
	},
	
	setFam: function(fam) {
    if (fam == null || trim(fam) == '') {
      this.pathFamSeparator.css('display', 'none');
      this.pathFam.html('');
    } else {
      this.pathFamSeparator.css('display', 'inline');
      this.pathFam.html(fam);
    }
  },
	
  setFamLabelAndURL: function(fam, nav_url) {
    if (fam == null || trim(fam) == '') {
      this.pathFamSeparator.css('display', 'none');
      this.pathFam.html('');
      this.pathFam[0].href='#';
    } else {
      this.pathFamSeparator.css('display', 'inline');
      this.pathFam.html(fam);
      this.pathFam[0].href="/catalogue#"+nav_url;
    }
  },
	
	setSfam: function(sfam) {
    if (sfam == null || trim(sfam) == '') {
      this.pathSfamSeparator.css('display', 'none');
      this.pathSfam.html('');
    } else {
      this.pathSfamSeparator.css('display', 'inline');
      this.pathSfam.html(sfam);
    }
  },
	
  setSfamLabelAndURL: function(sfam, nav_url) {
    if (sfam == null || trim(sfam) == '') {
      this.pathSfamSeparator.css('display', 'none');
      this.pathSfam.html('');
      this.pathSfam[0].href='#';
    } else {
      this.pathSfamSeparator.css('display', 'inline');
      this.pathSfam.html(sfam);
      this.pathSfam[0].href="/catalogue#"+nav_url;
    }
  }
});

var CatalogueSearch = jQuery.Class.create({
  init: function() {
		this.motsClesInput = $('#search_mot_cle');
		this.referenceInput = $('#search_reference');
		this.longueurInput = $('#search_longueur');
		this.largeurInput = $('#search_largeur');
		this.hauteurInput = $('#search_hauteur');
		
		this.actSelect = $('#search_activite');
		this.famSelectList = $('.search_famille');
		this.sfamSelectList = $('.search_sous_famille');
		
		this.form = $('#advanced_search_form');
		
		this.actSelect.change(function(event) {
			this.actSelectChange();
		}.bind(this));
		
    this.famSelectList.each(function(index, elem) {
			$(elem).change(function(event) {
				this.famSelectChange(elem);
			}.bind(this));
		}.bind(this));
		
		this.lnk = $('#search_link');
		this.lnk.click(function(event) {
			this.search();
		}.bind(this));
		
		this.form.submit(function(event) {
			this.search();
			return false;
		}.bind(this));
  },
	
	actSelectChange: function() {
		var newVal = this.actSelect[0].value;
		this.famSelectList.each(function(index, elem) {
			if ((newVal == '' && elem.id == 'search_famille_empty') || elem.id == 'search_famille_'+newVal) {
				$(elem).css('display', 'inline');
				elem.value = '';
				this.famSelectChange(elem);
			} else {
				$(elem).css('display', 'none');
			}
		}.bind(this));
	},
	
	famSelectChange: function(famSelect) {
		if (famSelect == null) {
			return;
		}
		var newVal = famSelect.value;
    this.sfamSelectList.each(function(index, elem) {
      if ((newVal == '' && elem.id == 'search_sous_famille_empty') || elem.id == 'search_sous_famille_'+newVal) {
        $(elem).css('display', 'inline');
        elem.value = '';
      } else {
        $(elem).css('display', 'none');
      }
    }.bind(this));
	},
	
	getMotsCles: function() {
		var val = this.motsClesInput[0].value;
		val = trim(val);
		if (val == '') {
			return null;
		}
		return val;
	},
	
	setMotsCles: function(motscles) {
		this.motsClesInput[0].value = motscles;
	},
	
  getReference: function() {
    var val = this.referenceInput[0].value;
    val = trim(val);
    if (val == '') {
      return null;
    }
    return val;
  },
	
	setReference: function(reference) {
		this.referenceInput[0].value = reference;
	},
	
  getLongueur: function() {
    var val = this.longueurInput[0].value;
    val = trim(val);
    if (val == '') {
      return null;
    }
    return val;
  },
	
	setLongueur: function(longueur) {
		this.longueurInput[0].value = longueur;
	},
	
  getLargeur: function() {
    var val = this.largeurInput[0].value;
    val = trim(val);
    if (val == '') {
      return null;
    }
    return val;
  },
	
	setLargeur: function(largeur) {
		this.largeurInput[0].value = largeur;
	},
	
  getHauteur: function() {
    var val = this.hauteurInput[0].value;
    val = trim(val);
    if (val == '') {
      return null;
    }
    return val;
  },
	
	setHauteur: function(hauteur) {
		this.hauteurInput[0].value = hauteur;
	},
	
	getActivite: function() {
		var val = this.actSelect[0].value;
		if (val == '') {
			return null;
		}
		return val;
	},
	
	setActivite: function(activite) {
		this.actSelect[0].value = activite;
		this.actSelectChange();
	},
	
	getFamille: function() {
		var act = this.getActivite();
		if (act == null) {
			return null;
		}
		var famSel = $('#search_famille_'+act);
		if (famSel != null) {
      var val = famSel[0].value;
      if (val == '') {
        return null;
      }
      return val;
		}
		return null;
	},
	
	setFamille: function(famille) {
    var act = this.getActivite();
    if (act == null) {
      return null;
    }
    var famSel = $('#search_famille_'+act);
    if (famSel != null) {
      famSel[0].value = famille;
			this.famSelectChange(famSel[0]);
    }
	},
	
	getSousFamille: function() {
    var fam = this.getFamille();
    if (fam == null) {
      return null;
    }
    var sfamSel = $('#search_sous_famille_'+fam);
    if (sfamSel != null) {
      var val = sfamSel[0].value;
      if (val == '') {
        return null;
      }
      return val;
    }
    return null;
	},
	
  setSousFamille: function(sousFamille) {
    var fam = this.getFamille();
    if (fam == null) {
      return null;
    }
    var sfamSel = $('#search_sous_famille_'+fam);
    if (sfamSel != null) {
      sfamSel[0].value = sousFamille;
    }
  },
	
	search: function() {
		var motsCles = this.getMotsCles();
		var reference = this.getReference();
		
		var longueur = this.getLongueur();
		var largeur = this.getLargeur();
		var hauteur = this.getHauteur();
		
		var act = this.getActivite();
		var fam = this.getFamille();
		var sfam = this.getSousFamille();
		
		var str_args = '';
		if (motsCles != null) {
			str_args += '/motscles['+urlencode(motsCles)+']';
		}
		if (reference != null) {
			str_args += '/reference['+urlencode(reference)+']';
		}
		if (longueur != null) {
			str_args += '/longueur['+urlencode(longueur)+']';
		}
    if (largeur != null) {
      str_args += '/largeur['+urlencode(largeur)+']';
    }
    if (hauteur != null) {
      str_args += '/epaisseur['+urlencode(hauteur)+']';
    }
		if (act != null) {
			str_args += '/act['+act+']';
		}
    if (fam != null) {
      str_args += '/fam['+fam+']';
    }
    if (sfam != null) {
      str_args += '/sfam['+sfam+']';
    }
		
		var url = '/catalogue/ajaxSearchProds?search='+str_args;
		
		document.location.href='/catalogue#search'+str_args;
		if (catContent != undefined && catContent != null) {
		  catContent.loadContent(url);
  	}
	},
	
	loadSearchStr: function(search) {
    if (search == null) {
      return;
    }
    var args = [];
    
    var splitted = split('/', search);
    for (index in splitted) {
			arg = trim(splitted[index]);
      splitted2 = split('\[', arg);
      if (count(splitted2) != 2) {
        continue;
      }
      key = splitted2[0];
      val = splitted2[1];
      if (strlen(val) > 0) {
        val = substr(val, 0, strlen(val) - 1);
      }
      
      args[key] = val;
    }
		
		if (count(args) == 0) {
			return;
		}
		
		for (key in args) {
			var value = html_entity_decode(args[key]);
      if (key == 'act') {
				this.setActivite(value);
      } else if (key == 'fam') {
				this.setFamille(value);
      } else if (key == 'sfam') {
				this.setSousFamille(value);
      } else if (key == 'longueur') {
				this.setLongueur(value);
      } else if (key == 'largeur') {
				this.setLargeur(value);
      } else if (key == 'epaisseur') {
				this.setHauteur(value);
      } else if (key == 'reference') {
				this.setReference(value);
      } else if (key == 'motscles') {
				this.setMotsCles(value);
      }
		}
		
		this.search();
	}
});

var CatalogueNav = jQuery.Class.create({
  init: function() {
		this.currentListProdsUID = null;
		this.contentDiv = $('#catalogue_content_real');
  },
  
  navTo: function(dest) {
		//alert('navTo '+dest);
		if (catalogueSwitch != undefined && catalogueSwitch != null) {
			if (dest == '') {
				catalogueSwitch.switchToTable();
				if (catalogueTitle != undefined && catalogueTitle != null) {
					catalogueTitle.setActFamSfamWithCodes(null, null, null, null, null, null);
					catalogueTitle.setMainTitle('');
		    }
			} else {
				document.location.href='/catalogue#'+dest;
				var treeDest = dest.split('/');
        var act = treeDest[0];
				var fam = null;
				var sfam = null;
				if (treeDest.length > 1) {
					fam = treeDest[1];
				}
				if (treeDest.length > 2) {
					sfam = treeDest[2];
				}
				//alert(act+" / "+fam+" / "+sfam);
				
				catalogueSwitch.switchToTree();
				
				if (menuActFamSfam != undefined && menuActFamSfam != null) {
					//menuActFamSfam.setSelected(act);
					menuActFamSfam.setSelectedTree(act, fam, sfam);
					//var labels = menuActFamSfam.getCurrentSelectionsLabels();
					var codesAndLabels = menuActFamSfam.getCurrentSelectionsCodesAndLabels();
				  if (catalogueTitle != undefined && catalogueTitle != null) {
						var actDatas = codesAndLabels['act'];
						var famDatas = codesAndLabels['fam'];
						var sfamDatas = codesAndLabels['sfam'];
						
						var actCode = null;
						var actLabel = null;
						var famCode = null;
            var famLabel = null;
						var sfamCode = null;
            var sfamLabel = null;
						
						if (actDatas != null) {
							actCode = actDatas['code'];
							actLabel = actDatas['label'];
						}
						
						if (famDatas != null) {
              famCode = famDatas['code'];
              famLabel = famDatas['label'];
            }
						
            if (sfamDatas != null) {
              sfamCode = sfamDatas['code'];
              sfamLabel = sfamDatas['label'];
            }
						
						
            //catalogueTitle.setActFamSfam(actLabel, famLabel, sfamLabel);
						catalogueTitle.setActFamSfamWithCodes(actLabel, actCode, famLabel, famCode, sfamLabel, sfamCode);
            //catalogueTitle.setMainTitle(this.getSousFamilleLabelFromCode(code));
						catalogueTitle.setMainTitle('');
          }
			   //menuActFamSfam.moveActMenuTo(act);
		    }
        if (catContent != undefined && catContent != null && act != null) {
					if (sfam != null) {
						catContent.loadContent('/catalogue/ajaxListProds?sous_famille_code='+sfam);
					} else if(fam != null) {
						catContent.loadContent('/catalogue/ajaxFamille?famille_code='+fam);
					} else if (act != null) {
						catContent.loadContent('/catalogue/ajaxActivite?activite_code='+act);
					}
					
          /*if (catalogueTitle != undefined && catalogueTitle != null) {
            catalogueTitle.setActFamSfam(this.getActiviteLabel(), this.getFamilleLabel(), '');
            catalogueTitle.setMainTitle(this.getSousFamilleLabelFromCode(code));
          }*/
        }
				
			}
		}
  },
	
	navToHref: function(href) {
    diesePos = href.indexOf('#');
		if (diesePos < 0) {
			this.navTo('');
			return;
		}
		//alert(href.substring(diesePos+1));
    this.navTo(href.substring(diesePos+1));
	},
	
	setCurrentListProdsUID: function(uid) {
		this.currentListProdsUID = uid;
	},
	
	showProd: function(href) {
		var prod_and_list_div = $('#prod_and_list_container');
		var prodDiv = $('#prod_container');
		if (prod_and_list_div != null && prodDiv != null) {
			prodDiv.html('<div class="loader_div" style="max-height: 400px"></div>');
			prodDiv.load(href);
			prodDiv.css('left', this.contentDiv.width());
			prodDiv.css('display', 'block');
			prodDiv.css('height', this.contentDiv.height());
				 
			prod_and_list_div.animate({left: -this.contentDiv.width()}, 300, function() {
					//alert('-'+this.contentDiv.width()+'px'+'  -  '+distance);
          //this.contentDiv.children().css('left', '-'+this.contentDiv.width());
        }.bind(this));
		}
	},
	
  retourList: function() {
    var prod_and_list_div = $('#prod_and_list_container');
    var prodDiv = $('#prod_container');
    if (prod_and_list_div != null && prodDiv != null) {
      var distance = this.contentDiv.width(); 
      this.contentDiv.children().animate({left: 0}, 300, function() {
        prodDiv.css('display', 'none');
        prodDiv.css('height', '0');
  		}.bind(this));
    }
		catalogueTitle.setMainTitle('');
  }
});

var CatalogueSwitch = jQuery.Class.create({
  init: function() {
		this.switchDiv = $('#catalogue_switch');
    this.tableDiv = $('#catalogue_table');
    this.navDiv = $('#catalogue_with_menu');
		
		this.menuDiv = $('#catalogue_menu');
		this.searchDiv = $('#catalogue_search');
		
		this.tableIsShown = true;
		if (this.tableDiv.css('display') == 'hidden') {
			this.tableIsShown = false;
		}
  },
  
  switchToTree: function() {
    this.searchDiv.css('display', 'none');
    this.menuDiv.css('display', 'block');
		this.tableDiv.css('display', 'none');
		this.switchDiv.css('overflow-y', 'auto');
		this.navDiv.css('display', 'block');
		this.reloadTreeLayout();
  },
	
	reloadTreeLayout: function() {
    $('#catalogue_with_menu').layout({
      west: {
        size: 388,
        spacing_open: 0,
        resizable: false
      },
      center: {
        spacing_open: 0,
        resizable: false
      }
    });		
	},
	
  switchToTable: function() {
    this.navDiv.css('display', 'none');
    this.switchDiv.css('overflow-y', 'scroll');
		this.tableDiv.css('display', 'block');
  },
	
	switchToSearch: function() {
		this.menuDiv.css('display', 'none');
		this.searchDiv.css('display', 'block');
    this.tableDiv.css('display', 'none');
    this.switchDiv.css('overflow-y', 'auto');
    this.navDiv.css('display', 'block');
	}
});

var CatalogueContent = jQuery.Class.create({
  init: function() {
    this.currentContentUri = null;
    this.loadingUri = null;
    this.loaderDiv = $('#catalogue_content_loader');
    this.contentDiv = $('#catalogue_content_real');
    
    this.cache = {};
  },
  
  loadContent: function(uri) {
		if (uri == this.currentContentUri) {
		  retourList();
			return;
		}
    if (uri == this.currentContentUri || uri == this.loadingUri) {
      return;
    }
    this.loadingUri = uri;
    if (this.cache[uri] != undefined) {
      this.contentDiv.fadeOut(50, function() {
        this.contentDiv.html(this.cache[uri]);
        this.loading_uri = null;
        this.currentContentUri = uri;
        this.contentDiv.fadeIn(150);
      }.bind(this));
      return;
    }
    this.contentDiv.html('');
    this.contentDiv.css('display', 'none');
    this.showLoader();
    this.contentDiv.load(uri, this.loadingFinished.bind(this));
  },
  
  loadingFinished: function() {
    this.contentDiv.fadeIn(300);
    this.hideLoader();
    if (this.loadingUri != null) {
      //this.cache[this.loadingUri] = this.contentDiv.html();
    }
    this.currentContentUri = this.loadingUri;
    this.loadingUri = null;
  },
  
  showLoader: function() {
    this.loaderDiv.css('display', 'block');
  },
  
  hideLoader: function() {
    this.loaderDiv.css('display', 'none');
  }
});

var catalogueNav = null;
function initCatalogueNav() {
	catalogueNav = new CatalogueNav();
}

var catalogueTitle = null;
function initCatalogueTitle() {
  catalogueTitle = new CatalogueTitle();
}

var catalogueSwitch = null;
function initCatalogueSwitch() {
	catalogueSwitch = new CatalogueSwitch();
}

var menuActFamSfam = null;
function initMenuActFamSfam() {
  menuActFamSfam = new MenuActFamSfam();
}

var catContent = null;
function initCatalogueContent() {
  catContent = new CatalogueContent();
}

var catSearch = null;
function initCatalogueSearch() {
	catSearch = new CatalogueSearch();
}

function catalogueShowArticle(code, tr) {
	//catContent.loadContent('/catalogue/ajaxFicheProd?article_code='+code);
  if (catalogueNav != undefined && catalogueNav != null) {
    catalogueNav.showProd('/catalogue/ajaxFicheProd?article_code='+code);
  }
	if (tr != null) {
		catalogueTitle.setMainTitle($($($($(tr).children()[1]).children()[0]).children()[0]).html());
	}
}

function retourList() {
	if (catalogueNav != undefined && catalogueNav != null) {
    catalogueNav.retourList();
  }
}

function catalogueNavigateTo(href) {
	if (catalogueNav != undefined && catalogueNav != null) {
		catalogueNav.navToHref(href);
  }
}

function catSetCurrentListProdsUID(uid){
  if (catalogueNav != undefined && catalogueNav != null) {
    catalogueNav.setCurrentListProdsUID(uid);
  }
}

var modal = null;

function initModal(){
  modal = $('<div id="modal_layout"></div>').html('').dialog({
    autoOpen: false,
    modal: true,
    width: 686,
    height: 443,
    resizable: false,
    draggable: false,
    closeText: ' fermer (x) '
  });
}

function openModal(url) {
  if (modal == null) {
    initModal();
  }
  if (modal != null) {
    modal.html('<div class="loader_div" style="height: 95%"></div>').dialog('open').load(url);
  }
}

function closeModal() {
  if (modal != null) {
    modal.html('').dialog('close');
  }
}

function showPanier() {
  openModal('/panier/ajaxPanier');
}

function deletePanierLine(line_id) {
  openModal('/panier/ajaxPanier?del='+line_id);
}

function demandeDevis() {
	openModal('/panier/ajaxDemandeDevis');
}

function addToPanier(article_code, lot_code) {
	var url = '/panier/ajaxAdd?article_code='+article_code;
	if (lot_code != null) {
		url = url + '&lot_code='+lot_code;
	}
	openModal(url);
}

function advancedSearch() {
	alert('search');
}

function headerSearch() {
  var inp = $('#header_search_input');
	if (catalogueSwitch != null) {
		catalogueSwitch.switchToSearch();
    if (inp != null) {
      var val = trim(inp[0].value);
			
			var searchStr = '/motscles['+urlencode(val)+']';
			
      var url = '/catalogue/ajaxSearchProds?search='+searchStr;
    
		  document.location.href = '/catalogue#search'+searchStr;
      if (catContent != undefined && catContent != null) {
        catContent.loadContent(url);
      }
			setAdvancedSearchMotsClesInputContent(val);
    }
	} else {
    if (inp != null) {
      var val = trim(inp[0].value);
			var searchStr = '/motscles['+urlencode(val)+']';
      document.location.href = '/catalogue#search'+searchStr;
    }
	}
}

function headerSearchAdvanced(){
  if (catalogueSwitch != null) {
  	catalogueSwitch.switchToSearch();
  } else {
    document.location.href = '/catalogue#search';
	}
}

function setAdvancedSearchMotsClesInputContent(content) {
	var advancedSearchMCinput = $('#search_mot_cle');
	if (advancedSearchMCinput != null) {
		advancedSearchMCinput[0].value = content;
	}
}

