$(document).ready(function() {


	/*$('#navigation #categories ul').not('#everything ul').hide();
	
	$('#navigation .main_category').hover(function() {
		//$('#categories ul li').not('ul li', this).hide();
		$('ul', this).slideDown('fast');
	}, function() {
		$('ul', this).slideUp('slow');
	});*/




	hideInputValue($('#search'));
	
	
	
	var addToCartButton = $('.add_to_cart_button:first .action').html();
	if (typeof(sizeSelector) != "undefined") {
		if (sizeSelector != 'off') { var originalPleaseChooseText = $('.size .action .please_choose:first').text(); }
		if (sizeSelector == 'diameter') { var originalDiameterSelector = $('.size .action:first').html(); }
	}

	
	
	$('.color_selector li').click(function() {
	
		$('.color_selector li').removeClass('selected');
		$(this).addClass('selected');
		
		var id = $(this).attr('id');
		var idParts = id.split('_');
		what = idParts[0];
		variationId = idParts[1];
		colorName = $('img', this).attr('alt');
		
		$('#single_product_image div > div').hide();
		$('#single_product_image div#image_' + id + "_1").fadeIn(500);
		buildImageShifter(what, variationId);
		
		var cartbox = $(this).parents('.cartbox');
		
		price = variations[what][variationId]['price'];		
		cartbox.find('.the_price span').text(price);
		cartbox.find('.the_price').animate({backgroundColor: '#ffca74'}, 70).animate({backgroundColor: '#ffffff'}, 400);
		
		$('.add_to_cart_button .action').html('');
		cartbox.find('.add_to_cart_button .action').html(addToCartButton);
		
	
		if (sizeSelector != 'off') {		
			
			if (originalPleaseChooseText != "") {
				$('.size .action').html('<div class="please_choose">' + originalPleaseChooseText + '</div>');
			}			
			
			if (sizeSelector == 'sizes') {		
				var sizes = variations[what][variationId]['sizes'];
				var sizesHtml = '<ul>';
				var countSizes = 1;
				$.each(sizes, function(key, value) {
					if (countSizes == 1) selected = ' class="selected"'; else selected = '';
					sizesHtml += '<li id="' + value + '"' + selected + '>' + value + "</li>";
					countSizes++;
				});
				sizesHtml += '</ul>';
				cartbox.find('.size .action').html(sizesHtml);			
			}			
			
			if (sizeSelector == 'diameter') {
				cartbox.find('.size .action').html(originalDiameterSelector);
			}
			
		}
	
	});
	
	
	
	$('.add_to_cart').live('click', function() {
	
		var inputDiameter = $("input[name='diameter']");
		var inputDiameterValue = inputDiameter.val();
	
		if (sizeSelector == 'off' || sizeSelector == 'sizes' || (sizeSelector == 'diameter' && inputDiameterValue != '')) {
		
			if (sizeSelector == 'diameter') size = inputDiameterValue + ' ' + $('.size_unit').text();
			
			var productData = {
				'postId': postId,
				'variationId': variationId,
				'name': productName,
				'price': price,
				'what': what,
				'size': size,
				'colorName': colorName,
				'categoryName': categoryName,
				'categorySlug': categorySlug,
				'permalink': permalink
			};
		
			$.ajax({  
				type: 'POST',
				url: '/wp-content/themes/felvarrom/add_to_cart.php',
				data: productData,
				success: function(response) {
					//console.log(response); /// D E L E T E ! ! !! ! !		 
				},
				error: function() {
					//console.log('Error.');
				}
			});
			
			showAdded();
			updateCart();    	
	    
	    	if (sizeSelector == 'diameter') size = '';
	    	inputDiameter.val('');
    
    	} else {
    	
    		alert('Please enter the size!');
    	
    	}    
    
	    return false;
	
	});
	
	
	
	$('.size li').live('click', function() {
	
		$('.size li').removeClass('selected');
		$(this).addClass('selected');
		size = $(this).attr('id');
	
	});
	
	
	
	$(document).keyup(function(event) {
		if (event.keyCode == 27) { 
			if ($('#added').is(':visible')) {
				hideAdded();
			}
		}
	});
	
	
	
	$('#the_order_button').mouseenter(function() {

		  for (var x = 1; x <= 3; x++) {
			$('#order_button').animate({ backgroundPosition: '0 0' }, 60)
				.animate({ backgroundPosition: '5px 3px' }, 60)
				.animate({ backgroundPosition: '3px 0' }, 60);
			}
		
	});
	
	
	
	validateOrderForm();
	
	
	
	$('#currency').css('opacity', 0.6);
	$('#currency').hover(function() {
		$(this).stop().animate({ 'opacity': 1 }, 10);
	}, function() {
		$(this).stop().animate({ 'opacity': 0.6 });
	});
	
	
	
	var countryId;
	var paymentMethod;

	
	$('#country').change(function() {
		
		// Reset values
		$('#payment_method div').html('Choose your country above!');
		$('#delivery_via div').html('Firstly, choose the payment method!');		
		$('.delivery_cost span').text('0');
		$('input[name="delivery_cost"]').val(0);
		$('.total span').text($('.subtotal span').text());
		$('input[name="total_cost"]').val($('.subtotal span').text());
		
		countryId = $(this).val();
		var country = $('#country [value="' + countryId + '"]').text();		
		$('input[name="country_name"]').val(country);
	
		if (countryId && countryId != 0) {
			$('#payment_method div').load('/wp-content/themes/felvarrom/payment_method.php?countryId=' + countryId, function() {				
				$('input[name="payment"]').rules('add', 'required');
			});
		}
		
	});
	
	$('.payment_method').live('change', function() {
		
		// Reset values
		$('.delivery_cost span').text('0');
		$('input[name="delivery_cost"]').val(0);
		$('.total span').text($('.subtotal span').text());
		$('input[name="total_cost"]').val($('.subtotal span').text());
		
		paymentMethod = $(this).val();
		$('input[name="order_payment"]').val(paymentMethod);
		$('#delivery_via div').load('/wp-content/themes/felvarrom/delivery_via.php?countryId=' + countryId + '&payment=' + paymentMethod, function() {				
			$('input[name="delivery"]').rules('add', 'required');
		});
		
	});
	
	$('.delivery_via').live('change', function() {
		
		var delivery = $(this).val();
		$('input[name="order_delivery"]').val(delivery);
		$('.delivery_cost span').load('/wp-content/themes/felvarrom/delivery_cost.php?countryId=' + countryId + '&payment=' + paymentMethod + '&delivery=' + delivery, function(){
			var deliveryCost = parseFloat($('.delivery_cost span').text());
			var totalCost = parseFloat($('.subtotal span').text()) + deliveryCost;
			$('.total span').text(totalCost);
			$('input[name="total_cost"]').val(totalCost);
			$('input[name="delivery_cost"]').val(deliveryCost);
		});		
		
	});
	
	

});



