jQuery.noConflict();

jQuery(document).ready(function($){
	//Scroll to top
	$('a#showtop, a.showtop').click(function(){
	     $('html, body').animate({scrollTop: '0px'}, 400);
	     return false;
	});
	
	//Search form
	$('#search input.text').focus(function(){
		if($(this).attr('rel') === $(this).attr('value')){
			$(this).attr('value', '');
		}
	});

	$('#search input.text').blur(function(){
		if($(this).attr('value') == ''){
			$(this).attr('value', $(this).attr('rel'));
		}
	});
	
	//Shop
	var timer = null;
	$('#area-products li.large a').mouseenter(function(){
		if($.browser.msie && parseInt($.browser.version) <= 8){
			$('#mask-products').css('background', 'none');
		}
		var parentClass = '';
		if($(this).closest('ul').hasClass('left')) parentClass = 'left';
		else if($(this).closest('ul').hasClass('right')) parentClass = 'right';
		else return false;
		var element = $(this).closest('li').find('div.mask-infos').clone(true);
		var index = $(this).closest('li').index('ul.'+parentClass+' li.large');
		if(index+1 == $(this).closest('ul').find('li.large').length && $(this).closest('ul').find('li.large').length >= 7) index --;
		if(timer){
			clearTimeout(timer);
			timer = null
		}
		timer = setTimeout(function(){
			$('#mask-products').html('').append(element);
			if(parentClass == 'right') element.css('left', 480);
			else if(parentClass == 'right') element.css('left', 0);
			element
				.css('top', 160*index-1)
				.css('display', 'block')
				.bind('mouseleave', function(){
					$(this)
						.css('display', 'none')
						.unbind('mouseleave')
					;
					$('#mask-products').fadeOut('normal').html('');
				})
			;
			$('#mask-products').fadeIn('normal');
		}, 500);
		$(this).bind('mouseleave', function(){
			clearTimeout(timer);
			timer = null;
		});
	});
	
	$('#mask-products div.mask-infos').live('click', function(){
		window.location = $(this).attr('rel');
	});
	
	// Fix for PNG transparency issue in IE when crossfading
	if($.browser.msie && parseInt($.browser.version) <= 8){
		var i;
		for (i in document.images) {
		    if (document.images[i].src) {
		        var imgSrc = document.images[i].src;
		        if (imgSrc.substr(imgSrc.length-4) === '.png' || imgSrc.substr(imgSrc.length-4) === '.PNG') {
		            document.images[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + imgSrc + "')";
		        }
		    }
		}
	}
	
	var openAreaProducts = false;
	var openAreaProductsHeight = false;
	$('#area-products li.title a').click(function(e){
		e.preventDefault();
		$('#area-products').closest('.wrap-center').css('overflow', 'hidden');
		$('#area-brands').css('z-index', 1);
		$('#area-products').css('z-index', 2);
		var _width = openAreaProducts?479:959;
		if(!openAreaProducts){
			$('span.open', this).show();
			$('span.close', this).hide();
		}else{
			$('span.open', this).hide();
			$('span.close', this).show();
		}
		
		$('#area-products').animate({
			width: _width
		}, 750, function() {
		    openAreaProducts = !openAreaProducts;
		});
		
		var elementsHeight = Math.ceil($('#area-products ul li.large').length / 2) * 160;
		var _height = openAreaProductsHeight?1119:elementsHeight;
		if(_height > 1119){
			$('#area-products').closest('.wrap-center').css('overflow', 'visible');
			$('#area-products').height(_height);
		}
		openAreaProductsHeight = !openAreaProductsHeight;
	});
	
	var openAreaBrands = false;
	var openAreaBrandsHeight = false;
	$('#area-brands li.title a').click(function(e){
		e.preventDefault();
		$('#area-brands ul li').not('#area-brands ul li:first').fadeOut('fast');
		$('#area-brands').css('z-index', 2);
		$('#area-products').css('z-index', 1);
		var _width = openAreaBrands?479:959;
		var _widthUL = _width + 1;
		if(!openAreaBrands){
			$('span.open', this).show();
			$('span.close', this).hide();
		}else{
			$('span.open', this).hide();
			$('span.close', this).show();
		}
		
		$('#area-brands').animate({
			width: _width
		}, 750, function() {
		    openAreaBrands = !openAreaBrands;
			$('#area-brands ul li').not('#area-brands ul li:first').each(function(){
				$(this).fadeIn(600);
			});
		});
		
		$('#area-brands ul').animate({
			width: _widthUL
		}, 750);
			
		var elementsHeight = (Math.ceil($('#area-brands ul li').length / 6) * 160) + 1;
		var _height = openAreaBrandsHeight?1121:elementsHeight;
		$('#area-brands').closest('.wrap-center').animate({
			height: _height
		}, 1000, function() {
			openAreaBrandsHeight = !openAreaBrandsHeight;
		});
	});
	
	if(location.href.indexOf("#") != -1) {
		var hash = location.href.substr(location.href.indexOf("#"));
		if(hash == '#nos-produits'){
			$('#area-products').width(959);
			$('#area-products').css('z-index', 2);
			$('#area-brands').css('z-index', 1);
			$('#area-products span.open').show();
			$('#area-products span.close').hide();
			openAreaProducts = true;	
		}else if(hash == '#nos-marques'){
			var elementsHeight = (Math.ceil($('#area-brands ul li').length / 6) * 160) + 1;
			$('#area-brands').closest('.wrap-center').height(elementsHeight);
			$('#area-brands').width(959);
			$('#area-brands ul').width(960);
			$('#area-products').css('z-index', 1);
			$('#area-brands').css('z-index', 2);
			$('#area-brands span.open').show();
			$('#area-brands span.close').hide();
			openAreaBrands = true;
			openAreaBrandsHeight = 479;
		}
	}
	
	/*var $contextHover = false;
	$('#menu-area li a').mouseenter(function(e){
		e.preventDefault();
		if($contextHover) return false;
		$contextHover = true;
		handlerOnClickMenu(this);
	});*/
	
	$('#menu-area li a').click(function(e){
		e.preventDefault();
		handlerOnClickMenu(this);
	});
	
	$('#header .menu a.close').click(function(e){
		e.preventDefault();
		handlerOnClickMenu('#' + $(this).attr('rel'));
	});
	
	function handlerOnClickMenu(_this){
		if($(_this).hasClass('open')){
			$(_this).removeClass('open');
			$('#' + $(_this).attr('rel')).slideUp('slow');
			$contextHover = false;
			return false;
		}else{
			if($('#menu-area li a.open').length > 0){
				$('#menu-area li a.open').each(function(){
					$(this).removeClass('open');
					$('#' + $(this).attr('rel')).slideUp('slow', function(){
						$(_this).addClass('open');
						$('#' + $(_this).attr('rel')).slideDown('normal');
					});
				});
			}else{
				$(_this).addClass('open');
				$('#' + $(_this).attr('rel')).slideDown('normal');
			}
		}
	}
	
	//$('#menu-area li a').click(function(e){});
	
	/*$('div.bloc-control li a').live('click', function(e){
		e.preventDefault();
		$(this).toggleClass('active');
	});*/
	
	if($('.mySelect').length > 0){
		var oHandler = $('.mySelect').msDropDown().data('dd');
		//oHandler.visible(true);
	}
	
	$('table#declinations tr').mouseenter(function(){
		$(this).addClass('hover');
	});
	
	$('table#declinations tr').mouseleave(function(){
		$(this).removeClass('hover');
	});
	
	$('#product .infos p.more a').click(function(e){
		e.preventDefault();
		var temp = $(this).attr('rel');
		$(this).attr('rel', $(this).text());
		$(this).text(temp);
		//$('#product .infos .description-long').slideToggle('slow');
		$('#product .infos .description-long').animate({opacity: 'toggle', height: 'toggle'}, 'slow'); 
	});
	
	if($("#slider-range").length > 0){
		$("#slider-range").slider({
			range: true,
			min: 0,
			max: $('#slider-range-prices').attr('rel'),
			values: [ parseInt($('#slider-range-prices span.from span').html()), parseInt($('#slider-range-prices span.to span').html()) ],
			slide: function( event, ui ) {
				$('#slider-range-prices span.from span').html(ui.values[0]);
				$('#slider-range-prices span.to span').html(ui.values[1]);
			}
		});
	
		$('#slider-price a.submit').click(function(e){
			e.preventDefault();
			var url = $(this).attr('href');
			url += '&price[from]=' + $('#slider-range-prices span.from span').html() + '&price[to]=' + $('#slider-range-prices span.to span').html();
			window.location = url;
		});
	}
	
	
	/* SHADOWBOX */
	//Pop-in
	//Shadowbox.init({skipSetup: true, flashParams:{bgcolor:"#FFFFFF"}});
	$('a.popin').click(function(e){
		e.preventDefault()
		var config = $(this).attr('rel').split('_');
		var content = $($(this).attr('href')).clone();
		content.find('.popin-access').css('display', 'block');
		var width = $($(this).attr('href')).find('.popin-access').innerWidth();
		var height = $($(this).attr('href')).find('.popin-access').innerHeight();
		Shadowbox.open({
			content: content.html(),
			player: 'html',
			title: '',
			height: height,
			width: width
		});
		if(config[0] == 'hide') $('#sb-info').hide(); else $('#sb-info').show();
	});
	$('a.popin-access-close').live('click', function(e){
		e.preventDefault()
		Shadowbox.close();
	});
	
	var _sendLoadCurrent = false;
	$('#rendezvousSubmit').live('click', function(e){
		e.preventDefault();
		if(_sendLoadCurrent) return false;
		_sendLoadCurrent = true;
		var _form = $(this).closest('form');
		$.ajax({
			url: _form.attr('action'),
			type: 'POST',
			data: _form.serialize(),
			success: function(response){
				_sendLoadCurrent = false;
				if(response == 'nok'){
					_form.find('.message')
						.addClass('error')
						.removeClass('success')
						.html("Impossible d'envoyer votre demande. Remplissez correctement tous les champs ou recommencez.")
						.show()
					;
				}else if(response == 'ok'){
					_form.find('.message')
						.addClass('success')
						.removeClass('error')
						.html("Votre demande a bien été envoyée.")
						.show()
					;
					_form.find('.input-text').val('');
					
				}else{
					return false;
				}
			}
		});
	});


	/* SORT */
	$('#declinations th.sort a').click(function(e){
		e.preventDefault();
		var sortby = $(this).attr('id');
		var reg = new RegExp("(sort-by-)", "g");
		var sort = sortby.replace(reg, '');
		if(!sort || !sortby.match(reg)) return false;
		
		$('#declinations th.sort a').removeClass('active');
		$(this).addClass('active');
		if($(this).hasClass('asc')) $(this).removeClass('asc').addClass('desc');
		else if($(this).hasClass('desc')) $(this).removeClass('desc').addClass('asc');
		else $(this).addClass('asc');
		
		var trs = $(this).closest('table').find('tbody tr');
		trs.sortElements(function(a, b){
			var a = $('td.' + sort, a);
			var b = $('td.' + sort, b);
			if(sort == 'name'){
				var a = a.find('a');
				var b = b.find('a');
			}
			var parent = $('th.sort a#sort-by-' + sort, a.closest('table'));
			if(parent.hasClass('asc'))
		    	return a.text() > b.text() ? 1 : -1;
			if(parent.hasClass('desc'))
			    return a.text() < b.text() ? 1 : -1;
			return false;
		});
		var $count = 1;
		trs.removeClass('altern');
		trs.each(function(){
			if($count % 2 == 0) $(this).addClass('altern');
			$count++;
		});	
	});
	$('#sort-by-name').click();
	
	
	/* DELIVERY SPECIAL */
	$('.delivery_special input[@name=delivery_special]:radio').change(function(e){
		if($(this).attr('id') == 'delivery_special_other'){
			$('#page .btn-checkout').hide();
			var content = $('#popup-delivery').clone();
			content.find('.popin-access').css('display', 'block');
			var width = $('#popup-delivery .popin-access').outerWidth(true);
			var height = $('#popup-delivery .popin-access').outerHeight(true);
			Shadowbox.open({
				content: content.html(),
				player: 'html',
				title: '',
				height: height,
				width: width
			});
			$('#sb-info').hide();
			$('#sb-wrapper, #sb-wrapper-inner').height($('#sb-container .popin-access').outerHeight(true));
			$('#sb-wrapper, #sb-wrapper-inner').width($('#sb-container .popin-access').outerWidth(true));
		}else{
			$('#page .btn-checkout').show();
		}
	});
	
	/* Hack bottom line list products */
	if($('#list-products').length > 0){
		if($('#controls').outerHeight(true) > $('#list-products').outerHeight(true)){
			$('#list-products li.last').removeClass('last');
		}else{
			var lines = Math.round($('#list-products').height() / $('#list-products li:eq(0)').outerHeight(true));
			$('#list-products li').each(function(){
				if($(this).position().top > ((lines - 1) * $('#list-products li:eq(0)').outerHeight(true)) || lines == 1){
					if(!$(this).hasClass('last')){
						$(this).addClass('last');
					}
				}
			});
		}
	}
	
	/* Devis commande étranger */
	$('#sb-container #send-devis').live('submit', function(e){
		e.preventDefault();
		$('#sb-container #send-devis .validation-advice').remove();	
		var elements = $('#sb-container #send-devis').map(function(){ return $.makeArray(this.elements); });
		var error = false;
		elements.each(function(){
			if($(this).hasClass('required-entry') && $(this).val() == ''){
				$('<div id="advice-required-entry" class="validation-advice" style="display:none;">Ce champ est obligatoire.</div>').insertAfter(this);
				error = true;
			}
		});
		$('#sb-container #send-devis .validation-advice').fadeIn('300');
		$('#sb-wrapper, #sb-wrapper-inner').height($('#sb-container .popin-access').outerHeight(true));
		$('#sb-wrapper, #sb-wrapper-inner').width($('#sb-container .popin-access').outerWidth(true));
		if(!error){
			$('#sb-container #submit-devis').val('En cours...');
			$.ajax({
				url: devisUrl,
				data: $('#sb-container #send-devis').serialize(),
				dataType: 'json',
				type: 'POST',
				success: function(response){
					$('#sb-container ul.messages li').removeClass('error').html('').hide();
					if(response.error){
						$('#sb-container ul.messages li').addClass('error').html(response.error).fadeIn('300');
					}else if(response.success){
						alert(response.success);
						Shadowbox.close();
					}
					$('#sb-container #submit-devis').val('Envoyer');
					$('#sb-wrapper, #sb-wrapper-inner').height($('#sb-container .popin-access').outerHeight(true));
					$('#sb-wrapper, #sb-wrapper-inner').width($('#sb-container .popin-access').outerWidth(true));
				}
			});
		}
	});
});

