jQuery(document).ready(function() {
	
	$.reject({  
        closeCookie: true,
        imagePath: _root + '/web/images/browsers/'
    });  
	
	Cufon.replace('#footer .subfooter li h4', {
		fontFamily: 'Helen',
		hover: true
	});
	
	Cufon.replace('.top-form h2', {
		fontFamily: 'Helen ExtBd',
		hover: true
	});
	
	Cufon.replace('#main-banner .wrapper span, #main-banner .wrapper var, #main-banner .wrapper strong, #category-header strong, h2.title, h3.subtitle, .products del, .products em, #product .info .old-price, #product .info .price, #cart ol.products li span strong.price, #total em, #shipping-info .wrapper .info, .circle-info .wrapper .circle .info, .three-columns .wrapper .info, #footer .subfooter .freeshipping var', {
		fontFamily: 'Helen',
		separate: 'none',
		hover: true
	});	

	Cufon.replace('#category-header .wrapper h2', {
		fontFamily: 'Code Pro Light',
		separate: 'none',
		hover: true		
	});
	
	$("select:not(.custom)").selectBox({
		'menuTransition': 'slide',
		'menuSpeed' : 'fast'
	});
	
	$('#navigation ul li:gt(1)').each(function(idx, elem){
		$(elem).css('background-image', 'url(' + _root + 'web/images/categories/' + $(elem).attr('id').replace('category-', '') + '.png)');
	});
	
	$('#header .user .register').click(function () {
		$('#top-message').slideUp('slow');
		if ($('#register').is(':hidden')) {
			$('#login, #forgotten-password').slideUp('slow', function () {
				$('#register').slideDown('slow');
			});
		} else {
			$('#register').slideUp('slow');
		}
	});
	
	$('#header .user .login').click(function () {
		$('#top-message').slideUp('slow');
		if ($('#login').is(':hidden')) {
			$('#register, #forgotten-password').slideUp('slow', function () {
				$('#login').slideDown('slow');
			});
		} else {
			$('#login').slideUp('slow');
		}
	});
	
	$('#login .forgotten-password').click(function () {
		$('#top-message').slideUp('slow');
		$('#login').slideUp('slow', function () {
			$('#forgotten-password').slideDown('slow');
		});
	});
	
	$('.top-form em').click(function () {
		$('#login, #register, #forgotten-password, #top-message').slideUp('slow');
	});
	
	$('#register .button').click(function () {
		$('#register ol').addClass('loading');
		$('#top-message').slideUp('slow');
		$.post(_root + "users/xhr?method=ajax_register", $("#register form").serialize(), function(answer) {
			if (answer.error == 0) {
				location.href = _root + 'users/account';
			} else {
				$('#top-message .wrapper').html(answer.message);
				$('#top-message').slideDown('slow');
				$('#register ol').removeClass('loading');
			}
		}, 'json');
	});	
	
	$('#login .button').click(function () {
		$('#top-message').slideUp('slow');
		$('#login ol').addClass('loading');
		$.post(_root + "users/xhr?method=ajax_login", $("#login form").serialize(), function(answer) {
			if (answer.error == 0) {
				location.reload();
			} else {
				$('#top-message .wrapper').html(answer.message);
				$('#top-message').slideDown('slow');
				$('#login ol').removeClass('loading');	
			}
		}, 'json');
	});
	
	$('#forgotten-password .button').click(function () {
		$('#top-message').slideUp('slow');
		$('#forgotten-password ol').addClass('loading');
		$.post(_root + "users/xhr?method=ajax_sendpassword", $("#forgotten-password form").serialize(), function(answer) {
			if (answer.error == 0) {
				location.reload();
			} else {
				$('#top-message .wrapper').html(answer.message);
				$('#top-message').slideDown('slow');
				$('#forgotten-password ol').removeClass('loading');	
			}
		}, 'json');
	});
	
	$('.need-login').click(function () {
		$.scrollTo('#header', 500, {
			onAfter: function() {
				if ($('#login').is(':hidden')) {
					$('#header .user .login').click();
				}
			}
		});
	});	
	
	$('#products-list ol').jcarousel({
		scroll: 1,
		auto: 0,
		initCallback: carouselMainCallback
	});
	
	$('.filter .size ol').jcarousel({
		scroll: 1,
		auto: 0,
		animation: 'slow',
		start: parseInt($('.filter .size p.selected').index('.filter .size p') + 1),
		initCallback: carouselSizesCallback
	});	

	if ($('#main-banner img').length > 1) {
		$('#main-banner .container').cycle({
			fx: 'fade',
			pause: true,
			speed: 500,
			sync: 1,
    		timeout: 7000,
    		pager: '#main-banner .pager-control',
    		before: function(curr, next, options, forward) {
    			$('#products-list ol').data('jcarousel').scroll($(next).index('#main-banner a') + 1);
				parts = $('img', $(next)).attr('alt').split('::');
				$('#main-banner .wrapper span').html(parts[0] + ' налични продукта');
				$('#main-banner .wrapper strong').html(parts[1] + 'лв.');
				Cufon.refresh();
    		}
		});
	}	
	
	$('.filter #order').change(function () {
		window.location = $(this).val().toString();
	});
	
	$('#product .filter p a.active').click(function () {
		$('#product .filter p a').removeClass('selected');
		$(this).addClass('selected');
		qnt = parseInt($(this).attr('rel'));
		options = params = new Array();
		for (i = 1; i <= qnt; i++) {
			options[i] = '<option value="' + i + '">' + i + '</option>';
			params[i] = i;
		}
		$('#product #quantity').attr('title', $(this).attr('rev')).html(options.join('')).selectBox('options', params);
	});	

	// product images display handling
	$('#product .gallery ul li a:not(.hidden)').click(function() {
		$('#product .gallery ul li a:not(.hidden)').removeClass('selected');
		$(this).addClass('selected');
		image = $(this).children("img:first");
		$('#product .gallery .preview.zoom img').attr('src', image.attr('src').toString().replace('_86x115_', '_375x500_'));
		$('#product .gallery .preview.zoom').attr('href', image.attr('src').toString().replace('_86x115_', '_525x700_'));
	});
	
	$('#product .gallery .enlarge').click(function() {
		$('#product .gallery .preview.zoom').click();
		return false;
	});
	
	$('#product .gallery .preview.zoom').click(function() {
		var href = $(this).attr('href').toString();
		$('#product .gallery ul li a.hidden').fancybox({'cyclic' : 'true'});
		$('#product .gallery ul li a.hidden').each(function(i, e) {
			if ($(this).attr('href') == href) {
				$(this).click();
			}
		});
		return false;
	});
	
	$('#product .gallery .prev').click(function() {
		idx = $('#product .gallery ul li a.selected').parents('li:first').index();
		max = $('#product .gallery ul li').length - 1;
		idx = (idx == 0) ? max : idx - 1;
		$('#product .gallery ul li:eq(' + idx + ') a:not(.hidden)').click();
	});
	
	$('#product .gallery .next').click(function() {
		idx = $('#product .gallery ul li a.selected').parents('li:first').index();
		max = $('#product .gallery ul li').length - 1;
		idx = (idx == max) ? 0 : idx + 1;
		$('#product .gallery ul li:eq(' + idx + ') a:not(.hidden)').click();
	});
	
	// init fancybox
	$('#product .filter .size .all').fancybox();	
	
	// faq
	$('#faq .left dl a').click(function () {
		window.location.hash = 'faq-' + $(this).attr('rel').replace('question-', '');
		$.scrollTo('#' + $(this).attr('rel'), 500);
	});
	
	if ($('#faq .left dl a').length) {
		hash = window.location.hash.toString();
		if (hash != "") {
			parts = hash.split('-');
			$.scrollTo('#question-' + parts[1], 500);
		}
		
		var offset = $('#faq dl').offset();
		$(window).scroll(function() {
			
			if ($(window).scrollTop() > offset.top) {
				$('#faq .left dl').css({'position': 'fixed', 'marginTop': '20px'});
			} else {
				$('#faq .left dl').css({'position': 'absolute', 'marginTop': '0px'});
			}
		});		
	}	
	
	$('#contacts #subject').change(function () {
		if ($(this).val() * 1) {
			$('#contacts .toggle').hide();
			$('#contacts #category-' + $(this).val() + ', #contacts a[rel=question-' + $(this).val() + ']').show('slow');
		} else {
			$('#contacts .toggle').show();
		}
	});
	
	// show flash messages
	$('.flash-message').slideDown('slow');
	
	$('a.button.submit, #footer .newsletter .submit').click(function () {
		$(this).parents('form:first').submit();
	});
	
	// submit order
	$('a.blue-button.confirm').click(function() {
		$('.flash-message, .message').slideUp('slow');

		if ($('#correct').get(0).checked == false) {
			$('#warn-message').slideUp('slow', function() {
				$('#warn-message strong').html(_translations['FLASH_MESSAGES']['confirm_address_correct']);
				$('#warn-message').slideDown('slow');
			});
			return false;
		}
		
		if ($('#terms').get(0).checked == false) {
			$('#warn-message').slideUp('slow', function() {
				$('#warn-message strong').html(_translations['FLASH_MESSAGES']['agree_to_terms_policy']);
				$('#warn-message').slideDown('slow');
			});		
			return false;
		};
		
		error = false;
		$('.not_empty').each(function() {
			if ($(this).attr('name').indexOf('billing_') >= 0 || ($(this).attr('name').indexOf('shipping_') >= 0 && !$('#use_billing_for_shipping').attr('checked'))) {
				if ($(this).val().toString().replace(/^\s+|\s+$/g, '') == '') {
					error = true;
				}
			}
		});
		
		if (error) {
			$('#flash-message').slideUp('slow', function() {
				$.scrollTo('#header', 500, {
					onAfter: function() {
						$('#flash-message strong').html(_translations['FLASH_MESSAGES']['required_fields_empty']);
						$('#flash-message').slideDown('slow');
					}
				});
			});
			return false;
		}
		$(this).parents('form:first').submit();	
	});	
	
	$('#use_billing_for_shipping').click(function () {
		if ($(this).is(':checked')) {
			$('#billing_details select, #billing_details input').each(function () {
				elem = $('[name="' + $(this).attr('name').toString().replace('billing_', 'shipping_') + '"]');
				elem.val($(this).val());
				if (elem.get(0).tagName.toLowerCase() == 'select') {
					$(elem).selectBox('value', $(this).val());
				}
			});
		} else {
			$('#billing_details select, #billing_details input').each(function () {
				elem = $('[name="' + $(this).attr('name').toString().replace('billing_', 'shipping_') + '"]');
				elem.val('');
				if (elem.get(0).tagName.toLowerCase() == 'select') {
					$(elem).selectBox('value', '');
				}
			});
		}
	});	
	
	// add to cart
	$('.add-to-cart').click(function () {
		size = $('#quantity').attr('title');	
		quantity = $('#quantity').val() * 1;		
		$('#flash-message').slideUp('slow', function () {
			$(this).removeClass('orange green');
			if (size == "") {
				$('#flash-message strong').html(_translations['FLASH_MESSAGES']['select_size']);
				$('#flash-message em').html(_translations['FLASH_MESSAGES']['select_size_info']);
				$('#flash-message').addClass('orange').slideDown('slow');
				return false;
			}				
			
			if (quantity && size != "") {
				$.ajax({
					url: _root + 'cart/xhr',
					data: 'method=add_to_cart&id=' + $('#product-id').val() + '&quantity=' + quantity + '&size=' + size,
					success: function(response){
						if (response.indexOf('success') != -1) {
							message = response.split('::');
							// update cart summary total quantity 
							$('#shopping-cart .count').html(parseInt(parseInt($('#shopping-cart .count').html()) + quantity));
							// update cart summary label
							if (parseInt($('#shopping-cart .count').html()) == 1) {
								$('#shopping-cart .label').html(_translations['SHOPPINGCART']['item']);
							} else {
								$('#shopping-cart .label').html(_translations['SHOPPINGCART']['items']);
							}
							
							// free shipping 
							if (message[3] == 0) {
								$('#flash-message em').html(_translations['FLASH_MESSAGES']['freeshipping_achieved'].replace('%1', message[4]));
							} else {
								$('#flash-message em').html(_translations['FLASH_MESSAGES']['freeshipping_away'].replace('%1', message[3]).replace('%2', message[4]));
							}
							$('#flash-message strong').html(_translations['FLASH_MESSAGES']['add_to_cart']);
							$('#flash-message').addClass('green').slideDown('slow');
						} else {
							message = response.split('::');
							// show message
							$('#flash-message em').html(message[1]);
							$('#flash-message').addClass('orange').slideDown('slow');
						}
					}
				});				
			}			
		});
	});	
	
	$('#cart .quantity .plus, #cart .quantity .minus').click(function () {
		container = $(this).parents('var:first')
		obj = $('dfn', container);
		limit = parseInt(obj.attr('title'));
		val = parseInt(obj.text());
		if ($(this).hasClass("plus")) {
			if (val + 1 <= limit) {
				obj.text(val + 1);
			} else {
				return false;
			}
		} else {
			if (val - 1 >= 1) {
				obj.text(val - 1);
			} else {
				return false;
			}
		}
		quantity = obj.text();
		info = container.attr('id').split('_');
		id = info[1];
		size = info[2];
		$('#flash-message, .flash-message').slideUp('slow', function () {
			$.ajax({
				url: _root + 'cart/xhr',
				data: 'method=update_cart&id=' + id + '&quantity=' + quantity + '&size=' + size,
				success: function(response){
					if (response.indexOf('success') != -1) {
						message = response.split('::');
						$('#shopping-cart .count').text(parseInt(message[1]));
						// update cart summary label
						if (parseInt(message[1]) == 1) {
							$('#shopping-cart .label').text(_translations['SHOPPINGCART']['item']);
						} else {
							$('#shopping-cart .label').text(_translations['SHOPPINGCART']['items']);
						}
						
						// manage shipping prices
						if (parseInt(message[3]) == 0) {
							$('.shipping_free_price').show();
							$('.shipping_price').hide();
							$('#price-shipping').text(0);
							$('#total code').text(_translations['FLASH_MESSAGES']['freeshipping_achieved'].replace('%1', message[5]));
						} else {
							$('.shipping_free_price').hide();
							$('.shipping_price').show();
							$('#price-shipping').text(message[3]);
							$('#total code').text(_translations['FLASH_MESSAGES']['freeshipping_away'].replace('%1', message[4]).replace('%2', message[5]));
						}					
						// update subtotal price
						$('#price-subtotal').text(message[2]);
						// update total price
						$('#price-total').text(parseFloat(parseFloat(message[2]) + parseFloat(message[3])).toFixed(2));
						$('#flash-message strong').text(_translations['FLASH_MESSAGES']['cart_updated'])
						$('#flash-message').slideDown('slow');
					}					
				}
			});				
		});
	});		
	
	// remove product from cart
	$('#cart .remove').click(function () {
		info = $(this).parents('li:first').attr('id').split('_');
		id = info[1];
		size = info[2];
		$('#flash-message, .flash-message').slideUp('slow', function () {
			$.ajax({
				url: _root + 'cart/xhr',
				data: 'method=remove_from_cart&id=' + id + '&size=' + size,
				success: function(response){
					if (response.indexOf('success') != -1) {
						message = response.split('::');
						// remove the item from the cart
						$('#product_' + id + '_' + size).slideUp('slow').remove();
						// if no items left in cart
						if (parseInt(message[1]) == 0) {
							// show cart summary
							$('#shopping-cart .count').text(0);
							$('#shopping-cart .label').text(_translations['SHOPPINGCART']['items']);
							$('#total, #cart .right form, #cart .left form').hide('slow');
							$('#flash-message strong').text(_translations['FLASH_MESSAGES']['empty_cart']);
							$('#flash-message').addClass('orange').slideDown('slow');
						} else {
							// update cart summary count
							$('#shopping-cart .count').text(parseInt(message[1]));
							// update cart summary label
							if (parseInt(message[1]) == 1) {
								$('#shopping-cart .label').text(_translations['SHOPPINGCART']['item']);
							} else {
								$('#shopping-cart .label').text(_translations['SHOPPINGCART']['items']);
							}
							// update subtotal price
							$('#price-subtotal').text(message[2]);
							
							// manage shipping prices
							if (parseInt(message[3]) == 0) {
								$('.shipping_free_price').show();
								$('.shipping_price').hide();
								$('#price-shipping').text(0);
								$('#total code').text(_translations['FLASH_MESSAGES']['freeshipping_achieved'].replace('%1', message[5]));
							} else {
								$('.shipping_free_price').hide();
								$('.shipping_price').show();
								$('#price-shipping').text(message[3]);
								$('#total code').text(_translations['FLASH_MESSAGES']['freeshipping_away'].replace('%1', message[4]).replace('%2', message[5]));
							}			
							// update subtotal price
							$('#price-subtotal').text(message[2]);									
							// update total price
							$('#price-total').text(parseFloat(parseFloat(message[2]) + parseFloat(message[3])).toFixed(2));
							$('#flash-message strong').text(_translations['FLASH_MESSAGES']['cart_updated'])
							$('#flash-message').slideDown('slow');
						}
					}					
				}
			});				
		});
	});	
	
	// update shipping price
	$('#shipping_type').selectBox({'menuTransition': 'slide', 'menuSpeed' : 'fast'}).change(function () {
		$('#flash-message, .flash-message').slideUp('slow', function () {
			$.ajax({
				url: _root + 'cart/xhr',
				data: 'method=update_shipping_price&shipping_type=' + $('#shipping_type').val(),
				success: function(response){
					if (response.indexOf('success') != -1) {
						message = response.split('::');
						// manage shipping prices
						if (parseInt(message[1]) == 0) {
							$('.shipping_free_price').show();
							$('.shipping_price').hide();
						} else {
							$('#price-shipping').text(message[1]);
							$('.shipping_free_price').hide();
							$('.shipping_price').show();
						}		
						// update total price
						$('#price-total').text(parseFloat(parseFloat($('#price-subtotal').text()) + parseFloat(message[1])).toFixed(2));							
						$('#flash-message strong').text(_translations['FLASH_MESSAGES']['cart_updated']);
						$('#flash-message').slideDown('slow');			
					}
				}
			});		
		});
	});	
	
	// wishlist
	$('.add-to-wishlist').click(function () {
		$.ajax({
			url: _root + 'users/xhr',
			data: 'method=add_to_wishlist&id=' + $('#product-id').val(),
			success: function(response){
				if (response.indexOf('success') != -1) {
					$('#flash-message').slideUp('slow', function () {
						$(this).removeClass('orange');
						message = response.split('::');
						$('.add-to-wishlist').hide();
						$('.remove-from-wishlist').show();
						$('#flash-message strong').html(message[1]);		
						$('#flash-message').addClass('info-message green').slideDown('slow');		
					});					
				}
			}
		});			
	});	
	
	$('.remove-from-wishlist').click(function () {
		$.ajax({
			url: _root + 'users/xhr',
			data: 'method=remove_from_wishlist&id=' + $('#product-id').val(),
			success: function(response){
				if (response.indexOf('success') != -1) {
					$('#flash-message').slideUp('slow', function () {
						$(this).removeClass('orange');
						message = response.split('::');
						$('.remove-from-wishlist').hide();
						$('.add-to-wishlist').show();
						$('#flash-message strong').html(message[1]);
						$('#flash-message').addClass('info-message green').slideDown('slow');
					});
				}
			}
		});			
	});	
	
});

function carouselMainCallback(carousel) {
    jQuery('#main-banner .pager-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });
};

function carouselSizesCallback(carousel) {
    jQuery('#category-header .filter .size label a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('rel')));
        return false;
    });
};
