/*
	LCS Master Function
*/

window.LCS = window.LCS || {};
LCS = {
		//Create LCS Object	/ ClassName
};

/*
	DHTML on page Pager with scroll
*/
LCS.Pager = {
	itemsPerPage : 4,
	currentPage : 1,
	
	moveTo : function(container, top) {
		Position.prepare();
		container_y = Position.cumulativeOffset($(container))[1]
		new Effect.Scroll(container, {x:0, y:top});		
		return false;
	},
	
	moveToPage : function(page) {
		this.setLinks(page, this.currentPage);
		this.currentPage = page;
		
		content = $('results').firstDescendant();
		content = content.getElementsByTagName('li');
		
		var h = 0;
		var firstItemPage = (page-1)*this.itemsPerPage;			
		
		for(x=0; x<content.length; x++) {				
			if(x < firstItemPage) { // stop calculate height at the current item.		
				h = h + $(content[x]).getHeight() + parseInt($(content[x]).getStyle("margin-top")) + parseInt($(content[x]).getStyle("margin-bottom"));																
			} 								
		}
		
		this.moveTo('results', h);	
	},
	
	previousPage : function() {
		if (this.currentPage > 1) {
			this.moveToPage(this.currentPage - 1);
		}
	},
	
	nextPage : function(lastPage) {
		if (this.currentPage < lastPage) {
			this.moveToPage(this.currentPage + 1);
		}
	},
	
	setLinks : function(nextPage, lastPage){
		var lastPage = String("resultsPage" + lastPage);
		$(lastPage).removeClassName('current');	
		
		var nextPage = String("resultsPage" + nextPage);
		$(nextPage).addClassName('current');
		return false;
	}	
}


/*
	DHTML Drop Down
*/
LCS.DropDown = {
	currentFilterId : null,
	currentFilterTop : null,
	currentFilterList : null,
	
	Init : function(id) {
		if(id != this.currentFilterId){
			this.currentFilterId = id;
			this.currentFilterTop = id + 'FilterTop';
			this.currentFilterList = id + 'FilterList';
			document.onmousemove = this.onMove;
			$(this.currentFilterList).show();
			$(this.currentFilterId)._autocomplete = new autocomplete(this.currentFilterId,this.currentFilterList);
		}
	},
		
	focusInit : function() {				
		this._autocomplete = new autocomplete(this.id,this.id + 'FilterList');			
	},

	blurInit : function() {
		this._autocomplete = null;
	},

	selectOptions : function(whichLink, whichOptions, whichInput, valueHid) {
		$(whichInput).value = whichOptions;
		if(valueHid) $(whichInput + '_hid').value = valueHid;
		$(whichLink).up(1).setStyle({display:'none'});
		LCS.DropDown.resetDropDown();
	},
	
	setSelection : function(whichInput, value, valueHid) {
		var value2 = value; 
	    value2 = value2.replace(/&Eacute;/, "É");
		value2 = value2.replace(/&Icirc;/, "Î");
		value2 = value2.replace(/&eacute;/, "é");		
		$(whichInput).value = value2;
		$(whichInput + "Hid").value = valueHid;
		myList = whichInput + "FilterList";
		$(myList).hide();
		LCS.DropDown.resetDropDown();
	},

	resetDropDown : function() {
		if(LCS.DropDown.currentFilterId) {			
			var hrefs = $(LCS.DropDown.currentFilterId + "FilterList").getElementsByTagName('a');			
			for(x=0; x<hrefs.length; x++) {
				hrefs[x].className = '';
			}
			$(this.currentFilterId)._autocomplete = null;
			LCS.DropDown.currentFilterId = '';	
		}
	},
	
	getPositionObject : function(obj) {
		var o = function() { var curtop =0;var curleft = 0 };		
			o.curleft = 0;
			o.curtop = 0;
		
		if (obj.offsetParent) {
			o.curleft = obj.offsetLeft
			o.curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				o.curleft += obj.offsetLeft
				o.curtop += obj.offsetTop
			}
		}
		
		return o;
	},
	
	onMove : function(event) {	
		var oTop = $(LCS.DropDown.currentFilterTop);
		var oList = $(LCS.DropDown.currentFilterList);
		var curleft = 0;
		var filtertop = 0;
		var filterbottom = 0;
		var filterstart = 0;
		var filterend = 0;
		event = event ? event : window.event;
		var r = LCS.DropDown.getPositionObject(oTop);
		filterstart = r.curleft;
		filtertop = r.curtop;
		filterend = filterstart + oTop.clientWidth;
		filterbottom = filtertop + oTop.clientHeight + oList.clientHeight;
		
		var clientY;
		var clientX;
		if (!document.body.scrollTop) {
			clientX = event.clientX + document.documentElement.scrollLeft; 
			clientY = event.clientY + document.documentElement.scrollTop;
		}
		else {
			clientX = event.clientX + document.body.scrollLeft; 
			clientY = event.clientY + document.body.scrollTop; 
		}
		if(clientY > filterbottom || clientY < filtertop || clientX > filterend || clientX < filterstart) {
			document.onmousemove ='';
			$(LCS.DropDown.currentFilterList).hide();
			LCS.DropDown.currentFilterId = '';
		}		
	} 	

}

