/**
 * Resizes floated image containers to the size of the image
 */
$.fn.imageWidth = function(threshold) {
	var	resizeImage = function($image, $parent, $container) {
		// Determine the width of the image along with borders and padding
		var imageWidth = $image.width();
		var paddingLeft = parseInt($image.css('padding-left').replace('px', ''), 10);
		var paddingRight = parseInt($image.css('padding-right').replace('px', ''), 10);
		var borderLeft = parseInt($image.css('border-left-width').replace('px', ''), 10);
		var borderRight = parseInt($image.css('border-right-width').replace('px', ''), 10);

		// Calculate total edge (padding and border) width and the total width (edge and image)
		var edgeWidth = paddingLeft + paddingRight + borderLeft + borderRight;
		var totalWidth = imageWidth + edgeWidth;

		// Determine parent width
		var parentWidth = $parent.width();

		// If the image is greater then the threshold times the parent width resize the image and the container width
		// Otherwise set the image left's div to the size of the image plus the edge
		if ((threshold * parentWidth) <= totalWidth) {
			var revisedWidth = parentWidth * threshold;
			var revisedImageWidth = revisedWidth - edgeWidth;

			$image.width(revisedImageWidth);
			$container.width(parseInt(revisedWidth, 10));
		} else {
			$container.width(totalWidth);
		};
	};

	return this.each(function() {
		// Threshold is the maximum width an image plus its border and padding can be 
		// in relation to its parent container
		var threshold = (threshold) ? threshold : 2/3;

		// Find image within div
		var $image = $('img', $(this));
		var $parent = $(this).parent();
		var $container = $(this);

		$image.each(function(index) {
			resizeImage($image, $parent, $container);
			$(this).load(function() {			
				resizeImage($image, $parent, $container);
			});
		});
	});		
};

/**
 * Builds pull quote divs assuming you've wrapped your content with a span with the class: pullquote-left or pullquote-right
 */
$.fn.pullQuote = function() {
	return this.each(function() {
		var contents = $.trim($(this).html());
		var firstCharacterCode = contents.charCodeAt(0);
		if (firstCharacterCode < 65 || firstCharacterCode > 96) {
			contents = '&hellip; ' + contents;
		};
		
		var lastCharacter = contents.charAt(contents.length - 1);
		if ("?!.".search(lastCharacter) < 0) {
			contents = contents + ' &hellip;';
		};
		var $parent = $(this).parent();
		var $pullquote = $('<div>').attr('class', $(this).attr('class')).html(contents);
		$parent.before($pullquote);
	});		
};

/**
 * Clears a text form element when it has the style 'clear-default'
 */
$.fn.clickClear = function() {
	return this.each(function() {
		this.defaultValue = $(this).val();
		$(this).click(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).focus(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).blur(function() {
			if ($(this).val() == "") {
				$(this).val(this.defaultValue);
			};
		});
		
		$('form').submit(function(event) {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		});
	});	
};

// Checks if a selector exists
$.fn.exists = function(){return jQuery(this).length>0;}

var markupPrep = function() {
	var listPrep = function() {
		$('> li:last', 'ul, ol').addClass('last');
	};
	
	var	tablePrep = function() {
		$('table tr:odd').addClass('alt');
		$('table td:last, table th:last').addClass('last');
	};
	
	listPrep();
	tablePrep();
};

// Loads in Modernizr script which checks for CSS3 capabilities
$('body').ready(function() {
	$.getScript('/js/modernizr.min.js');
});

$(document).ready(function() {
	$('input.clear-default').clickClear();
	$('div.image-left, div.image-right').imageWidth();
	$('span.pullquote-left, span.pullquote-right').pullQuote();
	
	markupPrep();
	
	// Funtions specific to BMO
	hideProductsCatalogues ();
	a_z_list ();
	if ($('.productTextarea').size()){
		$('#additional_options').show();
	}
	
	showViewCart();
	rewriteEmptyCart();
	navListener('#nav_14623 li a');
        navListener('#nav_906558 li a');
	navListener('#nav_1194553 li a');
	navListener('#nav_1202928 li a');
	toggleWholesaleApp();
	togglePaymentOptions ('PaymentMethodType');
});


// Hides categories or products depending on if they exist
function hideProductsCatalogues () {
	$(".productTable").has(".productItemNotFound").hide();
	if($(".catalogueTable").has(".catalogueItemNotFound").hide().length) {
			$(".category-description").hide();
	}else{
		$(".catalog-top-description").hide();
	}
}

// Create list and menu for a-z list page
function a_z_list () {
	
	if($('.a-z-list .catalogueitemdump').exists()) {
		$('.a-z-list .catalogueitemdump').attr('id', 'catalogueitemdump');
	    $('.a-z-list #catalogueitemdump').listmenu({ 
	      includeNums: false, 
	      includeOther: false, 
	      flagDisabled: true, 
	      noMatchText: 'Sorry, there are no products for this letter.', 
	      showCounts: false, 
	      menuWidth: 500, 
	      cols:{ 
	        count: 2, 
	        gutter: 15 
	      }
	    });

		$('.a-z-list #catalogueitemdump').load(function () {
			$('.lm-menu').css('display','block');
			$('.lm-menu .a ').css('display','block');

		});
	}
	


}

