var my_CloudCarousel = null;

$(document).ready(function(){
	
	if(navigator.appVersion.indexOf('MSIE 6') >=0) toggleMenuPrincipal();	//fix ie6 problems

	if($('#select-news-filter').length > 0){
		$('#select-news-filter option').click(function(){
			if($(this).val() !='#') $('#news-filter').submit();			
		});
	}
		
	if($('#select-gamme-filter').length > 0){
		$('#select-gamme-filter').change(function(){
			if($(this).val() !='#')
				$(location).attr('href',$(this).val());
			else
				$(location).attr('href','/catalogue');
		});
	}
	//initScrollpane();
	
	init_vcarousel();

	init_hcarousel();
	
	init_modalbox();

	init_slideshow();
	
	init_slideshow_modal();
	
	init_print_link();
	
	init_submit_link();
		
	init_quotation_form();

	init_callback();
	
	init_form_invite();

	init_contentbox_table();
	
	init_googlemap();

	init_accordion();

	$('.min-box .frame').html('<span>'+$('.min-box .frame').html()+'</span>').prepend($('<div/>').attr('class','bg'));	
	
	init_caroussel_home();
	
	init_vertical_menu();
	
	init_banner();
	
	initialize_textbox_blur_focus();

	if ($("a[rel=lightbox]").length>0) {
		$("a[rel=lightbox]").lightBox({
			fixedNavigation:true,
			imageLoading: 'http://kpark-com.homologation.kpark.com/media/images/lightbox-ico-loading.gif',
			imageBtnClose: 'http://kpark-com.homologation.kpark.com/media/images/lightbox-btn-close.gif',
			imageBtnPrev: 'http://kpark-com.homologation.kpark.com/media/images/lightbox-btn-prev.gif',
			imageBtnNext: 'http://kpark-com.homologation.kpark.com/media/images/lightbox-btn-next.gif',		
			txtOf:"de"
		});		
	}
	
	if (window.PIE) {
		$('.css3, .main-content, .shadowed').each(function() {
		  PIE.attach(this);
		});
	}	
	
});

function send_gamme2friend(id_gamme) {
	$("#Id_Gamme").val(id_gamme);
}
// #### TEXTBOX BLUR/FOCUS
function initialize_textbox_blur_focus() {
		
	$('input[type=text].focusable').focus(function() {
		if ($(this).attr("title").length>0) 
			if ($(this).val() == $(this).attr("title"))
				$(this).val("");		
	});	

	$('input[type=text].focusable').blur(function() {
		if ($(this).attr("title").length>0) 
			if ($(this).val() == "")
				$(this).val($(this).attr("title"));
	});	
	
}

//________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
function init_banner() {
	
	if ($("#banner").length<=0) return false;
	var swf_filename = $("#banner a:first").attr("alt");

	if (typeof(swf_filename)=="undefined") swf_filename = "";
	
	if (swf_filename.length>0) {
		var swf_title = $("#banner a:first").attr("title");
		var swf_width = 728;
		var swf_height = 90;
		if (swf_title.length>0) {
			dummy = swf_title.split("x");
			if (dummy.length==2) {
				swf_width = dummy[0];
				swf_height = dummy[1];
			}
		}
		var flashvars = {};
		var params = {'wmode':'transparent'};
		var attributes = {};
		//alert(swf_filename + " : " +swf_width+"x"+swf_height);
		swfobject.embedSWF(swf_filename, "banner", swf_width, swf_height, "9.0.0" ,"expressInstall.swf", flashvars, params, attributes);
	}	
}

function init_vcarousel() {
	
	if($('.vcarousel').length > 0){
		$('.vcarousel').jcarousel({
			vertical:true,
			scroll: 4
		});
	}	
}
function init_hcarousel() {
	
	if($('#video_carousel').length > 0){
		$('#video_carousel').jcarousel();
	}	
}