document.observe("dom:loaded", function() {
	var sel = $$("input.dropInput");
	for(x=0; x<sel.length; x++) {		
		sel[x].onfocus = LCS.DropDown.focusInit;
		sel[x].onblur = LCS.DropDown.blurInit;		
	}
});	

function autocomplete(textBoxId, containerDivId) {
    var ac = this;
    this.textbox     = document.getElementById(textBoxId);
    this.div         = document.getElementById(containerDivId);
    this.list        = this.div.getElementsByTagName('div');
    this.pointer     = null;

	this.textbox.focus();
    this.textbox.onkeydown = function(e) {
		e = e || window.event;
		
		//console.log(e.keyCode + ": " + String.fromCharCode(e.keyCode));
		var keyCode = e.keyCode; 
	   	switch( keyCode ) {
			case 13: //enter
               // ac.selectDiv(); 
				return false;
				break;            
			
			case 38: //up
                //ac.selectScrollDiv(-1);
                break;
				
            case 40: //down
               // ac.selectScrollDiv(1);
                break;
				
			default: 
				// fix for KeyPad numbers [0 ins] = 96 .. [9 PgUp] = 105, when regular [0 )] = 48 .. [1 !] = 57; 
				// InfoLink: http://unixpapa.com/js/key.html
				if (keyCode >= 96 && keyCode <= 105) {
					keyCode = keyCode - 48;
				}
				var key = String.fromCharCode(keyCode);
				//alert("e.keyCode = " + e.keyCode + "; key = " + key + ";  e = " + e);
				ac.findDiv(key);
				break
        }
    }
	
	this.findDiv = function(key) {
		var hrefs = this.div.getElementsByTagName('a');				
		
		if(this.textbox.value.charAt(0) == key) {			
			y = this.pointer+1;			
		} else {
			y = 0;
		}

		for(x=y; x<hrefs.length; x++) {
			if(hrefs[x].innerHTML.charAt(0) == key) {								
				this.pointer = x;
				ac.selectDiv();				
				break;
			} else {
				this.pointer = null;
			}
		}		
	}

	this.selectDiv = function() {	
		var a = this.list[this.pointer].getElementsByTagName('a')[0];
		
		adata = a.href.substring(a.href.indexOf("(")+1,a.href.indexOf(")"));
		adata = unescape(adata);
		adata = adata.replace(/'/gi, '');
		adata = adata.replace(/"/gi, '');
		adata = adata.replace(/ /gi, '');
		adata = adata.split(",");
	
		if(a.href.indexOf("setSelection") != -1) {
			LCS.DropDown.setSelection(adata[0],adata[1],adata[2]);
		} else {
			LCS.DropDown.selectOptions(adata[0],adata[1],adata[2],adata[3]);
		}
	
		return false;
	}

    this.selectScrollDiv = function(inc) {							
		if(this.pointer !== null && this.pointer+inc >= 0 && this.pointer+inc < this.list.length) {          
			this.list[this.pointer].getElementsByTagName('a')[0].className = '';
            this.pointer += inc;
            this.list[this.pointer].getElementsByTagName('a')[0].className = 'hover';
			/* this.div.scrollTop = 50; */
        }
        if(this.pointer === null ) {           			
			this.pointer = 0;		
            this.list[this.pointer].getElementsByTagName('a')[0].className = 'hover';
        }
    }
} 


/*
	Order Sumamry Panel
*/
LCS.OrderSummary = {
	timer : null,
	
	Open : function(url) {			
		$('orderHistory').innerHTML = "";	
		if(LCS.OrderSummary.timer) {
			clearTimeout(LCS.OrderSummary.timer);
			LCS.OrderSummary.timer = null;
		} 

		new Ajax.Updater('orderHistory', url,
				   {asynchronous:true, evalScripts:false }); 
		$('orderHistory').show();
		$('maskLightbox').show();
		document.location = "#orderHistory";
	},

	Close : function() {
		if(LCS.OrderSummary.timer) {
			clearTimeout(LCS.OrderSummary.timer);
			LCS.OrderSummary.timer = null;
		}
		LCS.OrderSummary.timer = setTimeout("LCS.OrderSummary.fade()",250);	
	},
	
	fade : function() {		
		new Effect.Fade($('orderHistory'), {duration: 0.3});
		new Effect.Fade($('maskLightbox'), {duration: 0.3});
	}	
	
}	


/*
Error Page Panel
*/
LCS.ErrorPage = {
timer : null,

Open : function(url) {			
	$('errorLightbox').innerHTML = "";	
	if(LCS.ErrorPage.timer) {
		clearTimeout(LCS.ErrorPage.timer);
		LCS.ErrorPage.timer = null;
	} 

	new Ajax.Updater('errorLightbox', url,
			   {asynchronous:true, evalScripts:false }); 
	$('errorLightbox').show();
	$('maskLightbox').show();
	document.location = "#errorLightbox";
},

Close : function() {
	if(LCS.ErrorPage.timer) {
		clearTimeout(LCS.ErrorPage.timer);
		LCS.ErrorPage.timer = null;
	}
	LCS.ErrorPage.timer = setTimeout("LCS.ErrorPage.fade()",250);	
},

fade : function() {		
	new Effect.Fade($('errorLightbox'), {duration: 0.3});
	new Effect.Fade($('maskLightbox'), {duration: 0.3});
}	

}	


/*
	Login Panel
*/
LCS.Login = {
	timer : null,
	
	init : function() {
		$('loginDashboard').observe('mouseover', LCS.Login.show);
		$('loginDashboard').observe('mouseout', LCS.Login.hide);		
	},
	
	show : function(open) {
		if(LCS.Login.timer) {
			clearTimeout(LCS.Login.timer);
			LCS.Login.timer = null;
		} 			
		
		$('wrapCart').hide();
		
		//hide select for ie6
		hideSelect();
		
		$('loginDashboard').show(); 	
		$('i_username').observe('keypress', LCS.Login.show);
		$('i_password').observe('keypress', LCS.Login.show);
		if(open == 1) $('i_username').focus();
	},
	
	hide : function() {
		if(LCS.Login.timer) {
			clearTimeout(LCS.Login.timer);
			LCS.Login.timer = null;
		}
		LCS.Login.timer = setTimeout("LCS.Login.fade()",2000);	
		
		//show select for ie6
		showSelect();
		
		
										
	},
	
	fade : function() {		
		new Effect.Fade($('loginDashboard'), {duration: 0.3});
		$('wrapCart').show();		
	}
}															
	

/*
	Show/Hide Panel
*/
LCS.Panel = {
	timer : null,
	panel : null,
	
	show : function(panel) {						
		LCS.Panel.hide();	
		document.location = "#";
		
		if(LCS.Panel.timer) {
			clearTimeout(LCS.Panel.timer);
			LCS.Panel.timer = null;
		}					
		
		$(panel).show(); 
		$('maskLightbox').setStyle({'display':'block'});		
		LCS.Panel.panel = panel;
	},
	
	hide : function() {	
		if(LCS.Panel.timer) {
			clearTimeout(LCS.Panel.timer);
			LCS.Panel.timer = null;
		}
		LCS.Panel.timer = setTimeout("LCS.Panel.fade()",250);
	},
	
	fade : function() {		
		new Effect.Fade($(LCS.Panel.panel), {duration: 0.3});
		new Effect.Fade($('maskLightbox'), {duration: 0.3});				
	}
}	


/*
	Scroll Effect
*/
Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
	initialize: function(element) {
		this.element = $(element);
		var options = Object.extend({
			x:    0,
			y:    0,
			mode: 'absolute'
		} , arguments[1] || {}  );
		this.start(options);
	},

	setup: function() {
		if (this.options.continuous && !this.element._ext ) {
			this.element.cleanWhitespace();
			this.element._ext=true;
			this.element.appendChild(this.element.firstChild);
		}

		this.originalLeft=this.element.scrollLeft;
		this.originalTop=this.element.scrollTop;

		if(this.options.mode == 'absolute') {
			this.options.x -= this.originalLeft;
			this.options.y -= this.originalTop;
		} else { }
	},

	update: function(position) {   
		this.element.scrollLeft = this.options.x * position + this.originalLeft;
		this.element.scrollTop  = this.options.y * position + this.originalTop;
	}
});


