/* ------------------------------------------------------------------------
	General site settings
	Re-used througought the site
------------------------------------------------------------------------- */

var settings = {
	initialized : false,
	
	init : function(val) {
 		if (!this.initialized) {
			$.each(val, function(msg) {
				if (!settings[msg])
					settings[msg] = val[msg];
			});

			this.initialized = true;
		} else {
			return false;
		};
	}
};

/* ------------------------------------------------------------------------
	Content to be runned on load
------------------------------------------------------------------------- */

	$(document).ready(function(){
		fixWidth.init();
		fixPNG.init();
		mainSearch.init();
		dropdown.init();
		bottomBackground.init();
		
		$('a[rel*=external]').attr('target','_blank');
		$('.toHide').hide();
		
		$(window).bind('resize',function(){
			fixWidth.init();
		});
		
		$("#ProductKeyword").autocomplete("/" + $('body').attr('id') + "/products/autocomplete/",{
			width: 212,
			minChars: 0,
			max: 20,
			scroll: true,
			scrollHeight: 300,
			selectFirst: false,
			highlight: false,
			formatItem: function(data, i, total) {
				return "<a href='/"+settings.lang+"/products/"+data[4]+"/"+data[0]+"' class='clearfix'><img src='"+data[3]+"' width='40' height='45' /><span>"+data[1]+"</span><br />"+data[2]+"</a>";
			}
		});
		
		$("#ProductKeyword").result(function(event,data){
			$(this).val(data[1]);
			location.href = "/" + settings.lang + "/products/"+data[4]+"/" + data[0];
		});
	});

/* ------------------------------------------------------------------------
	Main site search javascript
------------------------------------------------------------------------- */

	mainSearch = {
		init : function(){
			theForm = $('#siteSearchForm');
			theLabel = $(theForm).find('label:first');
			theInput = $(theForm).find('input[type=text]');
			
			// Position the label correctly
			$(theForm).find('label:first').addClass('js');
			
			// If the field is filled onload, hide the label
			if($(theInput).attr('value') != "")
				$(theLabel).hide();
				
			
			// Bind the events to the input to hide/show the label
			$(theInput).focus(function(){
				$(this).parent().prev().hide(); // Hide the label
			});
			
			$(theInput).blur(function(){
				if($(this).attr('value') == "")
					$(this).parent().prev().show() // If it's still empty, show the label
			});
		}
	}


