﻿$(function() {
	var ajaxUrl = 'cms/cfc/cart.cfc', 
		$ajaxButton = $('.ajaxButton'), 
		$cart;
	
	var qty = $('<input>')
				.addClass('qty')
				.attr('maxlength', 3)
				.attr('placeholder', 'Straws')
				.css({
					width : '40px',
					height : '12px',
					border : 'none',
					float : 'right',
					'margin-top' : '2px',
					'margin-right' : '7px',
					'font-size' : '10px',
					'text-align' : 'right'
				}).change(function(){					
					var $cThis = $(this);
					$cThis.css('border','none');
					
					if(parseInt($cThis.val(), 10) >= 0){
						try {
							$.ajax( {
								type : "get",
								url : ajaxUrl,
								contentType : "application/json; charset=utf-8",
								dataType : 'text',
								data : ( {
									method : "setItemQty",
									id : $cThis.parent().data('id') + '',
									amount : $cThis.val()
								}),
								success : function(response) {
								response = $.parseJSON(response.replace("UDsecure", ""));
								if (response.SUCCESS) {
									
										// console.log("removed " +
										// $cThis.parent().data('id'))
									} else {
										// console.log("Action was
										// unsuccessful please try
										// again: " + response.ERRORS)
									}
								},	error : function() {
									// console.log("There was a network
									// problem please try again");
								}
							})
						} catch (err) {
							alert(err);
						}
					} else {
						$cThis.css('border','1px solid #F00')
					}
				return false;
				})
	
	var removeButton = $('<a href="" />')
			.addClass('remove')
			.css('float', 'right')
			// .text('x')
			.click(	function() {
				var $cThis = $(this);
				try {
					$.ajax( {
						type : "get",
						url : ajaxUrl,
						contentType : "application/json; charset=utf-8",
						dataType : 'text',
						data : ( {
							method : "removeItem",
							id : $cThis.parent().data('id') + '',
							amount : 1
						}),
						success : function(response) {
						response = $.parseJSON(response.replace("UDsecure", ""));
						if (response.SUCCESS) {
							$cThis.parent().slideUp(
								'normal',
								function() {
									$(this).remove();
									var test = $cart.children(':not(.top, .close, .' + $cThis.parent().data('id') + ')');
									if (test.length <= 0) {
										$cart.slideUp();
									}
								});
								// console.log("removed " +
								// $cThis.parent().data('id'))
							} else {
								// console.log("Action was
								// unsuccessful please try
								// again: " + response.ERRORS)
							}
						},	error : function() {
							// console.log("There was a network
							// problem please try again");
						}
					})
				} catch (err) {
					alert(err);
				}
			return false;
			});

	$ajaxButton.filter('.add').after(
			$('<ul></ul>').addClass('cart').css( {
				'display' : 'none',
				'position' : 'absolute'
			}).append($('<li/>').addClass('top')).append(
					$('<li></li>').addClass('close').text('Close').click(function() {
								var href = $('.print')[0].href;
								if($cart.css('right') === '16px' && $cart.find('.empty').length == 0){
									window.open(href);
								}
								$cart.slideUp();
							})))

	$ajaxButton.click(function() {
		var $click = $(this), sId, sInfo;

		if (!(sId = (sInfo = $click[0].id).split('-')[1])) {
			if ($cart.children(':not(.top, .close)').length > 0) {
				sId = (sInfo = $ajaxButton.filter('.add')[0].id).split('-')[1];
				if ($cart.css('margin-left') === '16px') {
					$cart.slideUp(function() {
						$cart.find('.close').text('Print').css(
							'background-image',
							'url(img/add_print_ftr.gif)');
						$cart.css('margin-left', '168px').css('right','16px');
					});

				}
			} else {
				$cart.find('.close')
					.text('Close')
					.css('background-image','url(img/add_print_ftr.gif)')
					.before($('<li class="empty" />').text('Please add a sire'));
				$cart.css('margin-left', '168px').css('right','9px');
			}
			$cart.slideToggle();
		} else {
			$.ajax( {type : "get",
					url : ajaxUrl,
					contentType : "application/json; charset=utf-8",
					dataType : 'text',
					data : ( {
						method : "addItem",
						id : sInfo,
						amount : 0
					}),	success : function(response) {
						var wait = false;
						
						if ($cart.css('margin-left') === '168px') {
							function swapLeft() {
								$cart.find('.close').text('Close').css(
												'background-image',
												'url(img/add_ftr.gif)');
								$cart.css('margin-left','16px').css('right', '165px');
							
							}
							if($cart.css('display') != 'none'){	
								wait = true;
								$cart.slideUp({
									complete : swapLeft, 
									queue : 'cart'
								});
								$cart.dequeue('cart');
							} else {
									swapLeft();
							}
							
						}
						
						response = $.parseJSON(response.replace("UDsecure", ""));
						if (response.SUCCESS) {
							function slideUp(){
								var temp;
								if((temp = $cart.children('.empty')).length){
									temp.slideUp(function(){temp.remove()});
								}
							}
							if($cart.children('.' + sId).length == 0){ 
									
								$cart.children('.close')
									.before($item = $('<li />')
									.addClass(sId)
									.data('id',	sInfo)
									.text(sId)
									.css('display',	'none')
									.prepend((qty.clone(true)).val(''))	
									.prepend(removeButton.clone(true)));
							}
							
							if($item){
								if(wait || $cart.css('display') === 'none'){
									$cart.slideDown({queue : 'cart',
										complete : function(){
										$item.slideDown();
									}});
									$cart.dequeue('cart');
								} else {
									$item.slideDown();
								}
							}

							// console.log("Item added")
						} else {
							// console.log("Action was unsuccessful
							// please try again: " +
							// response.ERRORS)
							if(wait){
								$cart.delay(150,'cart').slideToggle({queue : 'cart'});
							} else {
								$cart.slideToggle();
							}
						}
				},error : function() {
					// console.log("There was a network problem
					// please try again");
				}
			});
		}

				return false;
			});

	$cart = $('.cart');

	$.ajax( {
		type : "get",
		url : ajaxUrl,
		contentType : "application/json; charset=utf-8",
		dataType : 'text',
		data : ( {
			method : 'sires'
		}),
		success : function(response) {
			response = $.parseJSON(response.replace("UDsecure", ""));
			for ( var i = 0; i < response.DATA.length; i++) {
				var spData = response.DATA[i].split('-');
				$cart.children('.close').before(
						$('<li></li>').addClass(i).data('id', response.DATA[i])
								.text(spData[1])
								.prepend((qty.clone(true)).val(spData[2] > 0 ? spData[5] : ""))
								.prepend(removeButton.clone(true)));
			}
		}
	})

});