/*
	Main Function
*/

var firefox = navigator.userAgent.indexOf('Firefox') != -1
var explorer = navigator.userAgent.indexOf('MSIE') != -1
var explorer7 = navigator.userAgent.indexOf('MSIE 7.0') != -1
var netscape = navigator.userAgent.indexOf('Netscape') != -1
var safari = navigator.userAgent.indexOf('Safari') != -1
var opera = navigator.userAgent.indexOf('Opera') != -1
var camino = navigator.userAgent.indexOf('Camino') != -1
var macintosh = navigator.platform.indexOf('Mac') != -1



//clear input on focus
function clearOnFocus(oTxt) {
	if(!oTxt.defaultValue) {
		oTxt.defaultValue = oTxt.value;
		oTxt.value = ''; 
	}
}

//function to change pics on oneItem page
function changePic(whichPath, whichThumbActive){
	//alert(whichPath)
	$('bigItem').setStyle({backgroundImage:'url("' + whichPath + '")'});
	clearThumbs(whichThumbActive);
	return false;
}

function clearThumbs(whichThumbActive){
	for(i=1; i<10; i++){
		var oneThumb = String("thumb" + i);
		if ($(oneThumb) != null) { 
			$(oneThumb).setStyle({opacity:1});
			$(whichThumbActive).setStyle({opacity:0.4});
		} else {
			break;
		}	
	}
	return false;
}