/* ------------------------------------------------------------------------
	Used for the custom dropdowns
------------------------------------------------------------------------- */

	dropdown = {
		init : function() {
			// Position the dropdown according to the title before it
			$('.dropdown').each(function(){
				// Define if it's a dropdown for the filter, if so, the style is a bit different
				if($(this).parents('.filter').size() > 0){
					dropdownOffest = $(this).prev().position()
					$(this).css({
						'top': dropdownOffest.top + 20,
						'left': dropdownOffest.left + 15
					});
				};
			});

			$('.dropdown li.selected').click(function(){
				dropdown.toggle($(this).parent());
			});

			$('.dropdown li a').bind('click',function(){
				dropdown.select($(this).parent());
				if($(this).attr('rel')){
					// If it a filter, we need to call a different function
					if($(this).parents('.filter').size() > 0){
						// The container
						$c = $('#content-container #content ul.categoryList');
						
						$c.parent().append('<img src="/media/images/prettyPopin/loader.gif" alt="Loading" class="loader" />');
						$c.fadeOut();
						
						dropdown.filters = "";
						$('ul.dropdown li.selected[rel]').each(function(){
							// Dont filter when it's all
							if($(this).attr('rel') != "all"){
								if(dropdown.filters == ""){
									dropdown.filters += '/filters:' + $(this).attr('rel');
								}else{
									dropdown.filters += ',' + $(this).attr('rel');
								};
							};
						});
						
						// Load the content via ajax
						$.get('/'+settings.lang+'/categories/view/makeup/subcategory:' + settings.subcategory + dropdown.filters,function(responseText){
							$c.html(responseText);
							$c.parent().find('.loader:first').remove();
							$c.fadeIn(function(){
								// Re-init sIFR
								sIFR.replace(dax_light, {
									selector: 'ul.categoryList li div.description h5',
									css: {
										'.sIFR-root': { 'text-transform': 'uppercase', 'color' : '#222222'},
										'a': { 'color':'#222222', 'text-decoration':'none' },
										'a:hover': { 'color':'#ed037c' }
									},
									selectable: false,
									fitExactly: true,
									wmode: 'transparent'
								});
							});
						});

					}else{
						// The container
						$c = $('.'+$(this).attr('rel'));
						$c.fadeOut();
						
						// Load the content via ajax
						$.get($(this).attr('href'),function(responseText){
							$c.html(responseText);
							$c.fadeIn(function(){
								// Reinit the scrollbar
								$('.clips .container ul').jScrollPane();
							});
						});
					}

					return false;
				}
			});
		},
		toggle : function(caller,callback) {
			$d = $(caller); // The dropdown
			var callback = callback || function(){}; // Custom callback
			var fullHeight = 0; // Used to know to what height open the dropdown

			$d.find('li:hidden').each(function(){ fullHeight += $(this).height(); }).css({'display':'block'}); // Calculate the full height

			fullHeight += $d.find('li.selected').height();

			if($d.height() > 19){ // It's opened
				$d.animate({'height':19},'fast',function(){ callback(); $d.find('li:not(.selected):visible').css('display','none'); $d.css({'border-bottom':'none','z-index':0}); });
			}else{
				$d.parent().find('ul.dropdown').each(function(){
					if($(this).find('li:eq(1)').is(':visible')){
						if($(this)[0] != $d[0]){
							$(this).animate({'height':19},'fast',function(){ callback(); $(this).find('li:not(.selected):visible').css('display','none'); $(this).css({'border-bottom':'none','z-index':0}); });
						}
					}
				});
				
				$d.css({'border-bottom':'1px #c9c7c7 solid','z-index':1000});
				$d.animate({'height':fullHeight},'fast',function(){ callback(); });
			}
		},
		select : function(caller) {
			$d = $(caller).parent(); // The dropdown
			$c = $(caller); // The caller

			$d.find('li.selected').text($c.text()).attr('rel', $c.find('a').attr('rel')); // Change the selected element

			dropdown.toggle($d,function(){$d.find('li:not(:visible)').show();$c.hide();}); // Close the dropdown, then hide the selected element from the list and show the hidden one(s).
		}
	}
	

