// Fonctions Javascript du catalogue de produits
// Widely enhanced by Prototype


// Lancement du menu de navigation
Event.observe(window, 'load', menuNav, false);
Event.observe(window, 'load', linkThumb, false);
Event.observe(window, 'load', linkAddPics, false);
//Event.observe(window, 'load', stripe, false);
Event.observe(window, 'load', loadPrices, false);
Event.observe(window, 'load', loadPrices2, false);

// ------------------------------------------------
// 	Scripts Généraux
// ------------------------------------------------

// Un simple Submit Form
function submitInfos()
{
 document.toolForm.submit();
}

// Vérifie sur un objet à une classe
function hasClass(obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result = obj.getAttributeNode("class").value;
     }
     return result;
}   

// ------------------------------------------------
// 	Scripts Catalogue de produits
// ------------------------------------------------

// Script d'animation du menu... Il se base sur la DB pour afficher ou non le sous-menu

function menuNav() {
	if($("vMenu")){
		var subMenus = $$('#vMenu .vMenuFx');
		var pager = location.href;
		var variables = pager.split("-");
		
		if (variables.length == 7 && variables[0]=="http://www.quatuor.be/fiche") {
			var dispNum = variables[4] - 1;
		} else {
			if(variables.length == 3) {
				var dispNum = 0;
			} else {
				var dispNum = variables[1] - 1;
			}
		}
		for(var i=0; i < subMenus.length; i++) {
			if(i == dispNum) {
				subMenus[i].show();
			} else {
				subMenus[i].hide();
			}
		}
			
		var togglers = $$("li.vMenuToggle a");
		for (var h=0; h < togglers.length; h++) {
			var subPref = togglers[h].id;
			togglers[h].onclick= function(){
				var subName = "sub" + this.id;
				Effect.toggle(subName, 'blind', { duration: 0.5 });
				return false;
			};
		}
	}
}

// Striping des tables de données en deux couleurs
function stripe() {
	var id = "table_dim_supp";
	var even = false;
	var evenColor = arguments[1] ? arguments[1] : "#FFFFFF";
	var oddColor = arguments[2] ? arguments[2] : "#D6EAF8";
	var table = $(id);
	
	if (table) {
		var tbodies = table.getElementsByTagName("tbody");
		for (var h = 0; h < tbodies.length; h++) {
			var trs = tbodies[h].getElementsByTagName("tr");
			for (var i = 0; i < trs.length; i++) {
				if (!trs[i].style.backgroundColor) {
					var tds = trs[i].getElementsByTagName("td");
					for (var j = 0; j < tds.length; j++) {
						var mytd = tds[j];
						if (!mytd.style.backgroundColor) {
			      			mytd.style.backgroundColor = even ? evenColor : oddColor;
	            		}
	          		}
	        	}
	        even =  ! even;
	      	}
	    }
	}
}

//	Swapping des tabs sur le Scroll products
function swapTab() {
		var bloc1 = document.getElementById("scrollBloc1");
		var bloc2 = document.getElementById("scrollBloc2");
			bloc2.style.display='none';
		
		var link1 = document.getElementById("tab1");
		var link2 = document.getElementById("tab2");
			link1.onclick = function() {
				link1.firstChild.src = "img/scroll_tab_new.gif";
				link2.firstChild.src = "img/scroll_tab_promo_i.gif";
				bloc1.style.display = 'block';
				bloc2.style.display = 'none';
				return false;
			}
				link2.onclick = function() {
				link1.firstChild.src = "img/scroll_tab_new_i.gif";
				link2.firstChild.src = "img/scroll_tab_promo.gif";
				bloc2.style.display = 'block';
				bloc1.style.display = 'none';
				return false;
			}	
	}

// Affichage du layer avec le prix du produit.
function loadPrices() {
	var link = $$('div.over');
	for (var i = 0; i < link.length; i++) {
	    link[i].onmouseover = function(){
	    	var prixOverlay = this.next('div');
	    	var infoO = this.next('div').firstDescendant();
	    	//infoO.style.top = "40px";
	    	prixOverlay.style.display = 'block';
	    	new Effect.Move(prixOverlay, { y:0, duration:0.3, mode: 'absolute'});
	    	new Effect.Move(infoO, { y:20, duration:0.5, mode: 'absolute'});
	    }
	    link[i].onmouseout = function(){
	    	var prixOverlay = this.next();
	    	var infoO = this.next('div').firstDescendant();
	    	new Effect.Move(infoO, { y:40, duration:0, mode: 'absolute'});
	    	new Effect.Move(prixOverlay, { y:90, duration:0.3, mode: 'absolute', afterFinish:function(){prixOverlay.style.display = 'none';}});
	    }
	}
}
function loadPrices2() {
	var link = $$('span.over');
	for (var i = 0; i < link.length; i++) {
	    link[i].onmouseover = function(){
	    	var prixOverlay = this.next('span');
	    	var infoO = this.next('span').firstDescendant();
	    	//infoO.style.top = "40px";
	    	prixOverlay.style.display = 'block';
	    	new Effect.Move(prixOverlay, { y:0, duration:0.3, mode: 'absolute'});
	    	new Effect.Move(infoO, { y:20, duration:0.5, mode: 'absolute'});
	    }
	    link[i].onmouseout = function(){
	    	var prixOverlay = this.next();
	    	var infoO = this.next('span').firstDescendant();
	    	new Effect.Move(infoO, { y:40, duration:0, mode: 'absolute'});
	    	new Effect.Move(prixOverlay, { y:90, duration:0.3, mode: 'absolute', afterFinish:function(){prixOverlay.style.display = 'none';}});
	    }
	}
}

