$(function(){
	// fix for edge case where modal pops then page is reloaded, causing inputs to be frozen in disabled state
	$('#aspnetForm input[type="text"]').each(function(){
		if($(this).attr('name').match(/qty/)){
			$(this).attr('disabled', '');
		}
	});
	
	if($('.cartItemProductName a').text().match(cp.stationery.pattern)){	
		$('#cartItems input[type="text"]').bind('blur', function(e){
			e.preventDefault();
			var items = $(this).closest('#cartItems').find('.cartItem'),
				problemItems = $([]);
			
			items.each(function(i,e){
				if($(this).find('.cartItemProductName a').text().match(cp.stationery.pattern)){
					var baseNum = 12;
					if(($(this).find('.tablebg').eq(0).find('input').val() % baseNum) !== 0){
						problemItems = problemItems.add($(this));
						$(this).data('problem', $(this).find('.cartItemProductNumber').text());
					}
				}
			});
			
			if(problemItems.length > 0){
				cp.modal.init(problemItems);
			}
		});
		$('#aspnetForm input[title="Update"], #aspnetForm input[title="Proceed to Checkout"], #aspnetForm input[alt="Proceed to Checkout"]').bind('click', function(e){
			e.preventDefault();
			var items = $('#aspnetForm').find('.cartItem'),
				problemItems = $([]);
			
			items.each(function(i,e){
				if($(this).find('.cartItemProductName a').text().match(cp.stationery.pattern)){
					/** create a base number for switch*/
					var baseNum = 12; //baseline number for flat cards 
					if(($(this).find('.tablebg').eq(0).find('input').val() % baseNum) !== 0){
						problemItems = problemItems.add($(this));
						$(this).data('problem', $(this).find('.cartItemProductNumber').text());
					}
				}
			});
			
			if(problemItems.length > 0){
				cp.modal.init(problemItems);
			} else {
				if($(e.target).attr('title') == 'Update'){
					// default "submit" event on this form results in update action
					$('#aspnetForm').submit();
				} else {
					// duplicate the targeting checkout button and fire click event on it, to avoid recursing back into this event
					var checkoutClone = $(e.target).clone();
					// title and alt removed to avoid triggering this calling event function, see .bind() line
					checkoutClone.attr('title','').attr('alt','').css('display','none');
					$('#aspnetForm').append(checkoutClone);
					checkoutClone.click();					
				}
			}
		});
	}
});

(function(){
	if(!window.cp){ cp = {}; }
	cp.stationery = {
		pattern: /(Flat\sCards)/
	};
	
	cp.modal = {
		// entry point for modal functions
		init: function(elems, arg){
			cp.modal.dialog(elems, arg);
		},
	
		// grey out the screen to prepare for dialog
		screen: function(){
			if($('#screen').length < 1){
				$('body').append('<div id="screen"></div>');
				$('#screen').animate({opacity:0.75,height:$(window).height()}, 600);
			} else if(!$('#screen').is(':visible')){
				$('#screen').animate({opacity:0.75,height:$(window).height()}, 600);
			}
		},
		
		// pop actual dialog box
		dialog: function(elems, arg){
			cp.modal.screen();
			
			
			
			if($('#dialog').length < 1){
				var baseNum = 12;
				$('body').append('<div id="dialog">'
								+ '<p><b>Oops, this product is only available in sets of 12(thus eliminating waste&hellip; cost-savings we pass on to you).</b></p>'
								+ '<p style="margin-bottom:5px;"><b>But please choose among these available quantities:</b></p>'
								+ '<div class="error">Please check a quantity option for each item below.</div>'
								+ '<table class="stationeryProblemItems" cellspacing="0"><thead><tr><td>New Quantity</td><td class="spacer">&nbsp;</td><td colspan="2">Item</td></tr><tbody></tbody></table>'
								+ '<a class="stationeryProblemSubmit" href="#" title="Save Changes">Save Changes</a>'
								+ '</div>'
							);
			
				elems.each(function(i,e){	
									
					var qty = parseInt($(this).find('.tablebg').eq(0).find('input').val(), 10),
						offset = qty % baseNum,
						diffDown = qty - offset <= 0 ? 0 : offset,
						diffUp = baseNum - offset,
						down = diffDown == 0 ? baseNum : qty - diffDown,
						up = qty + diffUp,
						thumb = $(e).find('td.tablebg').eq(1).find('a'),
						desc = $(e).find('td.tablebg').eq(2).find('.cartItemProductName a').text(),
						prodNum = $(e).find('.cartItemProductNumber').text();
					// prevent two instances of "12" being shown to the user for low quantities
					if(qty < baseNum){
						$('#dialog tbody').append('<tr class="stationeryProblemItem" id="stationeryProblemItemRadio"><td>'
													+ '<input type="radio" name="qty_'+i+'" value="'+up+'"/>'+up+' cards'
													+ '</td><td class="spacer"></td><td>'+thumb.parent().html()+'</td><td>'+desc+': '+prodNum+'</td></tr>'
												);
					} else {
						$('#dialog tbody').append('<tr class="stationeryProblemItem id="stationeryProblemItemRadio"><td>'
													+ '<input type="radio" name="qty_'+i+'" value="'+down+'"/>'+down+' cards<br/>'
													+ '<input type="radio" name="qty_'+i+'" value="'+up+'"/>'+up+' cards'
													+ '</td><td class="spacer"></td>'
													+ '<td>'+thumb.parent().html()+'</td><td class="desc">'+desc+': '+prodNum+'</td></tr>'
												);
					}
					$('#dialog .stationeryProblemItem').filter(':last').data('problem', prodNum);
				});
				
				$('.stationeryProblemSubmit').bind('click', function(e){
					e.preventDefault();
					var error = $(this).closest('#dialog').find('.error');
					error.hide();
					$('.stationeryProblemItem').each(function(i,e){
						var checked = false;
						$(this).find('input').each(function(){
							if(!checked && $(this).is(':checked')){
								checked = true;
							}
						});
						if(!checked){ error.show(); }
						if(i == ($('.stationeryProblemItem').length - 1) && !error.is(':visible')){
							$('.stationeryProblemItem').each(function(i,e){
								var self = $(this);
								var value = self.find('input:checked').val();
								$('.cartItem').each(function(i,e){
										if(self.data('problem') == $(this).data('problem')){
											$(this).find('td.tablebg').eq(0).find('input').val(value);
											//console.log($(this).find('td.tablebg').eq(0).find('input'));
											$(this).end();
										}
								});
							});
						}
					});
					// update cart to get new totals.
					cp.modal.kill();
					$('#aspnetForm input[title="Update"]').click();
				});
			} else if(!$('#dialog').is(':visible')){
				$('#dialog').fadeIn();
			}
			
			var offsetLeft = Math.floor((parseInt($(window).width(), 10) - $('#dialog').width()) / 2),
				offsetTop = Math.floor((parseInt($(window).height(), 10) - $('#dialog').height()) / 2);
			$('#dialog').css({'left':offsetLeft, 'top':offsetTop});
			// prevent editing of other cart items once the modal has popped
			$('#aspnetForm input[type="text"]').each(function(){
				if($(this).attr('name').match(/qty/)){
					$(this).attr('disabled', 'disabled');
				}
			});
		},
		
		// kill screen & dialog
		kill: function(){
			 //re-enable quantity editing when we kill the modal
			$('#aspnetForm input[type="text"]').each(function(){
				if($(this).attr('name').match(/qty/)){
					$(this).attr('disabled', '');
				}
			});
			$('#screen').remove();
			$('#dialog').remove();
		}
	};
})();