/* ------------------------------------------------------------------------
	Used in the product Listing page
------------------------------------------------------------------------- */

	products = {
		options : {
			previewHeight : 47,
			animationSpeed: 300,
			timeoutValue: 250,
			animatedOpening: false,
			animatedClosing: false,
			heightWhenClosed: 0
		},
		init : function() {
			// To fix a layout issue, I need to make sure the height of the list is at least the same as the sidebar
			if($('ul.categoryList').height() < $('#sidebar').height() && !location.hash)
				$('ul.categoryList').height($('#sidebar').height());
			
			// Associate the hover to all the "description" divs
			$('div.description.hover a.fakeHover').each(function(){
				$(this).mouseover(function(){
					// Find the sifr and fake the hover
					products.sifrOver($(this));
					
					// Find the link and fake the hover
					$(this).parent().find(':not(.hide)').addClass('hover');
				}).mouseout(function(){
					// Find the sifr and fake the hover
					products.sifrOut($(this));

					// Find the link and fake the hover
					$(this).parent().find(':not(.hide)').removeClass('hover');
				}).click(function(){
					// Find the link and click it
					$(this).parent().find('p:not(.hide) a').trigger('click');
					return false;
				});
			});
			
			$('div.description:not(.hover) a.fakeHover').each(function(){
				$(this).mouseover(function(){
					if(!$(this).parent().find('p > .btn_close').parent().hasClass('hide')){
						//Find the sifr and fake the hover
						products.sifrOver($(this));
						
						// Find the link and fake the hover
						$(this).parent().find(':not(.hide)').addClass('hover');
										
						$(this).css('cursor','pointer');
					}else{
						$(this).css('cursor','default');
					}
				}).mouseout(function(){
					if(!$(this).parent().find('p > .btn_close').parent().hasClass('hide')){
						// Find the sifr and fake the hover
						products.sifrOut($(this));
							
						// Find the link and fake the hover
						$(this).parent().find(':not(.hide)').removeClass('hover');
					}
				}).click(function(){
					if(!$(this).parent().find('p > .btn_close').parent().hasClass('hide')){
						// Find the link and click it
						$(this).parent().find('p:not(.hide) a').trigger('click');
						return false;
					}
				});
			});
		},
		expand : function(caller) {
			$ct = $(caller).parents('li'); // The container

			// Associate the proper class on the clicked element
			// remove the class from all the other elements.
			$ct.parent().find('.active').removeClass('active');
			$ct.addClass('active');

			// Make sur the sIFR is not in hover state
			$('ul.categoryList > li a.productOverlay').addClass('hide');
			
			$('ul.categoryList > li object').each(function(){
				products.sifrOut(caller);
			});

			// Detect if it's a fragrance page, if so, we need to expand the parent of the container too
			stretchParent = false;
			if($ct.parent().hasClass('fragrances')){
				stretchParent = true;
			}
			
			// Display the loader icon (only if the sIFR is there)
			if($ct.find('object').size() > 0)
				$ct.addClass('loading');
			
			// Save the height in its original state
			if(!products.initialHeight) products.initialHeight = $ct.height();
			
			// First make sure the content wont stretch
			$ct.css({
				'overflow': 'hidden',
				'height': $ct.height()
			});
			
			// Load the content, then animate the opening
			$ct.find('ul.productList').load($(caller).attr('href'),function(){
				// Hide the loader
				$ct.removeClass('loading');
				
				$ct.find('> div').css({'position':'static'});
				
				if($ct.parents('ul:first').height() != 'auto' && $ct.parents('ul:first').attr('style')){
					products.options.heightWhenClosed = $ct.parents('ul:first').height();
					$ct.parents('ul:first').css('height','auto');
				}
				
				$ct.animate({'height': $(this).height()},products.options['animationSpeed'],function(){
					$('ul.categoryList > li:not(.active) a.productOverlay').removeClass('hide');
					$('ul.categoryList > li:not(.active) a.fakeHover').addClass('hide');
				});
				
				// Show the close button
				$ct.find('.btn_seeAll').parent().addClass('hide');
				$ct.find('.btn_close').parent().removeClass('hide');
				$ct.find('a.fakeHover').removeClass('hide');
				
				// Close all the other product categories
				$('ul.categoryList > li:not(.active)').css({'overflow':'hidden'}).each(function(){
					($(this).find('div.description').height() > products.options['previewHeight']) ? previewHeight = $(this).find('div.description').height() + 20 : previewHeight = products.options['previewHeight'];
					$(this).animate({'height': previewHeight},function(){
						if(stretchParent){
							// Strech the fragrance image container
							(parseFloat($('ul.categoryList').height()) > 455) ? heightToStretch = parseFloat($('ul.categoryList').height()) : heightToStretch = 455;
							
							$('#fragrance_flash').animate({'height':heightToStretch + parseFloat($('#page .overlayProduct .content').css('padding-top'))},450);
							$('#page .overlayProduct').animate({'height':heightToStretch + parseFloat($('#page .overlayProduct .content').css('padding-top'))},440);
						}
					});
				});
				$('ul.categoryList > li:not(.active) > div').css({'position':'relative'});
				$('ul.categoryList > li:not(.active) div.description p:not(.hide), ul.categoryList > li:not(.active) ul.productList').fadeOut(products.options['animationSpeed'],function(){ $(this).find('li > a.btn_seeAll').removeClass('hide') });
				$('ul.categoryList > li.active div.description p:not(.hide), ul.categoryList > li.active ul.productList').fadeIn(products.options['animationSpeed']);
			});

			$.ajaxHistory.update($(caller).attr('rel'));
		},
		colapse : function(caller){
			$ct = $(caller).parents('ul:first'); // The container
			$ct.find('.btn_seeAll').each(function(){ $(this).parent().removeClass('hide'); });
			$ct.find('.btn_close').each(function(){ $(this).parent().addClass('hide'); });
			
			if($ct.css('height') == 'auto' && products.options.heightWhenClosed){
				$ct.height(products.options.heightWhenClosed);
			}
			
			$ct.find('> li').each(function(){
				$('ul.categoryList > li a.productOverlay').addClass('hide');
				$('ul.categoryList > li a.fakeHover').removeClass('hide');
				$(this).animate({'height':products.initialHeight},products.options['animationSpeed'],function(){
					products.sifrOut($(caller));
					
					$(this).find('div.description *,ul.productList').fadeIn();
					
					// Remove the extra products from the HTML
					$(this).find('ul.productList li:gt(2)').remove();
					
					if(stretchParent){
						// Strech the fragrance image container
						$('#fragrance_flash').animate({'height':455},450);
						$('#page .overlayProduct').animate({'height':455},440);
					}
				});
			});
		},
		sifrOver : function(caller) {
			$(caller).parents('li:first').css('overflow','visible');
			sifrID = $(caller).parents('div:first').find('object').attr('id');
			sIFR.replacements[sifrID].changeCSS(".sIFR-root {color:#ed037c;}");
		},
		sifrOut : function(caller) {
			$(caller).parents('li:first').css('overflow','hidden');
			sifrID = $(caller).parents('div:first').find('object').attr('id');
			sIFR.replacements[sifrID].changeCSS(".sIFR-root{color:#222222;}");
		}
	}


