var Korres = new function() {

	$(document).ready(function() {
		attachHomepageFeatureEvents();
		attachLeftNavigationEvents();
		attachTopNavigationEvents();
		attachCategoryNavigationEvents();
		attachListFilterEvents();
		attachColorPickerEvents();
		attachMiniBagEvents();
		attachBagEvents();
		attachSampleEvents();
		attachAddToBagEvents();
		attachCheckoutBillingEvents();
		attachCheckoutPaymentEvents();
		attachIngredientLayerEvents();
		attachCollectionVignetteEvents();
		attachLookVignetteEvents();
		attachTabbedListEvents();
		attachSpecialOffersEvents();
		attachPromotionTermsEvents();
		attachFriendsAndFamilyEvents();
		
		setInputDefaults('.search input.field', 'SEARCH THIS SITE');
		setInputDefaults('.mailing-block input.field', 'ENTER YOUR EMAIL');
	});

	/* Public functions */

	this.AddToBag = function(product_id, color_id) {
		var date = new Date();
		
		var analytics_enabled = (typeof pageTracker != 'undefined');
		
		if( analytics_enabled ){
			pageTracker._trackPageview('/add-to-bag/click');
		}
		
		$.get('/ajax/add-to-bag', {
				product_id: product_id,
				color_id: color_id || 0,
				time: date.getTime() //To make sure the request isn't cached
			},
			function(data) {
				if (data.response.status != 'success') {
					if (data.response.msg == 'sold-out') {
						overlayMessage('Sorry, that product is sold out.');
						if( analytics_enabled ){ pageTracker._trackPageview('/add-to-bag/sold-out'); }
					}
					else if (data.response.msg == 'invalid-color') {
						overlayMessage('Sorry, that shade is no longer available.');
						if( analytics_enabled ){ pageTracker._trackPageview('/add-to-bag/unavailable'); }
					}
					else if (data.response.msg == 'invalid-product') {
						overlayMessage('Sorry, that product is no longer available.');
						if( analytics_enabled ){ pageTracker._trackPageview('/add-to-bag/unavailable'); }
					}
					
					return false;
				}
				
				var mini_bag = $(data.c.mini_bag);
				$('#mini-bag').replaceWith(mini_bag);
				attachMiniBagEvents();
				
				$('#mini-bag-list').remove();
				var mini_bag_list = $(data.c.mini_bag_list);
				$('#mini-bag').append(mini_bag_list);
				miniBagListFadeInOut(true);
				
				if( analytics_enabled ){
					pageTracker._trackPageview('/add-to-bag/success');
				}
			},
			'json'
		);
	};

	this.RemoveFromBag = function(item_id) {
		var date = new Date();
		
		$.get('/ajax/remove-from-bag', {
				item_id: item_id,
				time: date.getTime() //To make sure the request isn't cached
			},
			function(data) {
				if (data.response.status != 'success') {
					return false;
				}
				
				$('#item_' + item_id).animate({opacity: 0}, 500, function() {
					setTimeout(function() {
						var list = $(data.c.list);
						$('#bag-list').replaceWith(list);
						attachBagEvents();
						
					}, 250 );
				});
				
				var mini_bag = $(data.c.mini_bag);
				$('#mini-bag').replaceWith(mini_bag);
				attachMiniBagEvents();
				
				var totals = $(data.c.totals);
				$('.merchandise .totals').replaceWith(totals);
				
				var promo = $(data.c.promo);
				$('#promo').replaceWith(promo);
			},
			'json'
		);
	};

	this.EssentialsChange = function(category) {
		$('#background').replaceWith($('<div style="background-image: url(/images/essentials-bg-' + category + '.jpg);" id="background">&nbsp;</div>'));
	};
	
	this.getCookie = function(c_name) {
		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) {
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) {
					c_end=document.cookie.length;
				}
				return unescape(document.cookie.substring(c_start,c_end));
			}
		}
		return "";
	};
	
	this.setCookie = function(c_name, value, expiredays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)
			+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
			+ ";path=/";
	};
	
	this.countClick = function() {
		// We're no longer counting clicks. I've left the hooks in for possible future reuse
		return;
	};
	
	this.fragrances_ca_warning = function(show) {
		var ship_to = $('div.ship-to');
		
		if( show ) {
			var ship_to_str = $("input:radio:checked", ship_to).val();
			$(".shipping-fragrance-ca." + ship_to_str).show();
		}
		else {
			$(".shipping-fragrance-ca").hide();
		}
	};
	
	this.check_fragrances_ca = function() {
		var ship_to = $('div.ship-to');
		
		Korres.fragrances_ca_warning(false);
		if( $('#contains-fragrances').val() ) {
			if( $("input:radio:checked", ship_to).val() == 'billing' ) {
				if( $('#billing_state').val() == 'CA' ) {
					Korres.fragrances_ca_warning(true);
				}
			}
			else {
				if( $('#shipping_state').val() == 'CA' ) {
					Korres.fragrances_ca_warning(true);
				}
			}
		}
	};
	
	this.ItemQuantityChanged = function(select_el) {
		var tr = select_el.parent().parent();
		var item_id = select_el.attr('name').split('_')[1];
		var quantity = select_el.val();

		$.post('/ajax/update-item-quantity', {
				item_id: item_id,
				quantity: quantity
			},
			function(data) {
				if (data.response.status != 'success') {
					if (data.response.msg == 'insufficient-stock') {
						var remaining = data.response.data.remaining;
						overlayMessage('Sorry, only '+remaining+(remaining == 1 ? ' is' : ' are')+' available.');
						select_el.val(remaining);
						Korres.ItemQuantityChanged(select_el);
					}
					
					return false;
				}
				
				var mini_bag = $(data.c.mini_bag);
				$('#mini-bag').replaceWith(mini_bag);
				attachMiniBagEvents();

				var list = $(data.c.list);
				$('#bag-list').replaceWith(list);
				attachBagEvents();

				var totals = $(data.c.totals);
				$('.merchandise .totals').replaceWith(totals);
			},
			'json'
		);
	};
	

	/* Private functions */

	var attachGiftWrappingEvents = function() {
		var textarea = $('#gift-wrapping-message');
		textarea.keyup(function() {
			var remaining = 250 - textarea.val().length;
			if (remaining <= 0) {
				textarea.val(textarea.val().substr(0, 250));
				remaining = 0;
			}
			$('em', '#gift-wrapping-message-container').text(remaining);
		});
		$('input', '#gift-wrapping-message-container').bind("keyup", function() {
			var remaining = 50 - $(this).val().length;
			var ems = $(this).prevAll("em");
			var em = ems[0];
			$(em).text(remaining);
		});
		
		// Add
		$('#gift-wrapping-add').click(function() {
			$.post('/ajax/add-gift-wrapping', {
				},
				function(data) {
					if (data.response.status != 'success') {
						return false;
					}

					$('#gift-wrapping-container').animate({opacity: 0}, 500, function() {
						setTimeout(function() {
							var list = $(data.c.list);
							$('#gift-wrapping-container', list).css('opacity', 0);
							$('#gift-wrapping-message-container', list).css('opacity', 0);

							$('#bag-list').replaceWith(list);
							attachBagEvents();

							$('#gift-wrapping-container', list).animate({opacity: 1}, 500);
							$('#gift-wrapping-message-container', list).animate({opacity: 1}, 500);

							var totals = $(data.c.totals);
							$('.merchandise .totals').replaceWith(totals);
						}, 250 );
					});
				},
				'json'
			);
			return false;
		});

		// Remove
		$('#gift-wrapping-remove').click(function() {
			$.post('/ajax/remove-gift-wrapping', {
				},
				function(data) {
					if (data.response.status != 'success') {
						return false;
					}
					$('#gift-wrapping-container').animate({opacity: 0}, 500, function() {
						setTimeout(function() {
							var list = $(data.c.list);
							$('#gift-wrapping-container', list).css('opacity', 0);

							$('#bag-list').replaceWith(list);
							attachBagEvents();

							$('#gift-wrapping-container', list).animate({opacity: 1}, 500);

							var totals = $(data.c.totals);
							$('.merchandise .totals').replaceWith(totals);
						}, 250 );
					});
					$('#gift-wrapping-message-container').animate({opacity: 0}, 500);
				},
				'json'
			);
			return false;
		});

		// Update
		$('#gift-wrapping-update').click(function() {
			var greeting = $('#gift-wrapping-greeting').val();
			var message = $('#gift-wrapping-message').val();
			var closing = $('#gift-wrapping-closing').val();
			$.post('/ajax/update-gift-wrapping', {
					greeting: greeting,
					message: message,
					closing: closing
				},
				function(data) {
					if (data.response.status != 'success') {
						return false;
					}

					$('#gift-wrapping-message-container').animate({opacity: 0}, 500, function() {
						var list = $(data.c.list);
						$('#bag-list').replaceWith(list);
						attachBagEvents();
					});
				},
				'json'
			);
			return false;
		});
	};

	var attachPromotionTermsEvents = function(parent) {
		$('a.promo-terms', parent).click(function() {
			$.post('/ajax/promotion-terms', {
					id_list: $(this).attr('href')
				},
				function(data) {
					if (data.response.status != 'success') {
						return;
					}

					overlayMessage(data.c.terms);
				},
				'json'
			);

			return false;
		});
	};

	var attachSpecialOffersEvents = function() {
		$('li.promos a').click(function() {
			$.post('/ajax/special-offers', {
				},
				function(data) {
					var overlay = $('#overlay');
					shade(overlay, true);
					overlay.html(data.c.promos);

					$('a.close', overlay).click(function() {
						shade(overlay, false);
					});
				},
				'json'
			);

			return false;
		});
	};

	var attachTabbedListEvents = function() {
		var tab_looks = $('#tab-looks');
		if (!tab_looks.size()) {
			return;
		}

		var tab_collections = $('#tab-collections');
		var collections = $('#container-collections');
		var looks = $('#container-looks');

		tab_collections.click(function() {
			collections.show();
			looks.hide();
			
			Korres.countClick();
			
			return false;
		});

		tab_looks.click(function() {
			looks.show();
			collections.hide();
			Korres.countClick();
			
			return false;
		});
	};

	var attachCollectionVignetteEvents = function() {
		$('#collections .collection').each(function() {
			var vignette = $(this);
			var a = $('a.view', vignette);
			vignette.click(function() {
				window.location.href = a.attr('href');
			});
		});
	};

	var attachLookVignetteEvents = function() {
		$('#getthelook-overview .look').each(function() {
			var vignette = $(this);
			var a = $('a.view-the-look', vignette);
			vignette.click(function() {
				window.location.href = a.attr('href');
			});
		});
	};

	var overlayMessage = function(message) {
		scrollTo(0, 0);
		var overlay = $('#overlay');
		shade(overlay, true);

		var html_message = $('<div id="overlay-message">' + message + '<a class="close">x</a></div>');
		overlay.html(html_message);
		$('a.close', html_message).click(function() {
			shade(overlay, false);
		});
	};
	
	var overlayRequest = function(url) {
		$.post(url, {
			},
			function(data) {
				var overlay = $('#overlay');
				shade(overlay, true);
				overlay.html(data.c.overlay);

				$('a.close', overlay).click(function() {
					shade(overlay, false);
				});
			},
			'json'
		);    
	};

	var setInputDefaults = function(selector, text) {
		$(selector).each(function() {
			var el = $(this);

			el.focus(function() {
				var val = el.val();
				if (val == text) {
					el.val('');
				}
			}).
			blur(function() {
				var val = el.val();
				if (val == '') {
					el.val(text);
				}
			});

			var val = el.val();
			if (val == '' || val == text) {
				el.val(text);
			}
		});
	};

	var shade = function(overlay, show) {
		var shade_el = $('#shade');
		shade_el.css('height', $(document).height());
		if (show) {
			shade_el.show();
			overlay.show();
		}
		else if (show == false) {
			shade_el.hide();
			overlay.hide();
		}
		else {
			shade_el.toggle();
			overlay.toggle();
		}

		shade_el.click(function() {
			shade(overlay, false);
		});
	};

	var attachIngredientLayerEvents = function() {
		var overlay = $('#overlay');
		$('a.more').click(function() {
			shade(overlay, true);

			var ingredient_id = $(this).attr('href');

			// Ingredient data already loaded
			var ingredient_overlay = $('#ingredient-overlay', overlay);
			if (ingredient_overlay.size() && ingredient_overlay.hasClass('ingredient-' + ingredient_id)) {
				return false;
			}

			$.post('/ajax/ingredient', {
					ingredient_id: ingredient_id
				},
				function(data) {
					if (data.response.status != 'success') {
						shade(overlay, false);
						return false;
					}

					overlay.html(data.c.ingredient);

					$('a.close', overlay).click(function() {
						shade(overlay, false);
					});
				},
				'json'
			);

			return false;
		});
	};

	var miniBagListFadeInOut = function(remove) {
		var mini_bag_list = $('#mini-bag-list');

		var min_scroll_distance = 115;
		var scroll_distance = $(window).scrollTop();

		if (scroll_distance > min_scroll_distance) {
			mini_bag_list.css('top', scroll_distance - 100);
		}

		mini_bag_list.fadeIn(1000);

		var fadeout = function() {
			mini_bag_list.fadeOut(1000, function() {
				mini_bag_list.css('top', '');
				if (remove) {
					mini_bag_list.remove();
				}
			});
		};

		var timeout = setTimeout(fadeout, 4000);
		mini_bag_list.hover(
			function() {
				clearTimeout(timeout);
			},
			function() {
				timeout = setTimeout(fadeout, 2000);
			}
		);
	};

	var attachMiniBagEvents = function() {
		var showList = function() {
			var mini_bag_list = $('#mini-bag-list');
			if (mini_bag_list.size() == 0) {
				$.post('/ajax/mini-bag-list',
					null,
					function(data) {
						var mini_bag_list = $(data.c.mini_bag_list);
						$('#mini-bag').append(mini_bag_list);
						showList();
					},
					'json'
				);
				return;
			}

			miniBagListFadeInOut(false);
		};

		$('#mini-bag div.items span.button').click(function() {
			showList();
		});
	};

	var attachBagEvents = function(parent) {
		attachGiftWrappingEvents();

		$('td.qty select', parent).change(function() {
			Korres.ItemQuantityChanged($(this));
		});

		$('a.remove').click(function() {
			Korres.RemoveFromBag($(this).attr('href'));
			
			Korres.countClick();
			
			return false;
		});

		var apply_coupon = function() {
			var code = $('#promo-code').val();
			if (!code) {
				return false;
			}

			$.post('/ajax/apply-promo-code', {
					code: code
				},
				function(data) {
					if (data.response.status == 'error') {
						overlayMessage('Sorry, the code you entered is not valid or has expired.');
						$('#promo-code').val('');
					}
					else {

						var promotion = $(data.c.promotion).css('opacity', 0);
						$('#promo').animate({opacity: 0}, 200, 'linear', function() {
							var totals = $(data.c.totals);
							$('.merchandise .totals').replaceWith(totals);
							
							var list = $(data.c.list);
							list.css('opacity', 0);
							$('#bag-list').animate({opacity: 0}, 200, 'linear', function() {
								$('#bag-list').replaceWith(list);
								$('#bag-list').animate({opacity: 1}, 200, 'linear');
								attachBagEvents();
								
								$('#promo').replaceWith(promotion);
								$('#promo').animate({opacity: 1}, 250, 'linear');
								attachPromotionTermsEvents($('#promo'));
							});
						});
					}
				},
				'json'
			);

			return false;
		};
		
		$('#promo .apply-form a').unbind('click').click(apply_coupon);

		$('#promo-code').unbind('keypress').keypress(function(e) {
			if (e.which == 13){
				apply_coupon();
			}
		});
	};

	var attachAddToBagEvents = function() {
		$('a.add').click(function() {
			Korres.countClick();
			
			if ($(this).hasClass('sold-out')) {
				return false;
			}

			var tuple = $(this).attr('href').split(',');
			Korres.AddToBag(tuple[0], tuple[1]);
			return false;
		});
	};

	var attachCheckoutPaymentEvents = function() {
		var hint = $('.payment-info a.hint');
		if (!hint.size()) {
			return;
		}

		hint.click(function() {
			overlayMessage('This is the 3 or 4 digit code found on the back of your credit card or on the front of an American Express card. It helps protect your card from unauthorized use.');
			return false;
		});
	};

	var attachCheckoutBillingEvents = function() {
		var contains_fragrances = $('#contains-fragrances');
		if (!contains_fragrances.size()) {
			return;
		}
		
		$(document).ready(function() {
			Korres.check_fragrances_ca();
		});
		
		
		var hide = function() {
			$('div.billing-form').css('background', '');
			$('div.toping-right').css('visibility', 'hidden');
			$('div.right-part').hide();
			$('div.left-part .btnp').show();
		};
		
		var show = function() {
			$('div.billing-form').css('background', 'transparent');
			$('div.toping-right').css('visibility', '');
			$('div.right-part').show();
			$('div.left-part .btnp').hide();
		};
		
		var ship_to = $('div.ship-to');
		$('input', ship_to).click(function() {
			if ($(this).val() == 'shipping') {
				show();
			}
			else {
				hide();
			}
			Korres.check_fragrances_ca();
		});
		
		$('#billing_state').change( function() {
			Korres.check_fragrances_ca();
		});
		
		$('#shipping_state').change( function() {
			Korres.check_fragrances_ca();
		});
	};

	var attachSampleEvents = function() {
		var allow_more = $('#allow_more').val();
		
		var add = function(a) {
			if (!allow_more)  {
				overlayMessage('Sorry, you have reached your sample limit.<br />Please remove a sample before choosing another.');
				
				return false;
			}
			
			a = $(a);
			var product_id = a.attr('href').split(',')[0];
			$.post('/ajax/add-sample', {
					product_id: product_id
				},
				function(data) {
					if (data.response.status != 'success') {
						return;
					}
					a.toggleClass('active');
					a.attr('href', product_id+','+data.response.item);
					allow_more = data.response.allow_more;
					a.unbind('click');
					a.click(function() { return remove(a); });
				},
				'json'
			);
			return false;
		};
		
		var remove = function(a) {
			a = $(a);
			var product_id = a.attr('href').split(',')[0];
			var item_id = a.attr('href').split(',')[1];
			$.post('/ajax/remove-sample', {
					item_id: item_id
				},
				function(data) {
					if (data.response.status != 'success') {
						return;
					}
					
					allow_more = data.response.allow_more;
					
					a.attr('href', product_id)
						.toggleClass('active')
						.unbind('click')
						.click(function() { return add(a); });
				},
				'json'
			);
			return false;
		};


		$('a.add-sample').click(function() {
			Korres.countClick();
			
			return add(this);
			return false;
		});

		$('a.remove-sample').click(function() {
			Korres.countClick();
			
			return remove(this);
		});
	};

	var attachColorPickerEvents = function() {
		var colors = $('div.color div.gallery a');
		var selected = $('div.color div.current-color');
		if (!colors.size()) {
			return;
		}

		colors.click(function() {
			colors.removeClass('active');
			
			var color = $(this);
			selected.css('background-color', $('span', color).css('background-color'));
			color.addClass('active');
			$('span', selected).text(color.attr('title'));
			
			var tuple = $('a.add', '#detailed').attr('href').split(',');
			$('a.add', '#detailed').attr('href', tuple[0] + ',' + color.attr('href'));
			
			Korres.countClick();
			
			return false;
		});
	};

	var attachListFilterEvents = function() {
		var bar = $('#list-filter-bar');
		var filter = $('#list-filter');
		if (!bar.size()) {
			return;
		}

		var filters = [];

		var updateBreaks = function() {
			var position = 1;
			$('div.multi-products div.product:visible').each(function() {
				var product = $(this);
				if (position % 4 == 0) {
					product.addClass('last-product');
				}
				else {
					product.removeClass('last-product');
				}

				position++;
			});
		};

		/// Reset filters
		$('a', filter).click(function() {
			filters = [];
			$('input', filter).attr('checked', false);

			$('div.multi-products').animate({opacity: 0}, 400, 'linear', function() {
				$('div.multi-products div.product').show();
				updateBreaks();
				$('div.multi-products').animate({opacity: 1}, 400, 'linear');
			});
			
			Korres.countClick();

			return false;
		});

		// Selecting a filter
		$('input', filter).click(function() {
			var radio = $(this);
			var index = radio.attr('name').split('_')[1];

			filters[index] = radio.val();

			$('div.multi-products').animate({opacity: 0}, 400, 'linear', function() {
				$('div.multi-products div.product').each(function() {
					var product = $(this);
					var subsections = $('input', product).val();

					var show = true;
					$.each(filters, function() {
						if (!show || !this || this == window) {
							return;
						}

						if (!subsections || subsections.indexOf('|' + Number(this) + '|') == -1) {
							product.hide();
							show = false;
						}
					});

					if (show) {
						product.show();
					}
				});
				updateBreaks();
				$('div.multi-products').animate({opacity: 1}, 400, 'linear');
			});
		});

		// Show filters
		$('a', bar).click(function() {
			bar.toggleClass('open');
			filter.toggle(400);

			if (bar.hasClass('open')) {
				$('img', bar).attr('src', '/images/list-filter-x.png');
			}
			else {
				$('img', bar).attr('src', '/images/list-filter-arrow.png');
			}
			
			Korres.countClick();

			return false;
		});
	};

	var attachHomepageFeatureEvents = function() {
		var parent = $('#introbox');
		if (!parent.size()) {
			return;
		}

		var switch_feature = function(a) {
			var id = a.attr('id').split('_')[1];
			$('div.nav a', parent).removeClass('active');
			$('div.info', parent).hide();

			a.addClass('active');
			$('#introbox').css('background-image', $('#hf_' + id + ' span').css('background-image'));  
			$('#hf_' + id).show();        
		};
		
		var rotate_start = $($('div.info', parent).get(0));
		var rotate_current = rotate_start;
		var rotate_timer;
		var rotate_feature = function() {
			var next = rotate_current.next().next(); 
			if (!next.hasClass('info')) {
				next = rotate_start;
			}         
			
			var id = next.attr('id').split('_')[1];
			rotate_timer = setTimeout(
				function() {
					switch_feature($('#hfl_' + id));
					rotate_current = next;
					if (next != rotate_start) {
						rotate_feature();
					}
				}, 
				2000
			);
		};        
		
		$('div.nav a', parent).click(function() {
			switch_feature($(this));
			clearTimeout(rotate_timer);
			
			Korres.countClick();
			
			return false;
		});      
		
		rotate_feature();
	};

	var attachLeftNavigationEvents = function() {
		$('.browser .dropable .classification').click(function() {
			$(this).parent().toggleClass('closed');
		});
	};
	
	var attachTopNavigationEvents = function() {
		$('#topbar div.nav li').hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
	};

	var attachCategoryNavigationEvents = function() {
		$('#catalognav li').hover(
			function() {
				$(this).find('a:eq(0)').addClass('hover');
				$(this).find('.dropdown').show();
			},
			function() {
				$(this).find('a:eq(0)').removeClass('hover');
				$(this).find('.dropdown').hide();
			}
		);
	};

	var attachFriendsAndFamilyEvents = function() {
		$('#fnf-form').validate();
		
		$('#fnf-form .error-row input').change(function() {
			//TODO?
			//$(this).parent
		});
	};

	return this;

}();