function updateCart() {	

	$.get('/wp-content/themes/felvarrom/cart_count.php', function(data) {
		$('#cart').html('<span><a href="' + $('#checkout a').attr('href') + '">' + data);
	});	

}



function buildImageShifter(what, variationId) {
	
		var images = $('#images_' + what + ' div.variation_' + variationId);
		var imageShifter = $('#badass_image_shifter_shit_i_am_sick');
		
		imageShifter.html('<ul><li id="label_ya">More pictures</li></ul>');
	
		if (images.length > 1) {		
			
			for (i = 1; i <= images.length; i++) {
				$('ul', imageShifter).append('<li><a href="#" id="' + what + '_' + variationId + '_' + i + '">' + i + '</a></li>');
			}
			
			imageShifter.show();
			
			$('a', imageShifter).click(function() {
				$('#single_product_image div > div').hide();
				var id = $(this).attr('id');
				$('#single_product_image div#image_' + id).fadeIn(500);
                $('#badass_image_shifter_shit_i_am_sick a').removeClass('selected');
                $(this).addClass('selected');
				return false;
			});
			
		} else {
			
			imageShifter.hide();
			
		}	
        $('#badass_image_shifter_shit_i_am_sick a').first().addClass('selected');
}



function hideInputValue(element, defaultValue) {

	if (defaultValue == undefined) {
		defaultValue = element.val();
	}
	
	element.focus(function() {
		if (this.value == defaultValue) {
			this.value = '';
		}
	});
	
	element.blur(function() {
		if (this.value == '' || this.value == defaultValue) {
			this.value = defaultValue;
		}
	});

}



jQuery.fn.center = function () {
    
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + 'px');
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + 'px');
    return this;
    
}



function showAdded() {

	$('#overlay').height($(document).height());
	$('#added').center();
	$('#overlay').fadeIn(200);
	$('#added').fadeIn(300);
	$('#overlay').click(function() {
		hideAdded();
	});
	
}



function hideAdded() {
	
	$('#overlay').fadeOut(100);
	$('#added').fadeOut(500);
	
}



function validateOrderForm() {

	$('#order_form').validate({
		rules: {
    		email: {
				required: true,
				email: true
			},
			name: 'required',
			address_1: 'required',
			city: 'required',
			country: 'required',
			postal: 'required',
            accept: 'required'
			//faszomx: 'required',
			//kuss: 'required'
		},
		messages: {
			/*
			contact_email: {
				email: "Kérjük, valós e-mail címet adjon meg!",
				required: "Kérjük, adja meg az e-mail címét!"
			}, 
			company: "Kérjük, adja meg a cég nevét!",
			contact_name: "Kérjük adja meg a kapcsolattartó személy nevét!"
			
			*/
			//name: "Please!"
		}	
	});	
	
}