/* ------------------------------------------------------------------------
	Used to fix the products PNGs in IE6
------------------------------------------------------------------------- */

	fixPNG = {
		init : function() {
			if($.browser.msie && $.browser.version == 6){
				$p = $('img.toFix'); // The product
				
				$p.parent().css({
					'background' : 'none',
					'width' : $p.width(),
					'height' : $p.height(),
					'filter' : 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+$p.attr('src')+'", sizingMethod="crop")'
				});
				
				$p.hide();
			}
		}
	}


/* ------------------------------------------------------------------------
	Used to selected the shaded
------------------------------------------------------------------------- */

	shade = {
		init : function() {
			i=0;

		 	// Preload all the images
			$('ul.shadeList li a').each(function(){
				jsonAttributes = eval('(' + $(this).attr('rel') + ')');
				$.preloadImages(jsonAttributes['img_bg'],jsonAttributes['img_medium'],jsonAttributes['img_large']);
				
				// Need to be defined a object, else only the last shade will be selected.
				var caller = new Object();
				caller = $(this);
				
				$(this).history(function(){
					if(!shade.inAnimation)
						shade.select(caller);
				});
			});
			
			if(location.hash){
				$('a[href='+location.hash+']').trigger('click');
			};
		},
		select : function(caller) {
			shade.inAnimation = true;
			
			var fadeSpeed = 200;
			
			// Get the json object in the rel element
			jsonAttributes = eval('(' + $(caller).attr('rel') + ')');
			
			// Change the application
			if(jsonAttributes['img_bg'] != "false" || $('#productHeader img.applicationBG').attr('src') != jsonAttributes['img_bg'])
			shade.changeApplication(fadeSpeed,jsonAttributes['img_bg']);
			
			// Change the product (little delay)
			if(jsonAttributes['img_medium'] != "false")
			shade.changeProduct(fadeSpeed,jsonAttributes['img_medium'],jsonAttributes['img_large']);
			
			// Change the shade
			if(jsonAttributes['img_shade'] != "false")
			shade.changeShade(fadeSpeed,jsonAttributes['img_shade'],jsonAttributes['txt_shade']);
			
			if(jsonAttributes['slug'] != "")
			shade.changeRelated(jsonAttributes['slug']);
			
			shade.changeCaption(jsonAttributes['caption']);
			
			// Select the right element
			$('ul.shadeList li.selected:first').removeClass('selected');
			$(caller).parent().addClass('selected');
			
			// Re-enable the animation.
			setTimeout('shade.inAnimation = false;',fadeSpeed);
		},
		changeProduct : function(fadeSpeed,img_medium,img_large){
			// Change the product images
			$('div.productImage img').fadeOut(fadeSpeed,function(){
				$(this).attr('src',img_medium);
				$(this).fadeIn(function(){
					fixPNG.init();
				});
			});
			
			$('div.zoomedProduct img').attr('src',img_large);
		},
		changeShade : function(fadeSpeed,img_shade,txt_shade){
			// Change the selected shade
			$('.selectedShade .shade img').fadeOut(fadeSpeed,function(){
				$(this).attr('src',img_shade);
				$(this).fadeIn();
			});
			$('.selectedShade .shade p').fadeOut(fadeSpeed, function(){
				$(this).text(txt_shade);
				$(this).fadeIn();
			});
		},
		changeApplication : function(fadeSpeed,img_bg){
			// Change the application
			$('#productHeader img.applicationBG').fadeOut(fadeSpeed, function(){
				$(this).attr('src',img_bg);
				$(this).fadeIn();
			});
		},
		changeRelated : function(slug){
			// Fade out the current related products
			$('div.colLeft').height($('div.colLeft').height());
			jQuery.get('/' + settings.lang + '/products/related/' + slug,function(responseHTML){
				// Only change the related if they're different
				// I check for all the hrefs, if the are all equivalent, don't fade
				matches = 0;
				$(responseHTML).each(function(i){
					if($(this).find('a').size() > 0){
						if($('ul.productList li a[href="'+$(this).find('a').attr('href')+'"]').size() > 0)
						matches += 1;
					}
				});
				
				if($('ul.productList li ').size() != matches){
					if($('div.prettyGallery').size() > 0){
						$('div.prettyGallery').fadeOut(function(){
							$('div.prettyGallery').remove();
							$('div.colLeft').append(responseHTML);
							$('div.colLeft ul.productList').hide().fadeIn();
						});
					}else{
						$('ul.productList').fadeOut(function(){
							$('ul.productList').remove();
							$('div.colLeft').append(responseHTML);
							$('div.colLeft ul.productList').hide().fadeIn();
						});
					}
				}
			});
		},
		changeCaption : function(caption){
			if(caption == "")
				caption = "&nbsp;";

			// Fade out the current caption
			$('p.caption').fadeOut(function(){
				$(this).html(caption).fadeIn();
			});
		}
	}


