$(document).ready(function(){
  	
	$(document).pngFix();
	searchMenu();
	newsletterForm();
	$('a.zoom').fancybox({
		'titleShow' : false
	});
	$('a.zoom80').fancybox();
	
	$("a.iframe").fancybox({
		'centerOnScroll': false,
		'height': 500,
		'width': 500,
		'padding' :2,
		'type': 'iframe'
	}); 
	$("a.iframesupport").fancybox({
		'centerOnScroll': false,
		'height': 500,
		'width': 800,
		'padding' :5,
		'hideOnOverlayClick':false,
		'type': 'iframe'
	});
	$("a.iframebig").fancybox({
		'centerOnScroll': false,
		'height': 650,
		'width': 990,
		'padding' :2,
		'type': 'iframe'
	});
	$("a.modifImgAnnonce").fancybox({
		'centerOnScroll': false,
		'height': 320,
		'width': 500,
		'padding' :2,
		'type': 'iframe',
		'onClosed' : function(){parent.location.reload();}
	});
	
	loginBox();
	carousel();
	handleForms();
	debug();
	datePickerInit();

	$().maxlength();
	
	imagePreview();
	productPreview();
	
	if($('div#diaporama').length > 0){
		//diaporama();
	}
	tooltip();

		
	handleMenu();

	selectDropdown();
	
	listings();
	
});

/**************** FONCTIONS ****************/
timeoutclose = 100;
closetimer = null;

timeoutopen = 200;
opentimer = null;

this.productPreview = function(){	
	/* CONFIG */

		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.productPreview").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='preview'><img src='"+ $(this).attr('rel') +"' alt='Image preview' /></p>");								 
		$("#preview")
			.css("top",(e.pageY - 100) + "px")
			.css("left",(e.pageX + 20) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.productPreview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - 100) + "px")
			.css("left",(e.pageX + 20) + "px");
				
	});
	//$("a.productPreview").click(function(){return false;});
};


function handleMenu(){
	
	$("ul#mainMenu > li").hoverIntent({
			over: function(){
				$("td.tdScat ul").hide();
				displayMenu($(this));
			},
			timeout :100,
			out: function(){
				hideMenu();
				$("td.tdScat ul").hide();
			}
		}
	);
	
	$("td.cat li > a").hoverIntent({
		over: function(){
			var id = $(this).attr('id');
			id = id.split('_');
			id = id[1];
			$("td.tdScat ul").hide();
			$("td.tdScat ul#cat_" + id).show();
			
		},
		sensitivity : 15,
		out: function(){}
	});	
}

function displayMenu(obj){
	obj.children('div').show();
	obj.children('h3').children('a').attr('class','current');
}

function hideMenu(){
	$('ul#mainMenu li h3 > a').removeAttr('class');
	$('div.menu-depliant').hide();
}






function selectDropdown(){
	
	//if ($.browser.msie){
		$('select.wide')
		.bind('mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })
		.bind('click', function() { $(this).toggleClass('clicked'); })
		.bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})
		.bind('change blur', function() { $(this).removeClass('expand clicked'); });
	//}
}

function slideSwitch() {
    
	var $divs = $('#slider div');
	var $active = $('#slider div.active');
	
	var $thumbs = $('#thumbsdiapo div');
	var $activeThumb = $('#thumbsdiapo div.active');
	
    if ( $active.length == 0 ) $active = $('#slider div:last');
    if ( $activeThumb.length == 0 ) $activeThumb = $('#thumbsdiapo div:last');

    // use this to pull the divs in the order they appear in the markup
    var $next =  $active.next().length ? $active.next() : $('#slider div:first');
    var $nextThumb =  $activeThumb.next().length ? $activeThumb.next() : $('#thumbsdiapo div:first');

    // uncomment below to pull the divs randomly
    //var $sibs  = $active.siblings();
    //var rndNum = Math.floor(Math.random() * $sibs.length );
    //var $next  = $( $sibs[ rndNum ] );

    $active.addClass('last-active');
    $activeThumb.addClass('last-active');

    $divs.animate({opacity: 0}, 500);
    
    $next
    	.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
    

    $nextThumb
    	.css({opacity: 0.0})
    	.addClass('active')
	    .animate({opacity: 1.0});
    
    $activeThumb.fadeTo('fast',0.5,function(){
		$activeThumb.removeClass('active last-active');
	});
}