function init_modalbox() {
	
	if($('.modal-box').length > 0){
		$('.modal-box').each(function(i,modal){
			if($(modal).hasClass('modal-slideshow')){
				$(modal).jqm({
					trigger: "a."+$(modal).attr('id')+"",
					toTop:true,
					overlay:60,
					onShow: function(e){
						$(modal).find('.modal-slideshow-controller-prev').css('left','-33px');
						$(modal).find('.modal-slideshow-controller-next').css('right','0px');
						$(modal).show();
					}
				});
			} else{
				$(modal).jqm({
					trigger: "a[href='#"+$(modal).attr('id')+"']",
					toTop:true,
					overlay:60,
					onHide: function(e){
						$('#flash-holder').append($('#video-player'));
						$('.jqmOverlay').remove();
						$(modal).hide();
					}
				});
			}
			$(modal).css('top','50px');
			$(modal).hide();
		});
	}
	
}
function init_slideshow() {
	
	if($('.slideshow-holder').length > 0){
		$('.slideshow-holder').each(function(i,holder){
			$(holder).find('.total').html($(holder).find('.slideshow > img').length);
			$(holder).find('.slideshow').cycle({
				// fx:'scrollHorz',
				// speed:1500,
				prev:'.slideshow-holder:eq('+i+') .prev',
				next:'.slideshow-holder:eq('+i+') .next',
				before: function(curelem,nextelem,options,flag){
					$(holder).find('.current').html($(this).index('.slideshow img')+1);
					$(holder).find('.main-title').html(this.alt);
				},
				timeout:5000
			}).append($(holder).find('.slideshow-controller').css({
				'position':'absolute',
				'bottom':'0',
				'left':'50%',
				'margin-left':'-45px'
			})).hover(
				function(){
					$(holder).find('.slideshow').cycle('pause');
					//$(holder).find('.slideshow-controller').slideDown();
				},
				function(){
					$(holder).find('.slideshow').cycle('resume');
					//$(holder).find('.slideshow-controller').slideUp();
				}
			);
		});
	}	
}

function init_slideshow_modal() {
	
	if($('.modal-slideshow-holder').length > 0){
		$('.modal-slideshow-holder').each(function(i,holder){
			$(holder).find('.slideshow').cycle({
				fx:'scrollHorz',
				speed:1000,
				prev:'.modal-slideshow-holder:eq('+i+') span.prev',
				next:'.modal-slideshow-holder:eq('+i+') span.next',
				before: function(curelem,nextelem,options,flag){
					$(holder).find('.main-title').html(this.alt);
				},
				timeout:0
			}).append(
				$(holder).find('.modal-slideshow-controller-holder-prev').hover(function(e){
					$(holder).find('.modal-slideshow-controller-prev').animate({left:0});
				}, function(){
					$(holder).find('.modal-slideshow-controller-prev').animate({left:-33});
				})
			).append(
				$(holder).find('.modal-slideshow-controller-holder-next').hover(function(e){
					$(holder).find('.modal-slideshow-controller-next').animate({right:0});
				}, function(){
					$(holder).find('.modal-slideshow-controller-next').animate({right:-33});
				})
			);
		});
	}	
}

function init_submit_link() {
	
	if($('a.submit-link').length > 0){
		$('a.submit-link').click(function(e){ //make <a> behave like <input submit/>
			$(this).siblings("input[type='submit']")[0].click();
			return false;
		});
	}	
	
	$('.click-submit').click(function() {
		$('#news-detail-rubrique').submit();
		return false;
	});	
}

function init_print_link() {
	if($('.print-link').length > 0){
		$('.print-link').click(function(){
			window.print();
			return false;
		});
	}	
}

