(function($) {
	
	$(document).ready(function() {
		
		// Find the qty box from the qty change icons
		var change_row_total = function(qty) {
			return this.parent().find('input').val( qty );
		}
		
		var update_wishlist_count = function() {
			$.get("/wishpreview/index/wishlist_item_count", function(item_count) {
				$(".wishlist_count:first").html(item_count);	
			});
		}
		
		$('.remove-btn-wishpopup').live('click', function() {
			id = $(this).attr('data-wishid');
			data = "wishid=" + id;
			$.ajax({
				url : '/wishpreview/index/remove',
				type : 'GET',
				data : data,
				success : function(response) {
					updateWishPreview();
				}
			});
		});

		$('.wishhead').qtip({

			content : {
				text : $('#preview_loader_wish_default').html(), // The text to use whilst the AJAX request is loading
				ajax : {
					url : '/wishpreview', // URL to the local file
					type : 'GET', // POST or GET
					data : {}, // Data to pass along with your request
					success : function(data, status) {
						this.set('content.text', data);
						$('#preview_loader_wish').hide();
					}
				}
			},
			position : {
				at : "bottom right",
				my : "top right"
			},

			hide : {
				effect : function(offset) {
					$(this).hide();
					// "this" refers to the tooltip
				},
				fixed : true,
				delay : 200
			},

			show : {
				effect : function(offset) {
					$(this).show();
					// "this" refers to the tooltip
				},
				fixed : true
			}

		});

		$('.addwishqty').live('click', function() {
			var $this = $(this);
			id = $this.attr('data-id');
			data = "wishid=" + id + "&math=add";
			$.ajax({
				url : '/wishpreview/index/qty',
				type : 'GET',
				data : data,
				success : function(item_row_count) {
					updateWishPreview();
					change_row_total.call( $this, item_row_count);
				}
			});
		});

		$('.minuswishqty').live('click', function() {
			
			var $this = $(this);
			id = $this.attr('data-id');
			data = "wishid=" + id + "&math=minus";

			$.ajax({
				url : '/wishpreview/index/qty',
				type : 'GET',
				data : data,
				success : function(item_row_count) {
					updateWishPreview();
					change_row_total.call( $this, item_row_count);
				}
			});
		});
		showWishPreview = function() {
			updateWishPreview();
			$('.wishhead').qtip('toggle', true);
		}
		hideWishPreview = function() {
			$('.wishhead').qtip('toggle', false);
		}
		updateWishPreview = function() {
			$('.wishhead').qtip('toggle', true);
			obj = $('.wishhead').qtip();
			$('#preview_loader_wish').show();

			$.ajax({
				url : '/wishpreview',
				type : 'GET',
				success : function(response) {
					obj.set('content.text', response);
					$('#preview_loader_wish').hide();
					
					update_wishlist_count();
					
				}
			});

		}
	});
})(jQuery);

