/* Cart.js */

/* Globals for ajax-cart */
var cartUrl = 'page/1/ajax-cart'; //REMEMBER TO CHECK FOR CORRESPONDING PAGE ID
var alertEnabled = true;

$(function() {
		
		/* User registration during ordering */
		$('#show-password-fields').click(function() { $(this).closest('tr').nextAll().toggle(); });
		if($('#show-password-fields:checked').length > 0) { $('#show-password-fields:checked').closest('tr').nextAll().show(); }

		/* Order has different recipient */
		$('#show-recipient-table').click(function() { $('#recipient-table').toggle(); });
		if($('#show-recipient-table:checked').length > 0) { $('#recipient-table').show(); }

		/* Show bottom-cart content */
		$('#bottom-cart-text-field').live('click', function() { 
				$(this).toggleClass('up');
				$('#select-arrow').toggleClass('select-arrow-down');
				$('#bottom-cart-item-list').slideToggle(250);
		});
        
		/* Change product amount in cart step 1 */	
		$('.amount-input').keyup(function() {
				alertEnabled = true;
				var elem = $(this);
				elem.val(elem.val().replace(/[^0-9]+/, ''));
				if(elem.val() === "" || parseInt(elem.val(),10) === 0) { elem.val(1); }
				updateCartAmounts(elem, alertEnabled);
		});
				
		/* Ajax-cart event */		
		$('.add2cart').click(function() {
				var $this = $(this),
				dataString = null,
				$amountElem = $('.amount-select'),
				$variationElems = $('.variation');
				$this.closest('form').find('img').eq(0).add2cart();
				if($variationElems.length > 0) { 
						var variations = $variationElems.map(function() {
								return $(this).attr('name') + "=" + ($(this).val()) ;
						}).get().join('&');
				}
				dataString = $this.attr('name') + '=x&amount[' + $amountElem.data('product-id') + "]=" + $amountElem.val();
				if(variations != undefined) { dataString += "&" + variations; }			
				updateBottomCartText();
				$.ajax({
						type: 'POST',  
						url: '/cart/add?ajax=1',  
						data: dataString,
						success: function() {
							$('#bottom-cart-content').load(cartUrl + ' #bottom-cart-text-field', function() {
								$('#bottom-cart-text-field').effect('highlight',{},1500, function() {
										toggleBottomCart();
										updateTopCart();
										setTimeout(function() { toggleBottomCart(); }, 1500);
								});
							});
						}
				});
				
				return false;
		});

});

function toggleBottomCart() { 
  $('#bottom-cart-item-list').slideToggle(250); 
}

function updateBottomCartText() { 
  $('#bottom-cart-item-text').text('Päivitetään...'); 
}

function updateTopCart() {
 if($('.cart-status').length > 0) 
  { $('.cart-status').html($('#bottom-cart-item-text').html());
 }
}

/* Change product amount in cart step 1 */	
function updateCartAmounts(elem, alertEnabled) {
		var dataString = elem.attr('name') + '=' + elem.attr('value') + '&ajax=1',
		val = elem.val();
		elem.parents('tr').animate({opacity: 0.3},250);
		updateBottomCartText();
		$.ajax({
			type: 'POST',  
			url: elem.closest('form').attr('action'),
			data: dataString,
			dataType: 'json',
			success: function(data) {
				elem.parents('tr').animate({opacity: 1},250);
				var amount = data[elem.attr('name') + '_amount'];
				$('#total-amount').text(data.total);				
				if (parseInt(val) > parseInt(amount)) {
					if (alertEnabled) {
						alertEnabled = false;
						alert('Tuotetta saatavilla vain ' + amount + ' kpl.');
					}
				}
				elem.val(amount);
				elem.parents('tr').find('.row-amount').html(data[elem.attr('name') + '_total']);
				$('#bottom-cart-content').load(cartUrl + ' #bottom-cart-text-field', function() {
						$('#bottom-cart-text-field').effect('highlight',{},1500);
						updateTopCart();
				});
			}
		});
}

(function($) {

		$.fn.add2cart = function(opts) {
				var settings = {
						source : $(this),
						target : $('#target'),
						opacity: 0.3,
						animationSpeed: 800,
						fadeoutSpeed: 300,
						callback: function() {}
				};

				if(opts) { $.extend(settings, opts); }

				var shadow = $('<div/>', {
						css: {
								display: 'none',
								backgroundColor: '#fff',
								border: '1px solid #CFDDB1',
								top: '0px',
								position: 'static',
								zIndex: 10000
						},
						html: $('<img>', {
								src: settings.source.attr('src'),
								width: '100%'
						})
						}).prependTo('body');
				shadow.width(settings.source.css('width')).height(settings.source.css('height'))
				.css({
						top: settings.source.offset().top,
						left: settings.source.offset().left,
						opacity: settings.opacity
				})
				.show();
				shadow.css('position', 'absolute');
				shadow.animate({ 
						width: settings.target.innerWidth(), 
						height: settings.target.innerHeight(), 
						top: settings.target.offset().top, 
						left: settings.target.offset().left 
				}, { duration: settings.animationSpeed }).animate({ opacity: 0 }, { duration: settings.fadeoutSpeed, complete: settings.callback });
		};
})(jQuery);