/* ------------------------------------------------------------------------
	Used in the product detail page to show the zoomed product
------------------------------------------------------------------------- */

	product = {
		toggle : function() {
			$p = $('div.zoomedProduct'); // The product container
			
			if($p.is(':visible')){
				$p.fadeOut();
				$('a.btn_zoom').removeClass('btn_close');
			}else{
				$p.fadeIn();
				$('a.btn_zoom').addClass('btn_close');
			}
		},
		checkScroll : function() {
			if($('div.scroller').height() > 105){
				$('div.scroller').css({
					'height': 114,
					'width': 335,
					'overflow': 'hidden'
				}).jScrollPane({'scrollbarMargin':10}).parent().append('<div class="shadow"></div>');
			}
		},
		showTab : function(caller,which) {
			// Deselect all the selected tab
			$('ul.tabs li.selected').removeClass('selected');
			$(caller).parent().addClass('selected');
			
			// Hide all the visible tab
			if($('div.productTabs:visible').size() > 0){
				$('div.productTabs:visible').fadeOut(function(){
					// Show the proper tab
					$('#' + which).removeClass('hide').hide().fadeIn();
				});
			}else{
				$('#' + which).removeClass('hide');
			}
		}
	}
	

/* ------------------------------------------------------------------------
	To fix the bottom background if the content is longer than viewport
------------------------------------------------------------------------- */

	bottomBackground = {
		init : function() {
			if($('#bottomBackground').height() > $(window).height()){
				$('#bottomBackground').height($(window).height());
			}
		}
	}


/* ------------------------------------------------------------------------
	Used in the beauty clips
------------------------------------------------------------------------- */

	beautyClips = {
		init : function() {
			// Init the tabs
			$('div.steps ol li:gt(0)').hide();
			$('ul.steps li a').each(function(i){
				this.i = i;
				$(this).click(function(){
					beautyClips.showTab(i,false);
					return false;
				});
			});
			
			// Make sure the steps products are the same height as the video container
			$('.videoPlayerSidebar .content').height($('.videoPlayer .content').height() - 6);
		},
		select : function(caller) {
			($(caller).hasClass('thumbnail')) ? $c = $(caller) : $c = $(caller).prev();
			
			// Remove the current selected item
			$c.parents('ul:first').find('li.selected').removeClass('selected');
			$c.parent().addClass('selected');
		},
		showTab : function(which,fromFlash) {
			// Get the total number of steps
			totalSteps = $('ul.steps li').size();
			
			// Deselect all tabs
			$('ul.steps li').removeClass('selected').removeClass('lastSelected').removeClass('firstSelected');
			
			// Select the clicked tab
			// Classes changes if it's the 1st or last tab that is clicked
			if(which == (totalSteps - 1)) {
				$('ul.steps li:eq('+which+')').addClass('lastSelected');
			} else if(which == 0) {
				$('ul.steps li:eq('+which+')').addClass('firstSelected');
			} else {
				$('ul.steps li:eq('+which+')').addClass('selected');
			}
			
			// Hide all tabs
			$('div.steps li').hide();
			
			//Show the correct tab
			$('div.steps li:eq('+which+')').show();
			
			// Scroll to the related product
			var $relatedProduct = $('.videoPlayerSidebar .container ul');
			$relatedProduct[0].scrollTo('.step_'+ which);
			
			// Make sure the steps products are the same height as the video container
			$('.videoPlayerSidebar .content').height($('.videoPlayer .content').height() - 6);

			// Send the flash to the correct step
			if(!fromFlash){
				$('#flashVideoPlayer')[0].onTabClick(which);
			}
		}
	}