// ------------------------------------------------
// 	Scripts Fiche produits
// ------------------------------------------------

// Gestion des photos additionnelles
// On crée les liens et le comportement des photos
function linkAddPics() {
	if($("addPhotosFiche")){
		var bloc = $("addPhotosFiche");
		var picture = $$("#addPhotosFiche .fullSubPic");
		var target = $("img_full");
		var targetImg = target.src;
		
		var src_new = Array("","");
		
		for (var i = 0; i < picture.length; i++) {
			var splitBloc = picture[i].src.split("/");
			src_new[i] = "http://www.quatuor.be/"+splitBloc[3]+"/"+splitBloc[5];
			picture[i].alt = src_new[i];
			picture[i].onmouseover = function(){
				targetImg = target.src;
				target.src = this.alt;
				return false;
			}
			picture[i].onmouseout = function(){
				target.src = targetImg;
				return false;
			}
		}
	}
}


// Gestion des produits multicolor

function linkThumb2(file) {
	var directory = file.split('_')[0];
	var src_new = "http://www.quatuor.be/color_pics/"+directory+"/"+file;
	var full_pic = $("img_full");
	var z = $('photoFicheA');
	if(!z) z = full_pic;
	if(src_new != full_pic.src) {
		full_pic.observe('load', function(){
			new Effect.Opacity(z,{
				from: 0,
				to: 1,
				duration: .5,
				afterFinish: function() {
					full_pic.stopObserving('load');
				}
			});
		});
		
		new Effect.Opacity(z,{
			from: 1,
			to: 0,
			duration: .5,
			afterFinish: function () {
				full_pic.src = src_new;
			}
		});
  	
	}
}

function color_check(cell) {
	$A($(cell).up('table').getElementsByTagName('td')).each(function(e){
		$(e).removeClassName('checked');
	});
	$(cell).up('td').addClassName('checked').previous('td').addClassName('checked').previous('td').addClassName('checked');
}

function linkThumb() {
	if($("productColor")) {
	    var menu = $('productColor');
	    menu.onchange = function(){
	    	if(this.value != "") {
		    	var src = this.value.split("-");
		    	var name = src[0];
		    	var directory = src[0].split("_");
		    	var file = name+".jpg";
		    	src_new = "http://www.quatuor.be/color_pics/"+directory[0]+"/"+file;
		    	var full_pic = $("img_full");
		    	if( src_new != full_pic.src) {
		    		new Effect.Opacity('img_full',{from: 1, to: 0});
					full_pic.src = src_new;
			    	new Effect.Opacity('img_full',{from: 0, to: 1});
		    	}
	    	}
	    }
	    return false;
	    }
}

// Gestion des votes produits
function sndVoteReq(vote,id_num,ip_num,units,uw) {

	var theUL = $('unit_ul'+id_num); // the UL
	
	// switch UL with a loading div
	theUL.innerHTML = '<div class="loading"></div>';
	
	var url = '/ecommerce/rating/vote.php?method=voteX&rating='+vote+'&referer='+id_num+'&ip='+ip_num+'&units='+units+'&uw='+uw ;
	var paramstr = '';
	var myAjax = 
			new Ajax.Request(
					url, {
					method: 'get',
					onSuccess : function(resp) {
						$('ratingContainer').innerHTML = resp.responseText;
					},
					onFailure : function(resp) {
						theUL.innerHTML = "Ouups ! Une erreur est survenue lors du vote.";
					},
					parameters : paramstr
			});	
	return false;
}


/* =============================================================== */
var ratingAction = {
		'a.rater' : function(element){
			element.onclick = function(){

			var parameterString = this.href.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');
			var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
			var parameterList = new Array();

			for (j = 0; j < parameterTokens.length; j++) {
				var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
				var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1
				parameterList[parameterName] = parameterValue;
			}
			var theratingID = parameterList['referer'];
			var theVote = parameterList['rating'];
			var theuserIP = parameterList['ip'];
			var theunits = parameterList['units'];			
			var theunitWith = parameterList['uw'];
			
			//for testing	alert('sndReq('+theVote+','+theratingID+','+theuserIP+','+theunits+')'); return false;
			sndVoteReq(theVote,theratingID,theuserIP,theunits,theunitWith); return false;		
			}
		}
		
	};
//Behaviour.register(ratingAction);





/*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).

   Description:
   	
   	Uses css selectors to apply javascript behaviours to enable
   	unobtrusive javascript in html documents.
   	
   Usage:   
   
	var myrules = {
		'b.someclass' : function(element){
			element.onclick = function(){
				alert(this.innerHTML);
			}
		},
		'#someid u' : function(element){
			element.onmouseover = function(){
				this.innerHTML = "BLAH!";
			}
		}
	};
	
	Behaviour.register(myrules);
	
	// Call Behaviour.apply() to re-apply the rules (if you
	// update the dom, etc).

   License:
   
   	This file is entirely BSD licensed.
   	
   More information:
   	
   	http://ripcord.co.nz/behaviour/
   
*/   

var Behaviour = {
	list : new Array,
	
	register : function(sheet){
		Behaviour.list.push(sheet);
	},
	
	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},
	
	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);
				
				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},
	
	addLoadEvent : function(func){
		var oldonload = window.onload;
		
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

Behaviour.start();

/*
   The following code is Copyright (C) Simon Willison 2004.

   document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names, 
     class names and ids and can be nested. For example:
     
       elements = document.getElementsBySelect('div#main p a.external')
     
     Will return an array of all 'a' elements with 'external' in their 
     class attribute that are contained inside 'p' elements that are 
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    
    if (!currentContext[0]){
    	return;
    }
    
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/


//	End of file... sorry ;-)