// JavaScript Document

var gid,gdelay,gloop;

function initFade(id,delay,loop) {
	//id: id du div
	//delay: nbr millisec
	//loop: 0=pas de loop, 1=loop fadeIn/fadeOut
	if (id!='') {
		gid=id;
		gdelay=delay;
		gloop=loop;
		setTimeout('initFadeIn()', gdelay);
	}
}

var gstep=0;

function myLoop(ids,delay,step,delayLoop) {
	if (ids!='') arrIds=ids.split(",");
	if (step<arrIds.length) MM_showHideLayers(arrIds[step],'','fadein');
	step++;
	if (step>arrIds.length) {
		step=0;
		for (i=0;i<arrIds.length;i++) changeOpac(0,arrIds[i]);
	}
	if (step!=arrIds.length-1) {
		setTimeout('myLoop(\'\','+delay+','+step+','+delayLoop+')', delay);
	} else {
		//delayLoop: ms entre chaque cycle, si negatif, stoppe
		if (delayLoop>0) setTimeout('myLoop(\'\','+delay+','+step+','+delayLoop+')', delayLoop);
	}
}

function initFadeIn() {
 	MM_showHideLayers(gid,'','fadein');
 	if (gloop) {setTimeout('initFadeOut()', gdelay+1000);}
}

function initFadeOut() {
 	MM_showHideLayers(gid,'','fadeout');
 	if (gloop) {setTimeout('initFadeIn()', gdelay+1000);}
}


function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

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 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_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 OLD_MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}


function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments,p,timer;
//  if(navigator.userAgent.indexOf("Safari")!=-1) {
  	speed=15;
  	pMax=100;
  	pStep=1;
// } else {
// 	speed=15;
//	pMax=100;
//	pStep=1;
//}  
  
  timer=0;
  
  for (i=0; i<(args.length-2); i+=3) 
  	if ((obj=MM_findObj(args[i]))!=null) { 
  		v=args[i+2];
  		switch (v.toLowerCase()) {
 		case "fadeout":
			changeOpac(100,args[i]);
			obj.style.visibility='visible';
 			for(p = pMax; p >= 0; p--) setTimeout("changeOpac(" + pStep*p + ",'" + args[i] + "')",(timer++ * speed)); 
 			break;
 		case "fadein":
			changeOpac(0,args[i]);
			obj.style.visibility='visible';
 			for(p = 0; p < pMax; p++) setTimeout("changeOpac(" + pStep*p + ",'" + args[i] + "')",(timer++ * speed)); 
			break;
		default:	//show ou hide
			if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    		obj.visibility=v;
		}
    }
}

function changeOpac(opacity, id) { 
	var object = MM_findObj(id).style; 
	object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
} 

function mychangeClass(id,value) {
	if (document.getElementById) {
		document.getElementById(id).className=value;
	} else if (document.all) {
		document.all[id].className=value;
	}
}

function changeInnerHtml(id,value) {
	value=unescape(value).replace(/\+/g, " ")
	
	if (document.getElementById) {
		document.getElementById(id).innerHTML=value;
	} else if (document.all) {
		document.all[id].innerHTML=value;
	}
}

function getInnerHtml(id) {
	if (document.getElementById) {
		return(document.getElementById(id).innerHTML);
	} else if (document.all) {
		return(document.all[id].innerHTML=value);
	}
}

function changeColorClass(s1,s2) {
	var arr=s1.split(',');
	for (i=0;i<arr.length;i++) {
		if (arr[i]!='') if (arr[i]==s2) mychangeClass('color'+arr[i],'selected'); else mychangeClass('color'+arr[i],'notselected');
	}
}

function pathZoomClose() {
	MM_showHideLayers('zoom','','show','zoom3','','hide');
}