/* ------------------------------------------------------------------------
	Used in the fragrances page
------------------------------------------------------------------------- */

	fragrances = {
		init : function(){
			// $(this).bind('click',function(){
			// 	// Need to keep it cause of scoping
			// 	$caller = $(this);
			// 	$(this).history(function(){
			// 		shade.select($caller);
			// 	});
			// });
		},
		toggle : function(caller){
			if(!$(caller).hasClass('active')) {
				$(caller).hide();
				
				$('.overlayProductClosed .content').css({'position':'relative','top':0})
				
				// Slide the products
				$('.overlayProduct').addClass('overlayProductAnimated').animate({
					'width': 785
				},'normal',function(){
					$(this).removeClass('overlayProductClosed').removeClass('overlayProductAnimated');
					// Change the button state
					$(caller).addClass('active').show();
				});
			
				// Hide the closed background
				$('.overlayProduct .closedContent').fadeOut();
			
				// Show the content
				$('.overlayProduct .content').fadeIn();
			}else{
				$(caller).hide();
				
				// Slide the products
				$('.overlayProduct').addClass('overlayProductAnimated').animate({
					'width': 190
				},'normal',function(){
					$(this).addClass('overlayProductClosed').removeClass('overlayProductAnimated');
					
					// Reset the product to their initial states
					products.colapse($('ul.categoryList li.active a.btn_close').trigger('click'));
				});
			
				// Hide the closed background
				$('.overlayProduct .closedContent').fadeIn();
			
				// Show the content
				$('.overlayProduct .content').fadeOut(function(){ $(caller).show(); });
			
				// Change the button state
				$(caller).removeClass('active');
			}
		}
	}


/* ------------------------------------------------------------------------
	Tabs toggle in the about lise watier page
------------------------------------------------------------------------- */

	about = {
		init : function(){
			$('ul.tabs a').bind('click',function(){
					$caller = $(this);

					about.showTab(this);
					
					// CLICKED CALLED FROM BACK/LINK
					$(this).history(function(){
						about.showTab($caller);
					});
			});
			
			$.ajaxHistory.initialize();
			
			// Select the first tab
			if(!location.hash)
			$('ul.tabs li:first a').trigger('click');
		},
		showTab: function(caller){
			// Need to keep it cause of scoping
			$caller = $(caller);

			// REGULAR CLICK
			// Remove all the selected menu items
			$('ul.tabs li.selected').removeClass('selected');

			// Select the correct menu item
			$caller.parent().addClass('selected');

			// Hide all the tabs
			$('div.tabs').hide();

			// Show the selected tabs
			$($caller.attr('href') + "_content").show();
		}
	}


/* ------------------------------------------------------------------------
	Used to fix the site for user ine 1024
------------------------------------------------------------------------- */

	fixWidth = {
		init : function() {
			if($(window).width() < $('#page').width()){
				toOffset = $(window).width() - $('#page').width() + 5;
				if(toOffset < -170) toOffset = -170;
				if($.browser.msie && $.browser.version == 6) toOffset += 25;
				$('#page').css('margin-left', toOffset);
				$('body').addClass('noScroll');
			}else{
				$('#page').css('margin-left','auto');
				$('body').removeClass('noScroll');
			}
		}
	}
	
	
/* ------------------------------------------------------------------------
	Used for filtering Regions by country id
------------------------------------------------------------------------- */

	regions = {
		filterByCountry : function(div,country_id) {
			var rand_no = Math.random();
			$.ajax({
				type: "GET",
				url:"/"+ settings.lang + "/regions/ajax_filter/" + country_id + "/?rand=" + rand_no,
				dataType: "json",
				timeout: 20000,
				success: function(j) {
					// If there's no region, load with the parent
					if(j == ""){
						$("#"+ div).parent().addClass('hide');
						stores.update_search('#searchForAStore');
					}else{					
						var options = '<option value="">Select region</option>';
						$.each(j, function(key,value) {
							   options += '<option value="' + key + '">' + value + '</option>';
						});
						$("#"+ div).html(options).bind('change',function(){
							stores.update_search('#searchForAStore');
						}).parent().removeClass('hide');
					}
				}
			})
	
		}
	}