function init_quotation_form() {
	
	//Validate
	if($('#quotation-form').length > 0){
			
		$.validator.addMethod("TEL", function(value, element, param) {
			return value.match(new RegExp("^" + param + "$"));
		}, "Le format de votre numéro de téléphone n'est pas valide.");

		$('#quotation-form').validate({
			rules: {
				Str_Tel : { TEL: "0[1-6789]([-. ]?[0-9]{2}){4}", minlength: 10},					
				Str_Email : { email: true }				
			},
			messages:{
				Str_Civilite: {required:"Veuillez indiquer votre civilité"},
				Str_Nom : {required:"Veuillez indiquer votre nom"},
				Str_Prenom : {required:"Veuillez indiquer votre prénom"},
				Str_Email : "Veuillez indiquer une adresse email valide",
				Str_Tel : {required:"Veuillez indiquer un n° de téléphone", TEL: "Le format de votre numéro de téléphone n'est pas valide."}
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent('div'));
				initScrollpane();
			}
		});
	}	
}

function init_callback() {
	
	if($('#form-add-YAKA_Callback').length > 0){
		$.validator.addMethod("TEL", function(value, element, param) {
			return value.match(new RegExp("^" + param + "$"));
		}, "Le format de votre numéro de téléphone n'est pas valide.");
		$('#form-add-YAKA_Callback').validate({
			rules: {
				Str_Tel : { TEL: "0[1-6789]([-. ]?[0-9]{2}){4}",
				minlength: 10 }
			},
			errorPlacement:function(error,element){
				if($('#footer > label.error').length == 0)
					error.appendTo(element.parents('div#footer')).addClass('error-callback');
			},
			unhighlight:function(element,errorClass){
				$(element).removeClass(errorClass);
				$('#footer > label.error').remove();
			}
		});
	}	
	
	$('#input-callback').focus(function(){
		if($(this).val() == 'Saisissez votre numéro') $(this).val('');
	});
	$('#input-callback').blur(function(){
		if($(this).val() == '') $(this).val('Saisissez votre numéro');
	});	
}

function init_form_invite() {
	
	if($('#form-invite').length > 0){
		$('#form-invite').validate({
			errorPlacement:function(error,element){
				error.remove();
			},
			 highlight: function(element, errorClass) {
				$(element).parent().addClass(errorClass);
			},
			 unhighlight: function(element, errorClass) {
				$(element).parent().removeClass(errorClass);
			}

		});
	}	
}
function init_contentbox_table() {
	
	if($('.content-box table').length > 0){
		$('.content-box table').each(function(i,table){
			$(table).find('thead th:first').addClass('first');
			$(table).find('thead th:last').addClass('last');
			$(table).find('tbody tr').each(function(o,tr){
				if(o%2==0) $(tr).addClass('odd');
				else $(tr).addClass('even');
				if(o==0) $(tr).addClass('first');
				if(o==$(table).find('tbody tr').length-1) $(tr).addClass('last');
			});
		});
	}
	
}

function init_accordion() {
	
	if($('.list-accordion').length > 0){
		$('.list-accordion > li:not(:first)').addClass('collapsed').find('.toggle').hide();
		initScrollpane();
		$('.list-accordion > li .handler').click(function(){
			if($(this).parent().hasClass('collapsed')){
				$(this).parent().siblings('li:not(.collapsed)').find('.toggle').slideUp('normal',function(){
					$(this).parent().addClass('collapsed');
					initScrollpane();
				});
				$(this).siblings('.toggle').slideDown();
				$(this).parent().removeClass('collapsed');
			}
		});
	}
	else{
		if($('#map-holder').length == 0) initScrollpane();
	}	
}
function init_googlemap() {
	if($('#map-holder').length > 0) loadMaps();
}

function init_vertical_menu() {
	
	if ($(".vmenu").length<=0) return false;	
	
	$(".vmenu > li").each(function() {
		
		$(this).hover(
			function() {				
				$(this).removeClass().addClass("hovered");
				$(this).find("ul:first").fadeIn("fast");
			},
			function() {
				$(this).find("ul:first").hide();
				$(".vmenu > li").each(function() {
					$(this).removeClass("hovered");
				});
			})
	});
}