function js_addRemoveBasket(code,action,flag) {
	// flag: if 1, show the basket after update
	codes=code.split("-");
	if (codes.length<3) {alert("Please, choose a size");return false}
	if (!flag)
		$('#basket_detail').load("/basket.asp",{'mode':'ajax', 'action':action, 'page':'detail', 'code':code});
	else
		$('#basket_detail').load("/basket.asp",{'mode':'ajax', 'action':action, 'page':'detail', 'code':code}, function(){js_showBasket(1)});
	
}
function js_regionBasket(value) {
	if (value!="") {
			$('#basket_detail').load("/basket.asp",{'mode':'ajax', 'action':'region', 'page':'detail', 'value':value}, function(){js_showBasket(1)});
	}
}
function js_postBasket(step) {
	//alert('post:'+$('#basket_post').serialize())
	var hasError=0;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	$('#basket_post').find('input, textarea.mandatory, select').each(function(i,input){if (jQuery.trim($(input).val())=="") {$(input).addClass("error");hasError++} else $(input).removeClass("error"); });
	$('#basket_post').find('input[name="email"]').each(function(i,input){if (jQuery.trim($(input).val())=="" || !emailReg.test($(input).val())) {$(input).addClass("error");hasError++} else $(input).removeClass("error"); });
	
	if (!hasError) $.post("/basket.asp",$('#basket_post').serialize(), function(){js_showBasket(step)}); else {alert("Please, correct field(s) in red")}
}
function js_showBasket(step) {
	$.fancybox.showActivity();
	$.ajax({
		type	: "POST",
		cache	: false,
		url		: "/basket.asp",
		data	: {'mode':'ajax','page':'popup'+step},
		success: function(data) {
			$.fancybox(data,{padding:0,margin:0});
		}
	});
}
function js_copyAddress(obj) {
	if (obj.checked) {
		$("#name_billing").val($("#name_delivery").val());
		$("#address_billing").val($("#address_delivery").val());
	}
}

function js_changeFitwith(obj,code_color,count) {
	$('#list').find('p.selectedProduct').removeClass("selectedProduct");
	$(obj).find("p").addClass("selectedProduct");
	$('#detail').load("/products.asp",{'mode':'ajax', 'action':'fitwith', 'code-color':code_color, 'count':count});
	
}

$(document).ready(function () {
	var loc=""+window.location;
	if (loc.indexOf("sp_confirm")>-1) js_showBasket(8);
	if (loc.indexOf("sp_fail")>-1) js_showBasket(7);
	if ($('#basket_detail').length==0) $('body').append($("<div id='basket_detail' style='display:none'>"));
	$('.fancyboxChart').fancybox();
});

