// JavaScript Document

$(function() {

	//DD_roundies.addRule('.item', '5px',false);
	
	/*
	*
	* Preload images
	*
	*/
	
	var isCampsDeJour = (window.location.href.indexOf('/camps-de-jour') != -1) ? true:false;
	
	$(window).load(function() {
		for(var i = 0; i < window.products.length; i++) {
			var img1 = new Image();
			if(window.products[i].photo) {
				img1.src = '/photos/resizer/238/181/'+window.products[i].photo;
			}
			/*var img2 = new Image();
			img2.src = '/photos/resizer/478/405/'+window.products[i].photo;
			var img3 = new Image();
			img3.src = '/photos/resizer/118/82/'+window.products[i].photo;*/
		}
	});
	
	
	$('.select ul li').live('click',function() {
		var $select = $(this).parents('.select');
		var val = $(this).attr('rel');
		var label = $(this).text();
		if(!val.length) {
			if(!$select.find('ul li:eq(0)').attr('rel').length) {
				$select.find('ul li:eq(0)').remove();
				$select.find('.list').removeClass('active');
			}
		} else {
			if($select.find('ul li:eq(0)').attr('rel').length) {
				$select.find('ul').prepend('<li rel="">Peu importe</li>');
				$select.find('.list').addClass('active');
			}
		}
		$select.find('select').val(val);
		$select.find('.label').text(label);
		$select.find('ul').css('display','none');
		window.setTimeout(function() {
			$select.find('ul').css('display','');
		},10);
		updateProducts();
	});
	
	$('.select').each(function() {
		
		var $select = $(this);
		
		if($select.find('select').val().length) {
			var val = $select.find('select').val();
			if($select.find('ul li:eq(0)').attr('rel').length) {
				$select.find('ul').prepend('<li rel="">Peu importe</li>');
				$select.find('.list').addClass('active');
			}
			var label = $select.find('li[rel='+val+']').text();
			$select.find('.label').text(label);
		}
		
		var hideTimeout = null;
		$select.hover(function() {
			if(hideTimeout) {
				window.clearTimeout(hideTimeout);
				hideTimeout = null;
			}
			$select.addClass('select-hover');
		},function() {
			hideTimeout = window.setTimeout(function() {
				$select.removeClass('select-hover');
			},300);
		});
		
	});
	
	function resize(callback) {
		
		if(!callback) { var callback = function(){}; }
		
		function changeImage(width,height) {
			/*var image = $(this).css('backgroundImage').replace(/\/resizer\/([0-9]+)\/([0-9]+)\//,'/resizer/'+width+'/'+height+'/');
			$(this).css('backgroundImage',image);*/
			var image = $(this).find('img').attr('src').replace(/\/resizer\/w([0-9]+)\/h([0-9]+)\//,'/resizer/w'+width+'/h'+height+'/');
			
			if($(this).find('img').length) {
				$(this).find('img').attr('src',image);
			}
		}
		
		function changeSize(width,height,imgheight) {
			
			if($('.products .results .items .item:not(.hidden):not(.tohide):not(.toshow)').length) {
				var originalWidth = $('.products .results .items .item:not(.hidden):not(.tohide):not(.toshow)').eq(0).width();
			} else {
				var originalWidth = $('.products .results .items .item:not(.hidden):not(.tohide)').eq(0).width();
			}
			if(width != originalWidth) {
				if(width > originalWidth) {
					$('.products .results .items .item').each(function() {
						changeImage.call(this,width,imgheight);
					});
				}
				$('.products .results .items .item:not(.hidden):not(.tohide):not(.toshow)').addClass('toresize');
				if(width == 478) {
					$('.products .results .items .item:not(.hidden):not(.tohide):not(.toshow)').addClass('big').removeClass('medium');
				} else if(width == 238) {
					$('.products .results .items .item:not(.hidden):not(.tohide):not(.toshow)').addClass('medium').removeClass('big');
				} else {
					$('.products .results .items .item:not(.hidden):not(.tohide):not(.toshow)').removeClass('medium').removeClass('big');
				}
				
				if($('.products .results .items .item.toresize').length) {
					var callbackCalled = false;
					$('.products .results .items .item.toresize:not(.TS99) img').stop(false,true).animate({
							'width':width+'px',
							'height':imgheight+'px'
						},300,'swing');
					if(isCampsDeJour && $('.products .results .items .TS99.toresize').length) {
						if(imgheight == 118) { tsheight = 82; }
						else if(imgheight == 238) { tsheight = 181; }
						else if(imgheight == 478) { tsheight = 405; }
						$('.products .results .items .TS99.toresize img').stop(false,true).animate({
								'width':width+'px',
								'height':tsheight+'px'
							},300,'swing');
					}
					$('.products .results .items .item.toresize, .products .results .items .item.toresize a').stop(false,true).animate({
							'width':width+'px',
							'height':height+'px'
						},300,'swing',function() {
							if(!$(this).is('a')) {
								$(this).removeClass('toresize');
								if(!callbackCalled && !$('.products .results .items .item.toresize').length) {
									if(width < originalWidth) {
										$('.products .results .items .item').each(function() {
											if($(this).is('.TS99')) {
												changeImage.call(this,width,tsheight);
											} else {
												changeImage.call(this,width,imgheight);
											}
										});
									}
									callback(width,height,imgheight);
								}
							}
					});
				} else {
					callback(width,height,imgheight);
				}
			} else {
				callback(width,height,imgheight);
			}
		}
		
		var itemsCount = $('.products .results .items .item:not(.hidden):not(.tohide)').length;
		if(itemsCount < 17 && itemsCount > 4) {
			
			if(isCampsDeJour) {
				changeSize(238,238,238);
			} else {
				changeSize(238,218,181);
			}
			
		}else if(itemsCount < 5) {
			
			if(isCampsDeJour) {
				changeSize(478,478,478);
			} else {
				changeSize(478,439,405);
			}
			
		} else if($('.products .results .items .item:not(.hidden):not(.tohide):not(.toshow)').eq(0).width() != 118 || $('.products .results .items .item:not(.hidden):not(.tohide)').eq(0).width() != 118) {
			if(isCampsDeJour) {
				changeSize(118,118,118);
			} else {
				changeSize(118,118,82);
			}
			
		} else {
			var width = $('.products .results .items .item:not(.hidden):not(.tohide)').eq(0).width();
			callback(width,width);
		}
	}
	
	var searchParams = [];
	var nextParams = [];
	
	function resetSearch() {
		searchParams = [];
		nextParams = [];
		$('.searchPanel a.option').removeClass('down').removeClass('disabled');
		$('.searchPanel a.option input:checked').removeAttr('checked');
		$('.searchPanel .camps a.option').removeClass('down').removeClass('disabled');
		$('.searchPanel .camps a.option input').attr('checked','checked');
		
		$('.products .results .item.hidden, .products .results .item.tohide').addClass('toshow').removeClass('hidden').removeClass('tohide');
		
		resize();
	}
	
	function updateProducts(nohash) {
		var sex = $('.searchPanel .sex input:checked').val();
		var camps = $('.searchPanel .camps input:checked').valArray();
		var durations = $('.searchPanel .duration input:checked').valArray();
		var age = parseInt($('.searchPanel .birthdate select').val());
		var date = $('.searchPanel .date select').length ? $('.searchPanel .date select').val():$('.searchPanel .date input:checked').valArray();
		var chid = $('.searchPanel input[name=chid]').val();
		var codes = $('.searchPanel input[name=codes]').val();
		codes = !codes.length ? null:codes.split(',');
		
		searchParams = [];
		nextParams = [];
		if(sex == 'G') { searchParams.push('gars'); }
		else if(sex == 'F') { searchParams.push('fille'); }
		if(age > 0) { searchParams.push(age+'ans'); }
		if(camps.length) { searchParams.push(camps.join('/')); }
		if(durations.length) { searchParams.push(durations.join('sem/')+'sem'); nextParams.push(durations.join('sem/')+'sem'); }
		if(date.length) {
			if(typeof(date) == 'string') {
				searchParams.push(date);
				nextParams.push(date);
			} else {
				searchParams.push(date.join('/'));
				nextParams.push(date.join('/'));
			}
		}
		if(chid.length) { searchParams.push('ch'+chid); nextParams.push('ch'+chid); }
		
		if(!nohash) {
			window.location.hash = '/'+searchParams.join('/');
		}
		
		$('.products .results .noresult').hide();
		
		//var selectedProducts = [];
		var selectedProducts = {'length' : 0};
		for(var i = 0; i < window.products.length; i++) {
			var product = window.products[i];
			
			var durationFound = false;
			var start = parseInt(product.durationstart);
			var end = parseInt(product.durationend);
			end = (end == 0) ? start:end;
			start = (start == 0) ? end:start;
			var maxDurations = durations.length;
			for(var j = 0; j < maxDurations; j++) {
				switch(durations[j]) {
					case '1':
						if(start >= 0 && (end <= 7 || start <= 7)) { durationFound = true; }
					break;
					case '2':
						if((start > 7 && (end <= 14 || start <= 14)) || (end <= 14 && end > 7)) { durationFound = true; }
					break;
					case '3':
						if(start > 14 || end > 14) { durationFound = true; }
					break;	
				}
			}
			
			if(typeof(date) == 'string') {
				var dateFound = (window.products_dates[date] && $.inArray(product.pid,window.products_dates[date]['pid']) != -1) ? true:false;
			} else {
				var dateFound = false;
				
				$.each(date,function() {
					if(!dateFound && window.products_dates[this] && $.inArray(product.pid,window.products_dates[this]['pid']) != -1) {
						dateFound = true;
					}
				});
			}
			
			if(
				(!age || (age >= parseInt(product.agestart) && age <= parseInt(product.ageend))) && 
				(!sex || !sex.length || product.sex == 'M' || product.sex == sex) && 
				(!camps || !camps.length || jQuery.inArray(product.cpermalink,camps) >= 0) && 
				(!codes || !codes.length || jQuery.inArray(product.code,codes) >= 0) && 
				(!durations || !durations.length || durationFound) && 
				(!date || !date.length || dateFound)
			) {
				//selectedProducts.push(product);
				selectedProducts[parseInt(product.pid)] = product;
				selectedProducts['length']++;
			}
			
		}
		
			
		if(!selectedProducts['length'] && codes.length) {
			$('.searchPanel input[name=codes]').val('');
			updateProducts();
			return;
		}
		
		if(nohash && !selectedProducts.length) {
			if(!isNaN(age) && age > 0) {
				window.location.href = '/camps-de-vacances/'+age+'ans/'+sex+'/';
			} else {
				window.location.href = '/camps-de-vacances/'+sex+'/';
			}
			return;
			//resetSearch();
			//return
		}
		
		if(!selectedProducts.length) {
			$('.products .results .noresult').show();
		}
		
		$('.products .results .items .item').each(function() {
			if(!selectedProducts[parseInt($(this).attr('rel'))]) {
				$(this).removeClass('toshow').addClass('tohide');
			} else if($(this).is('.hidden') || $(this).is('.tohide')) {
				$(this).removeClass('hidden').removeClass('tohide').addClass('toshow');
			}
		});
		
		
		
		if($('.products .results .items .item.tohide').length) {
			if(nohash) {
				$('.products .results .items .item.tohide').hide().css('display','none').addClass('hidden').removeClass('tohide');
				resize();
			} else {
				$('.products .results .items .item.tohide').stop(false,true).animate({'opacity':0,'width':'1px'},300,'swing',function() {
					$(this).css('display','none').addClass('hidden').removeClass('tohide');
					if(!$('.products .results .items .item.tohide').length) {
						resize(function() {
							
							if($.browser.msie) {
								$('.products .results .items .item:not(.hidden):not(.tohide) img').css('display','');
							}	
						});
						return;
					}
				});
			}
		}	
		
		if($('.products .results .items .item.toshow').length) {
			resize(function(width,height,imgheight) {
				var $items = $('.products .results .items .item.toshow').stop(false,true);
				$items.find('img').stop(false,true).css({
					'width' : width+'px',
					'height' : imgheight+'px'
				});
				$items.find('a').stop(false,true).css({
					'width' : width+'px',
					'height' : height+'px'
				});
				$items.css('width','1px').show().animate({
						'opacity':1,
						'width':width+'px',
						'height':height+'px'
					},300,'linear',function() {
						if(width == 478) {
							$(this).addClass('big').removeClass('medium');
						} else if(width == 238) {
							$(this).addClass('medium').removeClass('big');
						} else {
							$(this).removeClass('medium').removeClass('big');
						}
						$(this).css('filter','').removeClass('hidden').removeClass('toshow')
				});
				if($.browser.msie) {
					$('.products .results .items .item:not(.hidden):not(.tohide) img').css('display','');
				}
			});
		}
		
		updateFilters();
		
		//if(window.IP == '69.70.95.126' || window.location.host.indexOf('.local') != -1) { updateFilters(); }
	}
	
	function updateFilters() {
		var $items = $('.products .results .items .item:not(.hidden):not(.tohide)');
		var pids = [];
		$items.each(function() {
			pids.push($(this).attr('rel'));
		});
		
		var durations = [];
		var sex = [];
		var camps = [];
		var dates = [];
		var ages = [];
		for(var i = 0; i < window.products.length; i++) {
			var product = window.products[i];
			if(jQuery.inArray(product.pid,pids) != -1) {
				
				//Duration
				var start = parseInt(product.durationstart);
				var end = (parseInt(product.durationend) == 0) ? start:parseInt(product.durationend);
				end = (end == 0) ? start:end;
				start = (start == 0) ? end:start;
				if(start >= 0 && (end <= 7 || start <= 7)) {
					if(jQuery.inArray(1,durations) == -1) { durations.push(1); }
				}
				if((start > 7 && (end <= 14 || start <= 14)) || (end <= 14 && end > 7)) {
					if(jQuery.inArray(2,durations) == -1) { durations.push(2); }
				}
				if(start > 14 || end > 14) {
					if(jQuery.inArray(3,durations) == -1) { durations.push(3); }
				}
				
				//Ages
				var start = parseInt(product.agestart);
				var end = (parseInt(product.ageend) == 0) ? start:parseInt(product.ageend);
				for(var j = start; j < end+1; j++) {
					if(jQuery.inArray(j,ages) == -1) { ages.push(j); }
				}
				
				//Dates
				jQuery.each(window.products_dates,function(k,v) {
					if(jQuery.inArray(product.pid,v.pid) != -1) {
						if(jQuery.inArray(k,dates) == -1) {
							dates.push(k);
						}
					}
				});
				
				//Sex
				if(jQuery.inArray(product.sex,sex) == -1) { sex.push(product.sex); }
				
				//Camps
				var camp = product.cpermalink;
				if(jQuery.inArray(camp,camps) == -1) { camps.push(camp); }
				
			}
		}
		
		$('.searchPanel .duration a.option').each(function() {
			var duration = parseInt($(this).find('input').val());
			if(jQuery.inArray(duration,durations) == -1) {
				disableFilter($(this));
			} else {
				enableFilter($(this));
			}
		});
		
		
		$('.searchPanel .birthdate .select li').each(function() {
			var age = parseInt($(this).attr('rel'));
			if($(this).attr('rel') && $(this).attr('rel').length) {
				if(jQuery.inArray(age,ages) == -1) {
					$(this).hide();
				} else {
					$(this).show();
				}
			}
		});
		
		$('.searchPanel .camps a.option').each(function() {
			var camp = $(this).find('input').val();
			if(jQuery.inArray(camp,camps) == -1) {
				disableFilter($(this));
			} else {
				enableFilter($(this));
			}
		});
		
		$('.searchPanel .date .select li').each(function() {
			var date = $(this).attr('rel');
			if($(this).attr('rel') && $(this).attr('rel').length) {
				if(jQuery.inArray(date,dates) == -1) {
					$(this).hide();
				} else {
					$(this).show();
				}
			}
		});
		
		$('.sex a.option').each(function() {
			var s = $(this).find('input').val();
			if(jQuery.inArray(s,sex) == -1) {
				disableFilter($(this));
			} else {
				enableFilter($(this));
			}
		});
		
	}
	
	
	function disableFilter($el) {
		$el.addClass('disabled');
		$el.find('input, select').attr('disabled','disabled');
	}
	
	function enableFilter($el) {
		$el.removeClass('disabled');
		$el.find('input, select').removeAttr('disabled');
	}
	
	
	$('.products .results .items .item a').live('click',function(e) {
		//e.preventDefault();
		var href = $(this).attr('href');
		if(nextParams.length) {
			$(this).attr('href',href+'?params='+escape(nextParams.join('/')));
		}
		
	});
	
	$('.searchPanel a.option').click(function(e) {
		e.preventDefault();
		
		$(this).removeClass('disabled');
		$(this).toggleClass('down');
		if(!$(this).is('.down')) {
			$(this).find('input.checkbox').removeAttr('checked');	
		} else {
			$(this).find('input.checkbox').attr('checked','checked');
		}
		
		//S'il s'agit d'un radio button on active le toggle mode
		if($(this).find('input.checkbox').attr('type') == 'radio') {
			var name = $(this).find('input').attr('name');
			$('.searchPanel input[name='+name+']').each(function() {
				if(!$(this).is(':checked')) {
					$(this).parents('a.option').removeClass('down');	
				} else {
					$(this).parents('a.option').addClass('down');
				}
			});
		}
		
		//Si aucun camp de coché, ont les coche tous
		if($(this).parents('.camps').length && !$(this).parents('.camps').find('input:checked').length) {
			$(this).parents('.camps').find('a.option').addClass('down').removeClass('disabled');
			$(this).parents('.camps').find('a.option input.checkbox').attr('checked','checked');
		}
		
		if($(this).parents('.duration').length && $(this).is('.down')) {
			$(this).parents('.duration').find('a.option:not(.down)').addClass('disabled');
		}
		
		if($(this).parents('.duration').length && !$(this).is('.down')) {
			$(this).parents('.duration').find('a.option.disabled').removeClass('disabled');
		}
		
		updateProducts();
		
	}).each(function() {
		if($(this).find('input').length && $(this).find('input').is(':checked')) {
			$(this).addClass('down').removeClass('disabled');	
		} else {
			$(this).removeClass('down').removeClass('disabled');
		}
		
	});
	
	updateProducts(true);
	
	/*
	*
	* 
	*
	*/
	
	var mapTimeout = null;
	var mapOver = false;
	$('.searchPanel a.map').hover(function() {
		if($('div.map').is(':visible') && mapTimeout) { window.clearTimeout(mapTimeout); }
		mapTimeout = window.setTimeout(function() {
			$('div.map').slideDown();
			mapTimeout = null;
		},500);
	},function() {
		if(!$('div.map').is(':visible') && mapTimeout) { window.clearTimeout(mapTimeout); }
		mapTimeout = window.setTimeout(function() {
			$('div.map').slideUp();
			mapTimeout = null;
		},500);
	});
	
	$('div.map').hover(function() {
		if($('div.map').is(':visible') && mapTimeout) { window.clearTimeout(mapTimeout); }
	},function() {
		mapTimeout = window.setTimeout(function() {
			$('div.map').slideUp();
			mapTimeout = null;
		},300);
	});
	
	
	/*
	*
	* IE Fix
	*
	*/
	
	
	//DD_roundies.addRule('.products .searchPanel .camps .button', '5px',false);
	//DD_roundies.addRule('.products .searchPanel .camps .shadow', '5px',false);
	//DD_roundies.addRule('.products .searchPanel .select .list', '5px',false);
	//DD_roundies.addRule('.products .searchPanel .select .shadow', '5px',false);
	
	/*if(jQuery.browser.msie) {
	
		$('.products .searchPanel .camps .disabled .button').css('border','none');
		
		$('.products .searchPanel .camps a').click(function() {
			var $a = $(this);
			window.setTimeout(function() {
				var isDown = $a.is('.down');
				if(isDown) {
					$a.css('color','#fff !important');
				} else {
					$a.css('color','#fff !important');
				}
				$a.find('shape').each(function() {
					if($(this).get(0).fillcolor != '#303' && $(this).get(0).fillcolor != '#330033') {
						if(!isDown) {
							if(!$a.is('.disabled')) {
								$(this).get(0).fillcolor = '#999999';
							} else {
								$(this).get(0).fillcolor = '';
							}
						} else  {
							if($a.find('.button-3saumons').length) {
								$(this).get(0).fillcolor = '#33CCFF';
							} else if($a.find('.button-minogami').length) {
								$(this).get(0).fillcolor = '#009900';
							} else if($a.find('.button-artistes').length) {
								$(this).get(0).fillcolor = '#FF3300';
							} else if($a.find('.button-accord').length) {
								$(this).get(0).fillcolor = '#33cc99';
							}
						}
					} else if($a.is('.disabled')) {
						$(this).get(0).fillcolor = 'transparent';
					} else if(!$a.is('.disabled') && $(this).get(0).fillcolor == 'transparent') {
						$(this).get(0).fillcolor = '#330033';
					}
				});
			},50);
		});
		
		$('.products .searchPanel .select').hover(function() {
			var $select = $(this);
			$(this).find('shape').each(function() {
				if($(this).get(0).fillcolor != '#303') {
					$(this).get(0).fillcolor = '#F60';
				}
			});
		},function() {
			var $select = $(this);
			if(!$(this).find('.active').length) {
				$(this).find('shape').each(function() {
					if($(this).get(0).fillcolor != '#303') {
						$(this).get(0).fillcolor = '#999';
					}
				});
			}
		});
	}*/
	
	
});