//function to desactivate personalize mode
function desactivatePersonalize(){
	$("bt_buyPersonalize").setStyle({opacity:0.4});
	$("bt_buyPersonalize").disabled = true;
	$("bt_buyPersonalize").setStyle({cursor:'default'});
	$("btBuy").setStyle({opacity:1});
	$("btBuy").disabled = false;
	$("btBuy").setStyle({cursor:'pointer'});
	$("buy1a").checked = true;
	$("buy1b").checked = false;
	return false;
}

//function to activate personalize mode
function activatePersonalize(){	
	$("btBuy").setStyle({opacity:0.4});
	$("btBuy").setStyle({cursor:'default'});
	$("btBuy").disabled = true;
	$("bt_buyPersonalize").setStyle({opacity:1});
	$("bt_buyPersonalize").disabled = false;
	$("bt_buyPersonalize").setStyle({cursor:'pointer'});
	$("buy1a").checked = false;
	$("buy1b").checked = true;
	return false;
}

//function to activate left or right side of oneItem
function activateSide(whichSide){
	if(whichSide == "left"){
		$("leftSide").addClassName('selectedL');
        $("player").value = "";
		
        $("rightSide").removeClassName('selectedR');
	} else {
		$("rightSide").addClassName('selectedR');
        $("number").value = "";
        $("name").value = "";
		
		$("leftSide").removeClassName('selectedL');
	}
	activatePersonalize();
	return false;
}


//function for changeBG of one Item
function changeBgItem(whichLink){
	$(whichLink).previous('.bgItem').addClassName('selected');
	return false;
}

//function to remove blue BG of one Item
function removeBgItem(whichLink){
	$(whichLink).previous('.bgItem').removeClassName('selected');
	return false;
}

//calculate height to set up content
function calculateHeight(){
	var minHeight = $('wrapLayout').getStyle('height');
	$("bgLayout").setStyle({'height':minHeight});

	var minHeight = $('container').getStyle('height');
	$("maskLightbox").setStyle({'height':minHeight});

	return false;
}