function init_caroussel_home() {
	
	if ($("#caroussel_home").length>0) {
	
		var my_autoRotate = 'right';
		if ($("#caroussel_autoRotate").length>0) my_autoRotate = $("#caroussel_autoRotate").val();
		
		my_reflHeight = 30;
		my_ypos = 60;
		if(navigator.appVersion.indexOf('MSIE')>=0) {
			my_reflHeight = 0;
			my_ypos = 70;
		}
		$("#caroussel_home").CloudCarousel({		
				
			xPos:368,
			yPos: my_ypos,
			minScale: 0.1,
			xRadius:280,
			yRadius:-50,
			speed:0.2,
			autoRotate: my_autoRotate,
			autoRotateDelay:3000,
			mouseWheel:false,		
			reflHeight:my_reflHeight,
			reflGap:0,
			reflOpacity:0.3,
			bringToFront:true,
			buttonLeft: $("#carroussel_arrow_left"),
			buttonRight: $("#carroussel_arrow_right")
		});		
		
		$("#caroussel_home").find(".cloudcarousel").bind('mousedown',this,function(evt) {
			
			var count_img = $(".cloudcarousel").length;
			var img_index = $(evt.target).data('itemIndex');
			var front_index = $(evt.target).parent().parent().data("cloudcarousel").frontIndex;
			if (front_index<0) front_index = parseInt(count_img) + parseInt(front_index);
	
			if (img_index == front_index) {
				var url = $(this).attr("title");
				if (url.length>0) 
					document.location.href=  url;
			}		
		});
	}
	
	if ($("#caroussel_animation").length>0) {
	
		var swf_filename = $("#caroussel_animation").attr("alt");
	
		if (swf_filename.length>0) {
			var swf_title = $("#caroussel_animation").attr("title");
			var swf_width = 575;
			var swf_height = 310;
			if (swf_title.length>0) {
				dummy = swf_title.split("x");
				if (dummy.length==2) {
					swf_width = dummy[0];
					swf_height = dummy[1];
				}
			}
			var flashvars = {};
			var params = {'wmode':'transparent'};
			var attributes = {};

			swfobject.embedSWF(swf_filename, "caroussel_animation", swf_width, swf_height, "9.0.0" ,"expressInstall.swf", flashvars, params, attributes);
		}	
		
	}

}
function initScrollpane(){
	
	//Scroll pane		
	if(!$('body').hasClass('content-gammes') && !$('body').hasClass('content-model')){ // no scrollpane on gamme page
		
		var scrollPaneSettings = {
			scrollbarWidth: 17,
			reinitialiseOnImageLoad: true,
			verticalDragMinHeight:16,
			verticalDragMaxHeight:16
		};
		
		$('.scroll-pane').jScrollPane(scrollPaneSettings);		
		
		$('.jScrollPaneContainer').each(function(i,e){
			if((navigator.appVersion.indexOf('MSIE 6') >=0 || navigator.appVersion.indexOf('MSIE 7') >=0) && $(e).find('.jScrollPaneTrack').length != 0){ // corrige le probleme de background-position de la scrollbar sur ie
				$(e).css('background-position','100% '+($(e).height()-402)+'px');
			}
			
			$(e).removeClass('no-scroll');
			
			//console.log($(e).find('.jScrollPaneTrack'));
			if($(e).find('.jScrollPaneTrack').length == 0){
				
				if($('.type-carusel').hasClass('carusel-one-item-many')) {
					$(e).addClass('no-scroll');
					$(e).css('width',615+'px');
					$(e).find('.scroll-pane').css('width',615+'px');
				} else if($('.type-carusel').hasClass('carusel-alu')) {
					$(e).addClass('no-scroll');
					$(e).css('width',307+'px');
					$(e).find('.scroll-pane').css('width',307+'px');
				} else if($('.type-carusel').hasClass('carusel-one-item')) {
					$(e).addClass('no-scroll');
					$(e).css('width',625+'px');
					$(e).find('.scroll-pane').css('width',625+'px');
				} else if($(e).find('.scrolltop').length > 0) {
						//alert('scrolltop');
						$(e).addClass('no-scroll');
						$(e).css('width',434+'px');
						$(e).find('.scroll-pane').css('width',434+'px');
				} else if($(e).find('.scrollbottom').length > 0) {
						//alert('bottom');
						$(e).addClass('no-scroll');
						$(e).css('width',445+'px');
						$(e).find('.scroll-pane').css('width',445+'px');
				} else {
					$(e).addClass('no-scroll');
					$(e).css('width',674+'px');
					$(e).find('.scroll-pane').css('width',674+'px');
				}
			}
		});
	
	}
}