function navListener (element) {
	
		$(element).hover (
			
				function (event) {
					if($(this).siblings('ul').length > 0) {
						$(this).parent().attr("style","z-index:50");
						$(event.target).siblings().show();
						$(this).addClass('hover');
					}
				},
				function (event) {
					
					if($(this).siblings('ul').length > 0) {
						ul = $(event.target).siblings('ul');
						$(ul).hover (
							function () {
								$(this).siblings('a').addClass('hover');
								$(this).show();
								$(this).parent().attr("style","z-index:50");
							},
							function () {
								$(this).siblings('a').removeClass('hover');
								$(this).hide();
								$(this).parent().attr("style","z-index:20");
							}
						);

						$(ul).hide();
						$(this).removeClass('hover');
						$(this).parent().attr("style","z-index:20");
					}
				}
			
		);
}


// Replace ", Total:" with "|" for the cart info 
function replaceCartText () {
	text = $(".cartSummaryItem").html().replace(', Total:', ' |'); 
	text = text.replace('View', 'My');
	$(".cartSummaryItem").html(text);
}

function process_additional_options (){
	//  #catProdTd_1202118 (6 pack ice cream)  
	//  #catProdTd_1202119 (12 pack ice cream) 

	// If the id for the 6 or 12 pack exists, then process the options
	if ($('td#catProdTd_1202118').exists() || $('td#catProdTd_1202119').exists()) {
		
		if ($('td#catProdTd_1202118').exists() && !$('#tabs td#catProdTd_1202118').exists()) {
			 total_quantity = 6;
		} 
		else if ($('td#catProdTd_1202119').exists() && !$('#tabs td#catProdTd_1202119').exists()) {
			 total_quantity = 12;
		}

	 	chocolate = $('#flavor_chocolate').val();
	 	vanilla = $('#flavor_vanilla').val();
	 	cappucino = $('#flavor_cappucino').val();
	 	mint_cacao_chip = $('#flavor_mint_cacao_chip').val();
	 	mango = $('#flavor_mango').val();
	 	strawberry = $('#flavor_strawberry').val();
	 	date = $('#flavor_date').val();
	 	total = parseInt(chocolate)+parseInt(vanilla)+parseInt(cappucino)+parseInt(mint_cacao_chip)+parseInt(mango)+parseInt(strawberry)+parseInt(date); 
		
		if (total != total_quantity) {
			alert("You chose "+total+" flavors.  Please choose a total of "+total_quantity+" flavors.");
			$('input.productSubmitInput').detatchEvent('onclick', 'AddToCart');
			return false;
		} 
		
		var flavors = '';
		flavors+='Chocolate: '+chocolate+"\n";
		flavors+='Vanilla: '+vanilla+"\n";
		flavors+='Cappucino: '+cappucino+"\n";
		flavors+='Mint Cacao Chip: '+mint_cacao_chip+"\n";
		flavors+='Mango: '+mango+"\n";
		flavors+='Strawberry: '+strawberry+"\n";
		flavors+='Date Cream: '+date+"\n";
		$('#additional_options_textarea > textarea').val(flavors); 
	
	}
}

function showViewCart () {
	if(!$(".cartSummaryItem").has(".cartSummaryLink").length) {
		html = '<a href="/OrderRetrievev2.aspx?CatalogueID=0" class="cartSummaryLink">View Cart</a>';
		$(".cartSummaryItem").append(html);
	}
}

function rewriteEmptyCart () {
	html = '<div id="content-main-header" class="group"><h1>Your Shopping Cart</h1></div><p>Currently there are no items in your cart. Are you looking for something in particular? You can continue browsing or, search for a particular item.</p><form style="float:left;margin: 0;" class="search" action="/store/search-results.htm?SiteSearchID=-1&amp;PageID=430215" method="get" accept-charset="utf-8"><p> <input type="text" class="cat_textbox_small" name="CAT_Search" id="keywords"><input type="submit" name="submit" value="Go" id="submit"> </p> </form>';
	if($("#catCartDetails .cartLink").size()) {
		$("#catCartDetails").html(html);
	}
}

function toggleWholesaleApp () {
	if($('.wholesale-application').length) {
		// Check on load (incase we have cached values)
		if($('.ApplyForMembership:checked').val() == 'yes') {
			$('#Membership').show();
		} 
		else {
			$('#Membership').hide();
		}
		if($('.applyforterms:checked').val() == 'yes') {
			$('#CreditTerms').show();
		} 
		else {
			$('#CreditTerms').hide();
		}
	
		// On clicks
		$('.applyforterms').click(function(event) {
			if($(this).val() == 'yes') {
				$('#CreditTerms').show();
			} 
			else {
				$('#CreditTerms').hide();
			}
		});
			$('.ApplyForMembership').click(function(event) {
				if($(this).val() == 'yes') {
					$('#Membership').show();
				} 
				else {
					$('#Membership').hide();
				}
			});
		
	}
	
}

function togglePaymentOptions (controls) {
	 $(".details-payment-2").hide();
	
	  $("[name="+controls+"]").each(function(i) {

	    $(this).change(function(){

		  paymentNumber = $(this).val();
	      className = 'details-payment-'+paymentNumber;
	
	      $(".details-payment-1").hide();
		  $(".details-payment-2").hide();
	
	      $("."+className).show('slow');
	
	    });
	
	  });
	
}