/* ------------------------------------------------------------------------
	Used for filtering Regions by Country Code in the VIP Club
------------------------------------------------------------------------- */

	countries = {
		selectRegion : function(caller) {
			country_code = $(caller).attr('value');

			$.ajax({
				type: "GET",
				url:"/"+ settings.lang + "/vip_clubs/states/" + country_code,
				dataType: "html",
				timeout: 20000,
				success: function(reponseText) {
					if(reponseText != ""){
						$('div.states select:first').after(reponseText).remove();
						$('div.states').removeClass('hide');
					}else{
						$('div.states').addClass('hide');
					}
				}
			})

		}
	}


/* ------------------------------------------------------------------------
	Generates and overlay for store locator
------------------------------------------------------------------------- */	
	stores = {	
		update_search :function(form){
			var params = {}; 
			inputs = $(form).find(" input[@type='hidden'], input[@type='submit'], option[@selected]");

			inputs.each(function() { 
				params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; 
			});

			var rand_no = Math.random();
		
			// Display a loader
			$('#storeResults').html('<img class="loader" alt="Loading" src="/media/images/all/placeholders/ajax-loader.gif" />').slideDown();
			
			$.ajax({
				type:"POST",
				url:"/" + settings.lang + "/stores/search_ajax/?rand=" + rand_no,
				data : params,
	 			timeout: 20000,
				success: function(responseText){
					$('#storeResults').slideUp(function(){
						$('#storeResults').html(responseText);
						$('#storeResults').slideDown();	
						$('#storeResults').removeClass('hide');
					});		
					}
				});
		}
		
	}


/* ------------------------------------------------------------------------
	Code for the vip club
------------------------------------------------------------------------- */

	vipclub = {
		open : function(caller) {
				// Hide the message
				$('div.message').hide();
			
				$('div.slider:not('+$(caller).attr('href')+')').slideUp();
				$($(caller).attr('href')).slideToggle(function(){
					$(caller).parents('ul:first').find('li.selected').removeClass('selected');
					$(caller).parent().addClass('selected');
				});
		}
	}


/* ------------------------------------------------------------------------
	Code for the flash homepage
------------------------------------------------------------------------- */

var flashGallery = {
	flashGallery : null,
	isReady: false,
	currentFlash: 1,
	totalFlash: 0,
	previous : function(){
		flashGallery.flashGallery.previousSlide();
	},
	next : function(){
        flashGallery.flashGallery.nextSlide();
        //alert(flashGallery.currentFlash);
	},
	pause : function(){
		flashGallery.flashGallery.pauseSlide();
		$('.btnPlay').removeClass('hide');
		$('.btnPause').addClass('hide');
	},
	start : function(){
		flashGallery.flashGallery.startSlide();
		$('.btnPlay').addClass('hide');
		$('.btnPause').removeClass('hide');
	},
	updateCounter : function() {
		if(settings.lang == 'fr'){
			$('.controls .counter').html(flashGallery.currentFlash + ' DE ' + flashGallery.totalFlash);
		}else{
			$('.controls .counter').html(flashGallery.currentFlash + ' OF ' + flashGallery.totalFlash);
		}
	},
	setTotal : function(n){
		flashGallery.totalFlash = n - 1;
		flashGallery.updateCounter();
		if(flashGallery.totalFlash > 1){
			$('.controls').fadeIn('slow');
		}
	},
	setCurrent : function(n){
		flashGallery.currentFlash = n + 1;
		if(flashGallery.totalFlash > 0){
			flashGallery.updateCounter();
		}
	},
	sendToFriend : function(from){
		$('a[rel='+from+']').trigger('click');
	},
	sendToFriendClose : function(){
		flashGallery.flashGallery.shareItClose();
	}
};


/* ------------------------------------------------------------------------
	Code used to preload images
------------------------------------------------------------------------- */

jQuery.preloadImages = function() {
	for(var i = 0; i<arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
}