function listings(){
	
	$('table.listing tr').hover(
		function(){
			if (!$(this).parent('tbody').parent('table').hasClass('noover')){
				$(this).addClass('over');
			}
		},
		function(){
			if (!$(this).parent('tbody').parent('table').hasClass('noover')){
				$(this).removeClass('over');
			}
		}
	);
}



/* TOOLTIP */


this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};



/* IMAGE PREVIEW */

this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 10;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
	$("a.preview").click(function(){return false;});
};



function montWysiwyg(id_textarea){

	$('#'+id_textarea).wysiwyg({
	    controls: {
	      
	      strikeThrough : { visible : false },
	      underline     : { visible : true },
	      
	      separator00 : { visible : true },
	      
	      justifyLeft   : { visible : true },
	      justifyCenter : { visible : true },
	      justifyRight  : { visible : true },
	      justifyFull   : { visible : true },
	      
	      separator01 : { visible : false },
	      
	      removeFormat	: {visible : true},
	      
	      indent  : { visible : false },
	      outdent : { visible : false },
	      
	      separator02 : { visible : true },
	      
	      subscript   : { visible : false },
	      superscript : { visible : false },
	      
	      separator03 : { visible : false },
	      
	      undo : { visible : false },
	      redo : { visible : false },
	      
	      separator04 : { visible : false },
	      
	      insertOrderedList    : { visible : true },
	      insertUnorderedList  : { visible : true },
	      insertHorizontalRule : { visible : false },
	      
	      insertImage	: {visible : false },

	      h1mozilla : { visible : false && $.browser.mozilla, className : 'h1', command : 'heading', arguments : ['h1'], tags : ['h1'], tooltip : "Titre 1" },
	      h2mozilla : { visible : true && $.browser.mozilla, className : 'h2', command : 'heading', arguments : ['h2'], tags : ['h2'], tooltip : "Titre 2" },
	      h3mozilla : { visible : true && $.browser.mozilla, className : 'h3', command : 'heading', arguments : ['h3'], tags : ['h3'], tooltip : "Titre 3" },
	      h4mozilla : { visible : false && $.browser.mozilla, className : 'h4', command : 'heading', arguments : ['h4'], tags : ['h4'], tooltip : "Titre 4" },
	      h5mozilla : { visible : false && $.browser.mozilla, className : 'h5', command : 'heading', arguments : ['h5'], tags : ['h5'], tooltip : "Titre 5" },
	      h6mozilla : { visible : false && $.browser.mozilla, className : 'h6', command : 'heading', arguments : ['h6'], tags : ['h6'], tooltip : "Titre 6" },
	      
	      h1 : { visible : false && !( $.browser.mozilla ), className : 'h1', command : 'formatBlock', arguments : ['<H1>'], tags : ['h1'], tooltip : "Titre 1" },
	      h2 : { visible : true && !( $.browser.mozilla ), className : 'h2', command : 'formatBlock', arguments : ['<H2>'], tags : ['h2'], tooltip : "Titre 2" },
	      h3 : { visible : true && !( $.browser.mozilla ), className : 'h3', command : 'formatBlock', arguments : ['<H3>'], tags : ['h3'], tooltip : "Titre 3" },
	      h4 : { visible : false && !( $.browser.mozilla ), className : 'h4', command : 'formatBlock', arguments : ['<H4>'], tags : ['h4'], tooltip : "Titre 4" },
	      h5 : { visible : false && !( $.browser.mozilla ), className : 'h5', command : 'formatBlock', arguments : ['<H5>'], tags : ['h5'], tooltip : "Titre 5" },
	      h6 : { visible : false && !( $.browser.mozilla ), className : 'h6', command : 'formatBlock', arguments : ['<H6>'], tags : ['h6'], tooltip : "Titre 6" },
	      
	      separator07 : { visible : false },
	      
	      cut   : { visible : false },
	      copy  : { visible : false },
	      paste : { visible : false }
	    }
	  });
}