//function for open/close menu
function openMenu(whichLink){
	if(!$(whichLink).next('.body').visible()){
		Effect.BlindDown($(whichLink).next('.body'));
		$(whichLink).setStyle({backgroundImage:'url("/lcs/web/images/bg_blocLinkOn.jpg")'});
		setTimeout(calculateHeight, 1500);
		return false;
	} else {
		Effect.BlindUp($(whichLink).next('.body')); 
		$(whichLink).setStyle({backgroundImage:'url("/lcs/web/images/bg_blocLinkOff.jpg")'});
		setTimeout(calculateHeight, 1500);
		return false;
	}
}


//function for reopen Selection menu
function openSelection(whichLink, whichBloc){
	Effect.Fade($(whichLink).up()); 
	Effect.BlindDown($(whichBloc)); 
	nbMenuSelected -= 1;
	setTimeout(calculateHeight, 1500);
	checkIfAllSelected();
	return false;
}

//function for reopen Selection menu
function closeSelection(whichValue, whichSelected, whichBloc, whichCity){
	nbMenuSelected += 1;
	if(whichCity == "" || whichCity == undefined){
		Effect.Appear($(whichSelected)); 
		$(whichSelected).down().innerHTML = whichValue;
		Effect.BlindUp($(whichBloc)); 
		setTimeout(calculateHeight, 1500);
		checkIfAllSelected();
		return false;
	} else {
		Effect.Appear($(whichSelected)); 
		$(whichSelected).down().innerHTML = whichValue;
		$('city').innerHTML = whichCity;
		Effect.BlindUp($(whichBloc)); 
		setTimeout(calculateHeight, 1500);
		checkIfAllSelected();
		return false;
	}
	
}

//function for open All teams
function openAllTeams(whichAction){
	if(whichAction == 'open'){
		Effect.BlindUp($('middleSmallTeams')); 
		Effect.BlindDown($('middleBigTeams')); 
		setTimeout(calculateHeight, 1500);
		return false;
	} else {
		Effect.BlindUp($('middleBigTeams')); 
		Effect.BlindDown($('middleSmallTeams')); 
		setTimeout(calculateHeight, 1500);
		return false;
	}
}

//function for open All teams
function openAllProducts(whichAction){
	if(whichAction == 'open'){
		Effect.BlindUp($('middleSmallProducts')); 
		Effect.BlindDown($('middleBigProducts')); 
		setTimeout(calculateHeight, 1500);
		return false;
	} else {
		Effect.BlindUp($('middleBigProducts')); 
		Effect.BlindDown($('middleSmallProducts')); 
		setTimeout(calculateHeight, 1500);
		return false;
	}
}

var nbMenuSelected = 0;
//to check if all the left menus have been selected
function checkIfAllSelected(){
	var b = $$('div.filter');
	var dd = b[0];
	if(nbMenuSelected == 7){
		Effect.Fade(dd);
	} else if(nbMenuSelected == 6){
		Effect.Appear(dd);
	}
	return false;
}


String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};

//function for infotip over sports teams
function infotip(whichTeam, whichCity, whichLang,whichID, whichAction){
	
	var htmltext="";
	
	if (whichLang!=null && whichLang.trim()!="" )
	htmltext=whichTeam + "<div class='cityname' name='ciytname" + whichID + "'>" + whichCity + "</div>";
	else
	htmltext="<div class='cityname' name='ciytname" + whichID + "'>" + whichCity + "</div>&nbsp;"+whichTeam;
	
	
	if(whichAction == "show"){
		quelTip = "infotip" + whichID;
		$(quelTip).down().innerHTML = htmltext;
		Effect.Appear($(quelTip)); 
	} else if(whichAction == "hide"){
		quelTip = "infotip" + whichID;
		$(quelTip).down().innerHTML = htmltext;
		Effect.Fade($(quelTip)); 
	}
	return false;
}

