
$( document ).ready( function(){

	
	/**
	 * delete item from cart button observer
	 */
	$('#cart dd a.delete').live( 'click', function(){
		
		var oLink = $(this);
		if( document.getElementById( 'confirmDelete' ) ){
			$('#confirmDelete').slideUp('fast', function(){ 
				$(this).prev().show();
				$(this).remove(); 
				
				showConfirmDelete( $(oLink) );
			});
		} else {
			showConfirmDelete( $(oLink) );
		}
		return false;
	});


	/**
	 * add item to cart
	 */
	$('.product-info ul a').live( 'click', function(){
		
		var quantity = $( this ).parent(0).prev().find( 'input[name=quantity]' ).val();
		var idProduct = $( this ).attr( 'href' ).replace( 'id:', '' );
		
		/**
		 * update cart
		 */
		$.ajax({
		   type: 'POST',
		   url: '/ajax/product/addToCart',
		   data: 'data[id]='+idProduct+'&data[quantity]='+quantity,
		   success: function( responseText ){
				$( '#cart' ).replaceWith( $( responseText ) );
				
		   },
		   complete: function(){
			$.scrollTo($('#cart'), 500);
			/**
			 * blink updated cart item
			 */
			$('.changed').animate(
						{
							'backgroundColor': '#a8e357', 
							'opacity': 1
						}, 'slow', "linear", 
						function(){
							$('.changed').animate(
								{
									'backgroundColor': '#007CB7', 
									'opacity': 1
								}, 'slow', "linear"
							);
						});
				
		   }
		   
		 });
		

		return false;
	});
	

	/**
	 * change item amount on cart
	 */
	$( '#cart a:contains("zmień")' ).live( 'click', function(){
		$(this).prev('span').html( 'sztuk: <input type="text" name="quantity" title="wpisz ilość sztuk" size="3" maxlength="2" value="'+$(this).prev('span').html().replace('sztuk: ', '' )+'" id="changeQuantity"/> <a href="'+$(this).attr('href')+'">zapisz</a>' );
		$('#changeQuantity').focus();
		$(this).remove();
		
		/**
		 * change amount button observer
		 */
		$( '#cart a:contains("zapisz")' ).click( function(){
			/**
			 * update cart
			 */
			var idProduct = $( this ).attr( 'href' ).replace( 'id:', '' );;
			var quantity = $( this ).prev('input[name="quantity"]').val();
			
			$.ajax({
			   type: 'POST',
			   url: '/ajax/product/changeCartItemAmount',
			   data: 'data[id]='+idProduct+'&data[quantity]='+quantity,
			   success: function( responseText ){
					$( '#cart' ).replaceWith( $( responseText ) );
					
			   },
			   complete: function(){
				
				/**
				 * blink updated cart item
				 */
				$('.changed').animate(
							{
								'backgroundColor': '#a8e357', 
								'opacity': 1
							}, 'slow', "linear", 
							function(){
								$('.changed').animate(
									{
										'backgroundColor': '#007CB7', 
										'opacity': 1
									}, 'slow', "linear"
								);
							});
				
			   }
			   
			});
			return false;
		});
		return false;
	});
		
		
	/**
	 * item details window options
	 */
	var fancyOpts;
	
	if( document.getElementById( 'shop-wrapper' ) ){
		fancyOpts = {
			overlayOpacity: 0.8,
			padding: 0,
			idOuter				: 	'product-details-outer',
			idOverlay			:	'product-details-overlay',
			idWrap				: 	'product-details-wrap',
			idClose				:	'product-details-close',
			idTitle				:	'product-details-title',
			idInner				: 	'product-details-inner',
			idContent			:	'product-details-content',
			idAjax				:	'product-details-ajax',
			frameWidth			: 	800,
			frameHeight			:	500
		};
	}
	$.fn.fancybox.build( $.extend({}, $.fn.fancybox.defaults, fancyOpts ) );
	$( '.product-info .more' ).fancybox( fancyOpts );
	$( '.product-info h4 a' ).fancybox( fancyOpts );
	
	/**
	 * item image window options
	 */
	var fancyOpts;
	
	if( document.getElementById( 'shop-wrapper' ) ){
		fancyOpts = {
			overlayOpacity: 0.8
		}
		$.fn.fancybox.build( $.extend({}, $.fn.fancybox.defaults, fancyOpts ) );
		$( '.product-info .fancybox' ).fancybox( fancyOpts );
	}	
	
	
	
	/**
	 * order button observer
	 */
	if( document.getElementById( 'shop-wrapper' ) ){
		fancyOpts = {
			overlayOpacity: 0.8,
			padding: 0,
			idOuter				: 	'order-outer',
			idOverlay			:	'order-overlay',
			idWrap				: 	'order-wrap',
			idClose				:	'order-close',
			idTitle				:	'order-title',
			idInner				: 	'order-inner',
			idContent			:	'order-content',
			idAjax				:	'order-ajax',
			frameWidth			: 	840,
			frameHeight			:	600,
			hideOnContentClick	:	false,
			callbackOnShow		:	function(){
				
				initGUI();
				
				$('#order-form-data li:last-child div.row').hide();
				$('#order-form-data li:last-child input#isDelivery').click(function(){
					if( $(this).attr('checked') == true ){
						$('#order-form-data li:last-child div.row').show();
					} else {
						$('#order-form-data li:last-child div.row').hide();
					}
				});
				
				$( "#order-form-data" ).easySlider({
					controlsBefore:	'<div id="controls">',
					controlsAfter:	'<div class="clear"></div></div>',	
					prevId: 'prevBtn',
					nextId: 'nextBtn'	
				});
				
				
				$( '#isInvoice1' ).click( function(){
					if( $(this).attr('checked') == true ){
						$('#company').show();
						$('#NIP').show();
					}
				});
				
				$( '#isInvoice2' ).click( function(){
					if( $(this).attr('checked') == true ){
						$('#company').hide();
						$('#NIP').hide();
					}
				});
				
				$('#order-form table tbody tr:even').addClass( 'odd' );
				$( '#order-form table tbody tr td a:contains("zmień")' ).click( function(){
					/**
					 * update cart
					 */
					var idProduct = $( this ).attr( 'href' ).replace( 'id:', '' );;
					var quantity = $( this ).prev('input[name="quantity"]').val();
					var oRow = $( this ).parents('tr');
					var oCell = $( this ).parents('td');
					$.ajax({
					   type: 'POST',
					   url: '/ajax/order/changeCartItemAmount',
					   data: 'data[id]='+idProduct+'&data[quantity]='+quantity,
					   success: function( responseText ){
							var oResponse = $.evalJSON( responseText );
							$(oCell).next().html( number_format( oResponse.total, 2, ',', ' ' ) + ' pln' );
							$(oCell).next().next().html( number_format( oResponse.totalTax, 2, ',', ' '  ) + ' pln' );
							
							$('#order-form table tfoot tr td:nth-child(2)').html(number_format( oResponse.summary.total, 2, ',', ' ' ) + ' pln');
							$('#order-form table tfoot tr td:nth-child(3)').html(number_format( oResponse.summary.totalTax, 2, ',', ' ' ) + ' pln');
					   },
					   complete: function(){
							/**
							 * blink updated cart item
							 */
							if( quantity == 0 ){
								$(oRow).css( { 
									'backgroundColor': '#d70000',
									'color' : '#fff'
								} );
								$(oRow).fadeOut( 1500, function(){
									$(oRow).remove();
								});
								
							} else {
								var color = $(oRow).css('background-color');
								$(oRow).animate(
											{
												'backgroundColor': '#a8e357', 
												'opacity': 1
											}, 'slow', "linear", 
											function(){
												$(oRow).animate(
													{
														'backgroundColor': color, 
														'opacity': 1
													}, 'slow', "linear"
												);
											});
							}
					   }
					   
					});
					$.ajax({
					   type: 'POST',
					   url: '/ajax/order/refreshCart',
					   success: function( responseText ){
						$('#cart').replaceWith( responseText );
					   }
					});
					
					
					return false;
				});
				$( '#order-form table tbody tr td a:contains("usuń")' ).click( function(){
					/**
					 * update cart
					 */
					var idProduct = $( this ).attr( 'href' ).replace( 'id:', '' );;
					var oRow = $( this ).parents('tr');
					var oCell = $( this ).parents('td');
					$.ajax({
					   type: 'POST',
					   url: '/ajax/order/deleteCartItem',
					   data: 'data[id]='+idProduct,
					   success: function( responseText ){
							var oResponse = $.evalJSON( responseText );
							$(oCell).next().html( number_format( oResponse.total, 2, ',', ' ' ) + ' pln' );
							$(oCell).next().next().html( number_format( oResponse.totalTax, 2, ',', ' '  ) + ' pln' );
							
							$('#order-form table tfoot tr td:nth-child(2)').html(number_format( oResponse.summary.total, 2, ',', ' ' ) + ' pln');
							$('#order-form table tfoot tr td:nth-child(3)').html(number_format( oResponse.summary.totalTax, 2, ',', ' ' ) + ' pln');
					   },
					   complete: function(){
							/**
							 * blink updated cart item
							 */
							
							$(oRow).css( { 
								'backgroundColor': '#d70000',
								'color' : '#fff'
							} );
							$(oRow).fadeOut( 1500, function(){
								$(oRow).remove();
							});
							
						}
					   
					});
					$.ajax({
					   type: 'POST',
					   url: '/ajax/order/refreshCart',
					   success: function( responseText ){
						$('#cart').replaceWith( responseText );
					   }
					});
					
					
					return false;
				});
			},
			
			callbackOnClose:	function(){
				$.ajax({
				   type: 'POST',
				   url: '/ajax/order/refreshCart',
				   success: function( responseText ){
					$('#cart').replaceWith( responseText );
				   }
				});
			}
		};
	}
	$.fn.fancybox.build( $.extend({}, $.fn.fancybox.defaults, fancyOpts ) );
	$( '#order' ).fancybox( fancyOpts );
	
	
	
});

/**
 * show confirm message
 * @param object delete link
 */
function showConfirmDelete( oLink ){
	var delLink = $(oLink);
	$(oLink).hide();
	$('<div id="confirmDelete" style="display:none;"><p>Czy napewno usunąć produkt z koszyka?</p><p><a href="'+$(oLink).attr('href')+'" id="yes">usuń</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" id="no">nie usuwaj</a></p></div>').insertAfter( $(oLink) );
	$('#confirmDelete').slideDown( 'fast' );
	/**
	 * confirm window NO (don't delete) button observer
	 */
	$('#no').live( 'click', function(){
		$('#confirmDelete').slideUp('fast', function(){ 
			$(this).prev().show();
			$(this).remove(); 
			
		});
		
		
		return false;
	});
	
	/**
	 * confirm window YES (delete) button observer
	 */
	$('#yes').bind( 'click', function(){
		
		/**
		 * delete item from cart
		 */
		$.ajax({
		   type: 'GET',
		   url: $(this).attr('href'),
		   success: function( responseText ){
				$( '#cart' ).replaceWith( $( responseText ) );
			}

			});
			
		return false;
	});
}