function datePickerInit(){
	
	$.datepicker.regional['fr'] = {
			closeText: 'Fermer',
			prevText: '&#x3c;Préc',
			nextText: 'Suiv&#x3e;',
			currentText: 'Courant',
			monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
			monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun','Jul','Aoû','Sep','Oct','Nov','Déc'],
			dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
			dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
			dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
			dateFormat: 'dd/mm/yy',
			firstDay: 1,
			isRTL: false
	};
		
	$.datepicker.setDefaults($.datepicker.regional['fr']);
	$.datepicker.setDefaults({
			changeYear: true,
    		changeMonth: true,
    		yearRange: '1910:2005',
    		defaultDate: '-20y',
    		gotoCurrent: true
	});
}

function debug(){
	$('div.debugW').draggable();
	$('div.debugW a.fermerDebug').live('click', function(){$(this).parent('div').remove();} );
}

function carousel(){
	
	
	if ($("div.logoCarousel").length > 0){
	
		if($("div.logoCarousel li").length > 0){
			$("div.logoCarousel").easySlider({
	    		auto: true,
	    		continuous: true ,
	    		nextId: "slidermarquenext",
	    		prevId: "slidermarqueprev",
	    		nextText: "&nbsp;&nbsp;",
	    		prevText: "&nbsp;&nbsp;"
	    	});
		}
	}
}

	
function handleForms(){
	
	var formFields = $('input').add('textarea').add('select');
	
	formFields.focus(function() { $(this).addClass('focus'); });
	formFields.blur(function() { $(this).removeClass('focus'); });

	$('input#submit').fadeTo(0,0.75);
	$('input#submit').hover(
			function(){$(this).fadeTo(0,1);},
			function(){$(this).fadeTo(0,0.75);}
	);
	
}

function in_array(p_val,array){
	var bool = false
	$.each( array, function(i, n){
		if (typeof n!="undefined"){

		 if(n.toLowerCase() == p_val.toLowerCase()) {
	            bool = true;
	        }
		}
	});
	return bool;
}



function unset(array, value){
	var output=[];
	for (var i = 0 ; i<array.length;i++){
		if (array[i] != value)
			output[i]=array[i];
	}
	return output;
}

jQuery.fn.extend({
	   findPos : function() {
	       obj = jQuery(this).get(0);
	       var curleft = obj.offsetLeft || 0;
	       var curtop = obj.offsetTop || 0;
	       while (obj = obj.offsetParent) {
	                curleft += obj.offsetLeft
	                curtop += obj.offsetTop
	       }
	       return {x:curleft,y:curtop};
	   }
	});



function loginBox(){
	$('form#loginForm input#EMAIL').focus(function(){
		if($(this).val() == 'Adresse e-mail'){
			$(this).val('');
		}
	});
	$('form#loginForm input#EMAIL').blur(function(){
		if ($(this).val() == ''){
			$(this).val('Adresse e-mail');
		}
	});
	
	
	$('form#loginForm input#loginButton').click(function(){
		
		if(
		$('form#loginForm input#EMAIL').val() == 'Adresse e-mail'
		||
		$('form#loginForm input#EMAIL').val() == ''
		){
			$('form#loginForm input#EMAIL').focus();
			return false;
		}
	});
	
}

function searchMenu(){
	$('#inputSearch').focus(function(){$(this).attr('value','');});
	$('#inputSearch').blur( function(){
		if ($(this).attr('value') == ''){$(this).attr('value','Tapez votre recherche ici');}
	});
}

function newsletterForm(){
	$('#newsletterEmail').focus(function(){$(this).attr('value','');});
	$('#newsletterEmail').blur( function(){
		if ($(this).attr('value') == ''){$(this).attr('value','Votre email...');}
	});
}