//function to change the next and previous buttons
function checkButtons(whichButton){
	if(whichButton == "next-arrow"){
		$("next-arrow").setStyle({backgroundImage:"url('/lcs/web/images/bt_rightArrow_off.png')"});
		$("next-arrow").onclick = "return false;";
		$("next-arrow").setStyle({pointer:"default"});
		$("prev-arrow").setStyle({backgroundImage:"url('/lcs/web/images/bt_leftArrow_on.png')"});
		$("prev-arrow").onclick = function(){my_glider.previous(); checkButtons('prev-arrow');}
		$("prev-arrow").setStyle({pointer:"cursor"});
	} else if(whichButton == "prev-arrow"){
		$("next-arrow").setStyle({backgroundImage:"url('/lcs/web/images/bt_rightArrow_on.png')"});
		$("next-arrow").onclick = function(){my_glider.next(); checkButtons('next-arrow');}
		$("next-arrow").setStyle({pointer:"cursor"});
		$("prev-arrow").setStyle({backgroundImage:"url('/lcs/web/images/bt_leftArrow_off.png')"});
		$("prev-arrow").onclick = "return false;";
		$("prev-arrow").setStyle({pointer:"default"});
	}
	return false;
}

//open add cart in billing information
function openAddCart(){
	var addCartList = $$('.oneBloc .wrapAddCard');
	var monAddCart = addCartList[0];
	if(! monAddCart.visible()){
		Effect.BlindDown(monAddCart); 
		setTimeout(calculateHeight, 1000)
	} else {
		Effect.BlindUp(monAddCart); 
	}
}

//open add cart in billing information
function openAddAddress(){
	var addAddressList = $$('.oneBloc .wrapAddAddress');
	var monAddAddress = addAddressList[0];
	if(! monAddAddress.visible()){
		Effect.BlindDown(monAddAddress); 
		setTimeout(calculateHeight, 1000)
	} else {
		Effect.BlindUp(monAddAddress); 
	}
}


function disableInputs(whichCheckbox){
	myValue = ($(whichCheckbox).getValue());
	
	if(myValue == "true"){
		$('mask').show();
	} else {
		$('mask').hide();
	}
}


//check form f_profile
function checkForm(whichForm){
	var bodyList = $$('body');
	var myBody = bodyList[0];
	
	var errorMsgList = $$('.errorMsg')
	var myError = errorMsgList[0];
	
	if(myBody.hasClassName('fr')){
		var myMsgError = "<p class='red'>Les champs suivants sont erron&eacute;s ou vides :</p>"
		formInputs = $(whichForm).getElementsByTagName("input");
		for(i=0; i<formInputs.length; i++){
			myValue = formInputs[i].value;
			if(myValue == ""){
				inputID = formInputs[i].id;
				switch(inputID){
					case "sel_country":
					myMsgError += "<p class='red'>Pays: <span>Votre pays ne doit pas &ecirc;tre vide</span></p>"; 
					break;
					
					case "i_firstName":
					myMsgError += "<p class='red'>Pr&eacute;nom: <span>Votre pr&eacute;nom ne doit pas &ecirc;tre vide</span></p>"; 
					break;
					
					case "i_name":
					myMsgError += "<p class='red'>Nom: <span>Votre nom ne doit pas &ecirc;tre vide</span></p>"; 
					break;
					
					case "i_address1":
					myMsgError += "<p class='red'>Adresse 1: <span>Votre adresse doit contenir le num&eacute;ro civile et la rue</span></p>"; 
					break;
					
					case "i_address2":
					myMsgError += "<p class='red'>Adresse 2: <span>Votre adresse doit contenir le num&eacute;ro civile et la rue</span></p>"; 
					break;
					
					case "i_city":
					myMsgError += "<p class='red'>Ville: <span>Votre ville ne doit pas &ecirc;tre vide</span></p>"; 
					break;
					
					case "sel_province":
					myMsgError += "<p class='red'>Province: <span>Votre province ne doit pas &ecirc;tre vide</span></p>"; 
					break;
					
					case "i_zip":
					myMsgError += "<p class='red'>Code postal: <span>Votre code postal doit &ecirc;tre dans le format suivant (X1X 1X1). Exemple: (H6R 3B7)</span></p>"; 
					break;
					
					case "i_phone1", "i_phone2", "i_phone3":
					myMsgError += "<p class='red'>T&eacute;l&eacute;phone: <span>Votre num&eacute;ro de t&eacute;l&eacute;phone doit contenir 10 chiffres. Exemple: (514 333 4545)</span></p>"; 
					break;
				}
				myMsgError += "<div class='clearFix'></div>";
				myError.innerHTML = myMsgError;
				$(formInputs[i]).previous('label').addClassName('error');
				calculateHeight();
			}
		}
	} 
}