//__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
function toggleMenuPrincipal(){
	$.each($('#main-nav > li'), function(i, li){
		$(li).hover(
			function(){
				$(li).addClass('hover');
				$(li).addClass('main'+(i+1)+'-hover');
			},
			function(){
				$(li).removeClass('hover');
				$(li).removeClass('main'+(i+1)+'-hover');
			}
		);
		$(li).find('.category-title').append($('<div/>').append($(li).find('.category-title a')));
	});
}



// ____GOOGLE MAP FUNCTIONS________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
function loadMaps(){


	gdir = null; // GDirections ( pour calcul d'itinéraire )

	tinyIconRouge= null;
	tinyIconGris= null;

	markers = [];
	markers_is_hidden = true;

	if (GBrowserIsCompatible()) {
	  	GMap2.prototype.boundTo = function(bounds, delta) {
				if (typeof(delta) != "number") {delta = 0;}
 				var zoom = this.getBoundsZoomLevel(bounds) + delta;
 				if (zoom != this.getZoom()) {
 						this.setCenter(bounds.getCenter(), zoom);
 				} else {
 						this.panTo(bounds.getCenter());
 				}
		};
		var mapObj = $("#googlemap")[0];
		if (mapObj != "undefined" && mapObj != null) {
			map = new GMap2(mapObj);
			GEvent.addListener(map, "load", function() {
				//alert('map loaded');
				//initScrollpane();
			});
			map.setCenter(new GLatLng(47.000000, 2.559814), 5, G_NORMAL_MAP);
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.addControl(new GScaleControl());
			GEvent.addListener(map, "zoomend", function() {
					var zoomlevel = map.getZoom();
					if ( zoomlevel >= 6)
					{
						showAllMarkers();
					}
					else
					{
						hideAllMarkers();
					}
			});
			tinyIconRouge = new GIcon();
			tinyIconRouge.image = "/media/images/picto_rouge.png";
			tinyIconRouge.shadow = "/media/images/picto_ombre.png";
			tinyIconRouge.iconSize = new GSize(40, 22);
			tinyIconRouge.shadowSize = new GSize(40, 22);
			tinyIconRouge.iconAnchor = new GPoint(13, 22);
			tinyIconRouge.infoWindowAnchor = new GPoint(16, 1);
			markerOptionsRouge = { icon:tinyIconRouge };

			tinyIconGris = new GIcon();
			tinyIconGris.image = "/media/images/picto_gris.png";
			tinyIconGris.shadow = "/media/images/picto_ombre.png";
			tinyIconGris.iconSize = new GSize(40, 22);
			tinyIconGris.shadowSize = new GSize(40, 22);
			tinyIconGris.iconAnchor = new GPoint(13, 22);
			tinyIconGris.infoWindowAnchor = new GPoint(16, 1);
			markerOptionsGris = { icon:tinyIconGris };
			loadRegions();
			gdir = new GDirections(map, $('#stores-direction')[0]);
			GEvent.addListener(gdir,"addoverlay",function(){
					setTimeout("gdir.getMarker(1).hide();",1);
					setTimeout("initScrollpane();",1000);
			});
			geocoder = new GClientGeocoder();
			loadDynamicElements();
		}
	} else {
		alert("Sorry, the Google Maps API is not compatible with this browser.");
	}

}
function loadRegions() {

	var max_zoom_regions = 1;

	var xmlObj;
    if (window.XMLHttpRequest) { // Mozilla, Safari, IE7 ...
        xmlObj = new XMLHttpRequest();
    }else if (window.ActiveXObject) { // Internet Explorer 6
        xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
    }

	xmlObj.open('GET', 'media/js/regions.xml', true);

	xmlObj.onreadystatechange = function() {
		
		if( xmlObj.readyState == 4 ) {
			
			var regions = [];
			polys = xmlObj.responseXML.documentElement.getElementsByTagName("poly" );

			for( var i = 0; i < polys.length; i++ ) {
				
				var poly = polys[i];
				var name = poly.getAttribute("name");
				var color = poly.getAttribute("color");
				var dep_nbrs = poly.getAttribute("dep").split(",");
				var points = poly.getElementsByTagName("point");
				
				var pts = [];
				for( var j = 0; j < points.length; j++ ) {
					lat = parseFloat(points[j].getAttribute("lat"));
					lng = parseFloat(points[j].getAttribute("lng"));
					pts.push( new GLatLng( lat, lng ) );
				}

				var gpolygone = new GPolygon(pts,"#000000",1,1,color,0.2, {clickable: true});
				gpolygone.dep_nbrs_ = dep_nbrs;
				gpolygone.label_ = name;

				GEvent.addListener(gpolygone, 'click', function(){
							 	map.closeInfoWindow();
								map.boundTo(this.getBounds(), 0);
							});


				GEvent.addListener(gpolygone, 'mouseover', function(){
								map.getDragObject().setDraggableCursor("hand");
							});

				GEvent.addListener(gpolygone, 'mouseout', function(){
								map.getDragObject().setDraggableCursor("auto");
							});

				map.addOverlay(gpolygone);
			}
		}
	};

	xmlObj.send(null);
}