/* cbySlideshow plugin */
(function($){
	/* OO jquery based on http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html */
	$.fn.cbySlideshow = function(options) {
		return this.each(function() {
			var element = $(this);
			if (options && options.removeData==true) element.removeData('cbySlideshow');
			// Return early if this element already has a plugin instance
			if (element.data('cbySlideshow')) return;
			// pass options to plugin constructor
			var cbySlideshow = new cbySlideshowClass(this, options);
			// Store plugin object in this element's data
			element.data('cbySlideshow', cbySlideshow);
		});
	};
	
	var cbySlideshowClass = function(element,options) {
		// Start declaration (don't forget to put 'var' before every variables/functions!)
		// Default settings
		var settings = jQuery.extend({
			interval: 3000,
			speed: 1000,
			height: false,
			autoplay: true,
			loop: true,						// Loop at the end
			current:0,						// Allow to start from a specific slide
			title: true,					// Show title of img in the bottom part
			counter: "tiles",				// Can be 'tiles' (dots at the bottom-right), 'number' (1/x) or false
			start: 0						// Milliseconds of 'delay' to start slideshow (to delay autoplay when more that one slideshow on the page)
		}, options);
		var container=$(element);			// The object
		var height=0;						// Slideshow height
		var timeout=false;					// Variable to start/stop the slideshow
		var current=settings.current;		// Variable containing the index of the current slide
		var slides=container.children();	// We take the first level of children as slides (can be img, div, ...)
		if (!slides.length) return false;
		if (!settings.height && slides[0].nodeName.toLowerCase()=="img") {
			slides.eq(0).bind("load",function(){
				doResize();
			})
		};
		if (slides.length>5 && settings.counter=="tiles") settings.counter="number";		// If more than 5 slide, set the counter to number
		if (slides.length>1) {				// If only one slide, no transition
			if (!settings.height) 			// Default height to the first image
				height=slides.eq(current).height();
			else height=settings.height;
			container.css({position:"relative",height:height+"px"});	// The container MUST have a fixed height, must be handle if resize() can change it
			slides.each(function(){			// Set the slides position (top-left) and hide them
					$(this).css({position:"absolute",top:0,visibility:"visible"}).css("left",0).hide();
			});
			slides.eq(current).show();
			if (settings.autoplay) timeout=setTimeout(function() {next();},settings.interval+settings.start);
		}
		container.addClass("cbySlideshow");
		
		if (settings.title) {				// Set a 'title bar' at the bottom of the container and a serie of 'tiles' to navigate in the slideshow
			var title=$("<div>").css({position:"absolute",bottom:0,left:0,right:0}).addClass("title").html(slides.eq(0).attr("alt"));		// right AND left are set (to get true 100% no matter of padding)
			container.append(title);
		}
		switch (settings.counter) {
			case "tiles":
			case "number":
				var tiles=$("<div>").css({position:"absolute",bottom:0,right:4});
				if (settings.counter=="tiles") {
					for (var i=0;i<slides.length;i++) {		// Create the tiles and put class 'selected' on the first one
						var tile=$("<div>").css("cursor","pointer").addClass("tiles").addClass((i==0)?"selected":"");
						tiles.append(tile);
					}
				} else {
					tiles.addClass("number");
					tiles.text((current+1)+"/"+slides.length);
				}
				container.append(tiles);
				if (settings.counter=="tiles") {
					container.find("div.tiles").each(	// Bind the onclick event after tiles are appended!
						function(i,obj){
							$(obj).bind("click",{index:i},function(event){jumpto(event.data.index,true)})
						});
				}
				break;
		}
		var next = function() {						// Function to go to the next slide (and continue slideshow)
			var i=current+1;
			if (i==slides.length && settings.loop==false) return false;
			if (i==slides.length) i=0;
			jumpto(i,false);
			timeout=setTimeout(function() {next();},settings.interval);
		}
		var jumpto = function(i,stop) {				// Function to jump to a specific slide (and stop the slideshow if needed)
			if (!container.is(":visible")) return false;	// No animation if container is not visible!
			if (stop) clearTimeout(timeout);
			slides.eq(current).fadeOut(settings.speed);
			slides.eq(i).fadeIn(settings.speed);
			if (settings.title) {
				title.html(slides.eq(i).attr("alt"));
			}
			if (settings.counter=="tiles") {
				tiles.find("div").eq(current).removeClass("selected");
				tiles.find("div").eq(i).addClass("selected");
			}
			if (settings.counter=="number") {
				tiles.text((i+1)+"/"+slides.length);
			}
			current=i;
		}
		var doResize = function() {
			height=slides.eq(current).height();
			container.css({height:height+"px"});
		}
		this.resize = function() {
			doResize();
		}
	}
})(jQuery);

/* plugin hide and show options in a select list (because display:none on option does not work on IE/Chrome */
(function($){
	$.fn.cbyOptions = function(options) {
		return this.each(function() {
			var element = $(this);
			// Return early if this element already has a plugin instance
			if (element.data('cbyOptions')) return;
			// pass options to plugin constructor
			var cbyOptions = new cbyOptionsClass(this, options);
			// Store plugin object in this element's data
			element.data('cbyOptions', cbyOptions);
		});
	};
	
	var cbyOptionsClass = function(element,options) {
		// Start declaration (don't forget to put 'var' before every variables/functions!)
		// Default settings
		var settings = jQuery.extend({
			selector:""
		}, options);
		var container=$(element);				// The object
		var copy=container.clone();						// Copy content
		container.html("");						// Empty the select
		this.filter = function(selector) {
			_filter(selector);
		}
		var _filter = function(selector) {		// Ex of selector: "option[data-value='50']"
			container.html("");	
			var content=copy.find(selector);
			//alert(selector+' '+content.length)
			container.append(content.clone());
		}
		if (settings.selector!="") _filter(settings.selector);
		
	}
})(jQuery);