//var colorsNames = new Array("white","black","red","yellow","blue","grey","green","orange","pink","aqua","purple","earth");

function checkColorsForSize(currentSize) {

//build list of color swatches
	var colorsList = $$('.color a.oneColor');
	var colorCount = 0;
	//hide all swatches
	for(j=0; j<colorsList.length; j++){
		var myColorButton = colorsList[j];
		//myColorButton.setStyle({opacity:0.2})
		myColorButton.style.display = "none";
		myColorButton.onclick = null;
		myColorButton.setStyle({pointer:"default"});
		myColorButton.removeClassName('selected')
		
		//check which color are available
		for(i=0; i<skus.skus.length; i++){
			
			if (skus.skus[i].size == currentSize) {				
				var myColors = skus.skus[i].color.toLowerCase();				
				//show available swatches
				if(myColorButton.id == myColors){
					colorCount++;
					if(colorCount == 1){
						myColorButton.addClassName('selected');
						$('colorId').value=myColorButton.id;							
					} 
					//myColorButton.setStyle({opacity:1});
					myColorButton.style.display = "";
					//myColorButton.myColor = j;
					myColorButton.onclick = changeColorSelected;
					myColorButton.setStyle({pointer:"cursor"});
				} else {
					myMsg = "Désolés, aucune couleur disponible!"
				}
			}
		}		
	}	
	
	if((colorCount == 0) && (skus.skus.length > 0)) {		
		$('colorId').value=skus.skus[0].color.toLowerCase();		
		$('colorSwatch').setStyle({display:"none"});
	} else {
		$('colorSwatch').setStyle({display:"block"});
	}
	return false;
}

//  document.getElementById('colorId').value

function updateSelectedSku() {
	var currentColor = $('colorId').value;	
	var currentSize = $('selHid').value;
	
	if (currentColor.toLowerCase() == 'na') currentColor = '';
	
	//alert("Expected: " + currentColor + ":" + currentSize);

	// Find sku
	for(i=0; i<skus.skus.length; i++) {
		//alert(thisColor + ":" + skus.skus[i].size);
		var thisColor = skus.skus[i].color;
		if (thisColor.toLowerCase()== 'na') thisColor = '';
		if ((String(thisColor).toLowerCase() == String(currentColor).toLowerCase())
				&& (String(skus.skus[i].size).toLowerCase() == String(currentSize).toLowerCase())) {
			updateSku(i);
			//alert('found');
			break;
		}
	}				    				    
}

function updateSku(i) {
	$('skuId').value = skus.skus[i].id;
	$('currentPrice').innerHTML = parseFloat( skus.skus[i].listPrice ).toFixed(2) + " $";
	$('salePrice').innerHTML = parseFloat( skus.skus[i].salePrice ).toFixed(2) + " $";
	if ("true" == skus.skus[i].onSale) {
		$('currentPrice').className = "price regular";
		$('salePrice').style.display = "block";
	} else {
		$('currentPrice').className = "price";
		$('salePrice').style.display = "none";
	}
}

function initMinPriceSku() {
	// init html with minimal price of available skus
	var minPriceIndex = 0;
	var minPrice;
	for(i=0; i<skus.skus.length; i++) {
		var sku = skus.skus[i];
		//alert("sku.onSale = [" + sku.onSale +"]"); 
		if (sku.onSale == "true" ) {
			price = parseFloat( skus.skus[i].salePrice );
		} else {
			price = parseFloat( skus.skus[i].listPrice );
		}
		if (i == 0 || price <= minPrice) {
			//alert("sku.onSale = [" + sku.onSale +"] (price <= minPrice) = (" + price  + " < " + minPrice + ")"); 
			minPrice = price;
			minPriceIndex = i;
		}
	}
	updateSku(minPriceIndex);
	//alert("!!! minPrice = $" + minPrice + "$; minPriceIndex = " + minPriceIndex + " !")
}


function afterChangeSize() {
	var currentSize = $('selHid').value;
	checkColorsForSize(currentSize);				    	
	updateSelectedSku();
}		