function hideAllMarkers() {
	
	if (markers_is_hidden == false) {
		//console.log("hideAllMarkers");
 		for( var i = 0; i < markers.length; i++ )
			markers[i].hide();
		markers_is_hidden = true;
	}
}

function showAllMarkers()
{
	if (markers_is_hidden == true) {
		for( var i = 0; i < markers.length; i++ )
			markers[i].show();
		markers_is_hidden = false;
	}
}

function showMarkers(departement_number) {
 	
 	for( var i = 0; i < markers.length; i++ ) {
		if (markers[i].depNbr_ == departement_number)
			markers[i].show();
	}
}

function showAddress(address) {
	
	geocoder.getLatLng(
	address,
	function(point) {
		if (!point) {
			alert(address + " not found");
		} else {
			map.setCenter(point,13);
			var marker = new GMarker(point);
			map.addOverlay(marker);
			//marker.openInfoWindowHtml(address);
		}
	});
}
function addMarker(address) {

	geocoder.getLatLng(
	address,
	function(point) {
		if (!point) {
			//alert(address + " not found");
		} else {
			map.setCenter(point,13);
			var marker = new GMarker(point);
			map.addOverlay(marker);
			//marker.openInfoWindowHtml(address);
		}
	});
}
function showAddressForm(){
	
	$('#stores-form').show();
	initScrollpane();
	$('#input-address').focus();
}

/* reprise de code de l'ancien site pour faire refonctionner l'ancien formulaire */
function get_xmlhttp() {

	var xmlhttp = false ;
	/* on essaie de cr�er l'objet si ce n'est pas d�j� fait */
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest() ;
		} catch (e) {
			xmlhttp = false ;
		}
	}
	return xmlhttp ;
}