/* AJAX */

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
    	var c = ca[i];
    	while (c.charAt(0)==' '){
        	c = c.substring(1,c.length);
    	}
    	if (c.indexOf(nameEQ) == 0){
        	return c.substring(nameEQ.length,c.length);
    	}
	}
	return null;
}




function alertie6(){

		if(jQuery.browser.msie && jQuery.browser.version == 6){
			if($.cookie("iecookie") == null){
				$('div#ie6nomore').show();
			}
			
			$('#closeie6banner').click(function(){
				var date = new Date();
				date.setTime(date.getTime() + (20 * 60 * 1000)); // 20 minutes
				$.cookie("iecookie", "ie6nomore", { expires: date });
				
			});

		}
	}



function editeurTexte(idtextarea){
	
	$('textarea#'+idtextarea).tinymce({
		// General options
		theme : "advanced",
        skin : 'default',
        language :'en',
        plugins : 'paste',
        theme_advanced_blockformats : "p,h2,h3,h4",

        entity_encoding : "raw",
		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,formatselect",
        theme_advanced_buttons2 : '',
        theme_advanced_buttons3 : '',
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar : false,
		theme_advanced_resizing : false,
		paste_remove_styles : true,
		paste_preprocess : function(pl, o) {
        	o.content = o.content.replace(/h1/g, 'h2');
		}
	});
}

function editeurTexteForum(idtextarea){
	
	$('textarea#'+idtextarea).tinymce({
		
		// General options
		theme : "advanced",
        skin : 'default',
        language :'en',
        plugins : 'paste,bbcode,emotions,autoresize',
        theme_advanced_blockformats : "p,h2,h3,h4",
        font_size_style_values : "9,11,13,15,18,24,36",

		// Theme options
        theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,|,forecolor,fontsizeselect,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,emotions,code",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",

		theme_advanced_statusbar : false,
		theme_advanced_resizing : false,
		paste_remove_styles : true,
		paste_preprocess : function(pl, o) {
        	o.content = o.content.replace(/h1/g, 'h2');
		},
		
		entity_encoding : "raw",
		add_unload_trigger : false,
		remove_linebreaks : false,
		relative_urls : false,
		convert_urls : false

	});
}



function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
            	return true;
            }
        }
    }
    return false;
}

/* Autocomplete ville  */

ajaxCache = {};
function autocompleteVille(idInput,fillCP){
	$input = $('input#'+idInput);
	$input.autocomplete({
		source : function(request, response) {
			//what are we searching for
			var query_type = $(this).attr('element').attr('id');
			//the cacheterm that we use to save it in the cache
			var cachedTerm = (request.term + '' + query_type) . toLowerCase();
			//if the data is in the cache and the data is not too long, use it
			if (ajaxCache[cachedTerm] != undefined && ajaxCache[cachedTerm].length < 13) {
				//map the data into a response that will be understood by the autocomplete widget
				response($.map(ajaxCache[cachedTerm], function(item) {
					return {
						label: item.ville + '<span>('+item.departement+')</span><span class="cp" style="display:none">'+item.cp+'</span>',
						value: item.ville
					}
				}));
			}
			//get the data from the server
			else {
				$.ajax({
					url: ws_path+"ajax/ajax.php",
					dataType: "json",
					data: {
						query_type: query_type,
						process: 'villes',
						ajaxtoken: function(){ return readCookie('ajaxtoken'); },
						q: request.term
					},
					success: function(data) {
						//cache the data for later
						ajaxCache[cachedTerm] = data;

						//map the data into a response that will be understood by the autocomplete widget
						response($.map(data, function(item) {
							return {
								label: item.ville + '<span>('+item.departement+')</span><span class="cp" style="display:none">'+item.cp+'</span>',
								value: item.ville
							}
						}));
					}
				});
			}
		},
		minLength: 3,
		select: function(event, ui) {

			if(fillCP == true){

				$label = ui.item.label;
				$label = $($label);
				$cp = $label[1].innerHTML;
				$('#CP').val($cp);
			}
			//close the drop down
			this.close;
		}
	});
}