//function Make color available depending on the item selected
function checkColors(){
	//build list of color swatches
	var colorsList = $$('.color a.oneColor');
	var colorCount = 0;
	//hide all swatches
	for(j=0; j<colorsList.length; j++){
		var myColorButton = colorsList[j];
		//myColorButton.setStyle({opacity:0.2})
		myColorButton.style.display = "none";
		myColorButton.onclick = null;
		myColorButton.setStyle({cursor:"default"});
		myColorButton.removeClassName('selected')
		
		//check which color are available
		for(i=0; i<skus.skus.length; i++){
			var myColors = new Array;
			myColors[i] = skus.skus[i].color.toLowerCase();
		
			//show available swatches
			if(myColorButton.id == myColors[i]){
				colorCount++;
				if(colorCount == 1){
					myColorButton.addClassName('selected');
				} 
				//myColorButton.setStyle({opacity:1});
				myColorButton.style.display = "";
				//myColorButton.myColor = j;
				myColorButton.onclick = changeColorSelected;
				myColorButton.setStyle({cursor:"pointer"});
			} else {				
				myMsg = "Désolés, aucune couleur disponible!";
			}
		}
	}
	
	if((colorCount == 0) && (skus.skus.length > 0)) {
		$('colorId').value=skus.skus[0].color.toLowerCase();	
		$('colorSwatch').setStyle({display:"none"});
	} else {
		$('colorSwatch').setStyle({display:"block"});
	}	
	return false;
}

//function to add the class Selected to the color swatches
function changeColorSelected(e){
	color = this.id;
	//build list of color swatches
	var colorsList = $$('.color a.oneColor');
	//remove selected class
	for(j=0; j<colorsList.length; j++){
		var myColorButton = colorsList[j];
		myColorButton.removeClassName('selected');
	}
	this.addClassName('selected');
	$('colorId').value=color;
}

function setColor(color) {
	//build list of color swatches
	var colorsList = $$('.color a.oneColor');
	//remove selected class
	for(j=0; j<colorsList.length; j++){
		var myColorButton = colorsList[j];
		myColorButton.removeClassName('selected');
	}
	if($(color)) $(color).addClassName('selected');
	$('colorId').value=color;
	updateSelectedSku();
}

	
// Find the product object
function findObjFromSku(obj,sku){ 
	var _obj = null;
	for(x=0; x<obj.length; x++) {
		if(obj[x].id == sku) {
			_obj = obj[x];		
		}
	}	
	return _obj;
}

// Check Language
function checkLanguage(){
	bodyList = $$('body');
	monBody = bodyList[0];
	if(monBody.hasClassName('fr')){
		$('i_lang2').checked = "checked";
	} else {
		$('i_lang1').checked = "checked";
	}
}

/*
CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only thing you need to change in this file is the following
variables: checkboxHeight, radioHeight and selectWidth.

Replace the first two numbers with the height of the checkbox and
radio button. The actual height of both the checkbox and radio
images should be 4 times the height of these two variables. The
selectWidth value should be the width of your select list image.

You may need to adjust your images a bit if there is a slight
vertical movement during the different stages of the button
activation.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "13";
var radioHeight = "12";
var selectWidth = "190";

/* No need to change anything after this */
document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; z-index: 5; }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				span[a].onmousedown = Custom.pushed;
				span[a].onmouseup = Custom.check;
				document.onmouseup = Custom.clear;
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.choose;
			}
		}
		
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {

				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}

Event.observe(window, "load", Custom.init);



function hideSelect(){
	var selList = $$('.content select');
	if(selList.length!=0){
		for(i=0;i<selList.length;i++){
			selList[i].hide();
		}
	}
	
}

function showSelect(){
	var selList = $$('.content select');
	if(selList.length!=0){
		for(i=0;i<selList.length;i++){
			selList[i].show();
		}
	}
}


// Slow down IE, and problem with DOM refresh with javascript on other script.
function correctPNG() {
	for(var i=0; i<document.images.length; i++) {
		var img = document.images[i]
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			//alert(img.src)
			var imgID = (img.id) ? "id='" + img.id + "' " : ""
			var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			var imgStyle = "display:block;" + img.style.cssText 
			if (img.align == "left") imgStyle = "float:left;" + imgStyle
			if (img.align == "right") imgStyle = "float:right;" + imgStyle
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
			var strNewHTML = "<span class=\"pngFix\" " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
			img.outerHTML = strNewHTML
			i = i-1
		}
	}
}

if (explorer && !explorer7) {
	window.attachEvent('onload', correctPNG);
}
